douyi1899 2014-12-01 18:20
浏览 31
已采纳

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

I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:

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

?>

Thank you for your help!

  • 写回答

2条回答 默认 最新

  • doujiaoang69440 2014-12-01 18:21
    关注

    You don't ever actually execute your query:

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

    Other things:

    1. if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.

    2. Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

    3. You are also wide open to SQL injections

    4. You do no error checking. How do you expect to know if there are problems if you don't look for them?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面