简体   繁体   English

PHP和MySQL表格。 添加空行

[英]PHP & MySQL form. Adding empty row

I am having a problem with PHP from that adds data to MYSQL database : 我在使用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>

The main problem is when I input username and password here is what I get: 主要问题是,当我在此处输入用户名和密码时,得到的是:

http://i.padsbanger.pl/img/cdf5b5p988ga 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 ? 有什么帮助吗?

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

SQL Injection - You should read this SQL注入 -您应该阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM