duandao2306 2012-03-09 16:55
浏览 84
已采纳

为什么这个PHP脚本不会在MySQL数据库中插入表单数据?

On form submit, I'm getting a blank page (insert.php) with no error and no success message.

This is the form:

<form action="insert.php" method="post">
Firstname: <input type="text" name="first_name" id="first_name" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

This is the script:

mysql_select_db("my_db", $con);


$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');

$stmt->execute(':first_name', $first_name);


if (!mysql_query($stmt,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?>
  • 写回答

2条回答 默认 最新

  • duankuangxie9070 2012-03-09 16:58
    关注

    You need to create a PDO object to be able to use prepared statements. Instead you have opened a connection with mysql_connect(). The two do not mix, and PDO is preferred between them as it is more easily secured through the use of prepared statements (among other reasons).

    From the PDO docs:

    // This establishes your connection using PDO.
    // The PDO connection object is $db
    
    /* Connect to an ODBC database using driver invocation */
    $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
    $user = 'dbuser';
    $password = 'dbpass';
    
    try {
        $db = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    

    Pass an associative array to execute(), rather than a list of arguments representing your placeholders. The

    // Now that the PDO object is successfully created, prepare your statement
    $stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
    
    // Arg to execute() should be an associative array
    $stmt->execute(array(':first_name' => $first_name));
    

    The following call to mysql_query() is unnecessary, as you have already executed the prepared statement with PDO.

    // Don't do this
    // mysql_select_db("my_db", $con);
    
    // Or this...
    //if (!mysql_query($stmt,$con))
    //{
    //  die('Error: ' . mysql_error());
    //}
    
    // Or this...
    // mysql_close($con)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化