我不能插入我的数据PHP的形式到mysql ??我的代码如下


i cannot insert my data of php form into mysql ?? my code is following?

<?php 
include 'db.php';
$serial= $_POST['serial'];
$date_of_reg = $_POST['date_of_reg'];
$name = $_POST['name'];
$doc_type = $_POST['doc_type'];
$sql = "INSERT INTO clients (serial,date_of_reg,name,doc_type) VALUES ('$serial','$date_of_reg','$name', '$doc_type');";
$result = mysql_query($sql, $link);
if ($result == false) {
    include "src/header.php";
    include "src/mainmenu.php";
    echo '<p>Error: cannot execute query</p>';
    echo '<p><a href="register.php">Try again</a></p>';
    include "src/footer.php";
    exit;
}
else {
    header('Location: private.php');
}
mysql_close($link);
?>

在没有检查错误的情况下假设成功,如果这样做,将会发出语法错误的信号,效果为:

你的SQL语法有错误;查看与MySQL服务器版本对应的手册,以便在'serial

附近使用正确的语法。

而在代码中使用or die(mysql_error())mysql_query()

使用MySQL的保留字,是serial(编辑)和name,但奇怪的是,许多人使用(名称)没有问题,包括我自己,这让我困惑。

  • https://dev.mysql.com/doc/refman/5.5/en/keywords.html

要么将其重命名为"serials",这样可以安全使用,要么将其包装在tick中:

INSERT INTO clients (`serial`, date_of_reg, `name`, doc_type)

全行重写:

$sql = "INSERT INTO clients (`serial`,date_of_reg, `name`, doc_type)  
        VALUES ('$serial','$date_of_reg','$name', '$doc_type');";
$result = mysql_query($sql, $link) or die(mysql_error());

你也应该转义你的数据,如果你输入的数据包含任何MySQL可能抱怨的东西。

例如: James O'Neil会导致撇号的问题。逃脱:

$name = mysql_real_escape_string($_POST['name']);

另外,关于SQL注入,这是你开放的,使用mysqli预处理语句,或PDO预处理语句它们更安全


错误报告添加到文件的顶部,这将有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code

旁注:错误报告应该只在登台阶段进行,而不应该在生产阶段进行。

如果你得到一个弃用通知,你会看到你必须做什么;切换到MySQLi或PDO,你应该这样做,因为它将从未来的PHP版本中删除。
领先于游戏


脚注:

因为你使用的表单是你没有发布的东西,确保它使用post方法,所有输入都有"name"属性,没有打字错误。一个见解。

即:

<form action="" method="post">
<input type="text" name="serial">
...
</form>

等。编辑:

根据您为表单留下的链接:

<input type="text" name="name" id="serial" />

应该读作<input type="text" name="serial" id="serial" />,你使用了"name"而不是"serial",错误报告会发现这一点。

然后再次使用<input type="text" name="name" id="date_of_reg" />,使用错误的名称属性,为"name"。

<input type="text" name="date_of_reg" id="date_of_reg" />

你不能只依赖"id"。


连接:

另外,因为我们不知道你正在连接哪个MySQL API,确保它实际上是mysql_而不是mysqli_或PDO,因为你需要从连接到查询使用相同的。

  • 这些不同的api不会混合。

引用:

  • http://php.net/manual/en/mysqlinfo.api.choosing.php
  • http://php.net/manual/en/function.mysql-connect.php