Reputation: 1278
I am having a problem with PHP from that adds data to MYSQL database :
<?php require("config/connection.php"); ?>
<?php require("includes/functions.php"); ?>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$error='';// zmienna do błędów
if(isset($_POST[submit])){
if(trim($_POST[username])=='' || strlen(trim($_POST[username])) < 6 ||strlen(trim($_POST[username])) >12){
$error.="Name must be between 6 ad 12 chars<br />";
}
}if($error==''){ // if no error, do a query
$sql = @mysql_query("INSERT INTO users SET username=\"$username\", password=\"$password\"");
}
else {
echo "<span style=color:red>$error</span>";
}
mysql_close($connection);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<h2>Add user</h2>
<form action="add.php" method="post">
<p>Name: <input type="text" name="username" id="username" /></p>
<p>Password: <input type="text" name="password" id="password" /></p>
<p> <input type="submit" value="submit " name="submit" /></p>
</form>
<a href="index.php">Cancel</a>
</body>
</html>
The main problem is when I input username and password here is what I get:
http://i.padsbanger.pl/img/cdf5b5p988ga
For unknown reason it adds an empty row and after that it adds what I have trully inputed into my form. Any help ?
Upvotes: 0
Views: 1581
Reputation: 38147
You are executing the query twice, once on page load and then again on submit
$error='';
if(isset($_POST[submit])){
if(trim($_POST[username])=='' || strlen(trim($_POST[username])) < 6 ||strlen(trim($_POST[username])) >12){
$error.="Name must be between 6 ad 12 chars<br />";
}
}// closes if(isset *** move this until after the next if statement ***
//this is run everytime as its outside the if(isset block
if($error==''){ // errors is initialised as '' so this will run
$sql = @mysql_query("INSERT INTO users SET username=\"$username\", password=\"$password\"");
}
if(isset($_POST[submit])){
should be if(isset($_POST['submit'])){
SQL Injection - You should read this
Upvotes: 4