PHP& MySQL表单。添加空行

时间:2011-12-08 20:12:43

标签: php mysql forms row

我遇到了PHP的问题,因为它将数据添加到MYSQL数据库:

<?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>

主要问题是我在这里输入用户名和密码是我得到的:

http://i.padsbanger.pl/img/cdf5b5p988ga

由于未知原因,它会添加一个空行,之后它会将我所填写的内容添加到我的表单中。有什么帮助吗?

1 个答案:

答案 0 :(得分:4)

您正在执行查询两次,一次是在页面加载时,然后是再次提交

$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])){应为if(isset($_POST['submit'])){

SQL Injection - You should read this