MySQL - PHP表单将值插入表中?

时间:2014-12-01 18:20:20

标签: php mysql

我想使用简单的表单向数据库添加注释。无论出于何种原因,当我使用所述表格时,我似乎无法更新表格。我没有收到任何错误,只是在我之后刷新桌子时没有任何反应。换句话说,即使在提交表单后,该表仍然有0个条目。这是我的代码:

<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
    die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());

$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];

$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";

mysql_close($connection); // Closing Connection

?>

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

您实际上并没有真正执行过您的查询:

$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);

其他事项:

  1. if ($connection->connect_error) {无效。您不能以OOP方式使用旧的mysql API。您需要使用mysqli

  2. Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO,here is a good tutorial

  3. 您也欢迎SQL injections

  4. 您执行错误检查。如果你不去寻找它们,你怎么能知道是否有问题?

答案 1 :(得分:0)

(注意:请更改服务器信息的服务器,用户名和密码)

 <?php
    session_start();
    $connection = mysql_connect("server","username","password");
    if (!$connection) {
        die('Connect Error: ' . mysql_error());
    }
    // Selecting Database
    mysql_select_db("database",$connection) or die(mysql_error());

    $name = $_POST['name'];
    $title = $_POST['title'];
    $comments = $_POST['comments'];

    $sql = "INSERT INTO comments (Name,Title,Comments)
    VALUES ('$name', '$title', '$comments')";

    mysql_query($sql);
    mysql_close($connection); // Closing Connection

    ?>

为了安全性(防止SQL注入),您可以使用mysql_real_escape_string函数来限制输入字段。例如:

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