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条)

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C