【问题标题】:I want to use the INSERT statement to insert values that come from the SELECT statements in PHP我想使用 INSERT 语句插入来自 PHP 中 SELECT 语句的值
【发布时间】:2021-05-21 09:03:09
【问题描述】:

我想使用 INSERT 语句插入来自 PHP 中的 SELECT 语句的值

student的表没有得到数据

$sql = "INSERT INTO student(academic_major, promo, user_id) VALUES (?, ?, (?));";
$stmtt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmtt, $sql)){
    header("Location: add_student_forum.php?error=sqlerrorstudent");
    exit();
}else{

    $id = "SELECT id FROM user WHERE email = '$email'";
    mysqli_stmt_bind_param($stmtt, "sss", $academic_major, $promo, $id);
    mysqli_stmt_execute($stmtt);
    header("Location: add_student_forum.php?signup=success".$id);
    exit();
}

当我执行它时,它会显示这个标题 header("Location: add_student_forum.php?signup=success".$id);在网址中 而且我不知道为什么桌子之后是空的

【问题讨论】:

  • 这能回答你的问题吗? Insert into ... values ( SELECT ... FROM ... )
  • 语句被成功准备的事实并不意味着它会被成功执行。查询文本看起来是错误的,但可以准备。
  • 这里我需要用户表中的 id 才能像外键一样使用它
  • 我想用PHP实现这个SQL语句:
  • 执行select,获取id然后在insert语句中使用

标签: php mysql database


【解决方案1】:

您不会将 SQL 绑定为参数。将数据绑定为参数,并将SELECT SQL放入准备好的语句SQL中

$sql = "INSERT INTO student(academic_major, promo, user_id) VALUES (?, ?, SELECT id FROM user WHERE email = ?);";
$stmtt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmtt, $sql);
mysqli_stmt_bind_param($stmtt, "sss", $academic_major, $promo, $email);
mysqli_stmt_execute($stmtt);
header("Location: add_student_forum.php?signup=success".$id);
exit();

确保您已启用 mysqli 错误报告。 How to get the error message in MySQLi?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 2016-09-01
    • 2016-07-27
    • 2012-10-18
    相关资源
    最近更新 更多