douzheren3349 2014-02-24 15:59
浏览 76
已采纳

准备好INSERT语句以使insert_id在第二个准备好的INSERT语句中使用

Im trying to create my own register form but im having issues with prepared statements.

the idea is to create a prepared statement to insert info into the user table, then from that get the insert_id from the generated content to use in another insert statement

here is a version of my register script

  <?php

    $returnedId = '';

    include "includes/dbconnect.php";

    $stmt = $db->prepare("INSERT INTO `users`(`Username`, `Email`, `Password`) VALUES (?, ?, ?)");
    $stmt->bind_param('sss', $_POST['username'], $_POST['email'], $_POST['password']);
    $stmt->execute();
    $returnedId = $stmt->insert_id;
    $stmt->close();

    echo $returnedId;

    $allergystmt = $db->prepare("INSERT INTO 'user_allergy' ('user_id', 'allergy_id') VALUES (?, ?)");
    $allergystmt->bind_param('ss', $returnedId, $_POST['check_list']);
    $allergystmt->execute();
    $allergystmt->close();

    header('Location: index.php');

?>

the first prepared statement runs correctly and inserts information into the table, after that the $returnId variable is successfully echoed. next in the script is my second prepared statement, when it tries to run im getting the error that says:

Fatal error: Call to a member function bind_param() on a non-object in D:\filepathegister.php on line 17

it seems that my variable isnt being carried into the second prepared statement.

  • 写回答

1条回答 默认 最新

  • dongyin8009 2014-02-24 16:06
    关注

    Your second query has syntax errors and failed to prepare. Since you have no error handling for database failures like this, your later code just blunders onwards:

    $allergystmt = $db->prepare("INSERT INTO 'user_allergy' ('user_id', 'allergy_id') VALUES (?, ?)");
                                             ^---         ^--^---    ^-- etc...
    

    You cannot use ' quotes on table and field names. ' indicate strings. None of those field/table names are reserved words, so there is NO need to quote them at at all:

    $allergystmt = $db->prepare("INSERT INTO user_allergy (user_id, allergy_id) VALUES (?, ?)");
    if (!$allergystmt) { die($dbh->errorInfo()); }
    

    Note the addition of the errorInfo() output. Never assume a DB operation was successful. Always assume failure, and treat success as a pleasant surprise.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向