我正在尝试针对同一 ID 获取单选按钮和复选框值,但这两个值都存储在两个不同的 ID 中。问题出在哪里?帮帮我
$sql1 ="INSERT INTO student (name,fathername)
VALUES ('$name','$fathername')";
$sql2 = "SELECT last_insert_id() as id";
$res1 = mysqli_query($conn, $sql1); //here you insert
$res2 = mysqli_query($conn, $sql2); //here you fetch the ID you inserted
$id = mysqli_fetch_array($res2)['id'];
$sql3 = "INSERT INTO information (user_id,email)
VALUES ('$id','$email')"; //here you use that said ID in your second query
$res3 = mysqli_query($conn, $sql3); //aaand you insert
Now the problem starts from here, both values are stored against different ids.
//For insertion multiple values of checkbox
$sql6="INSERT INTO information (checkbox) VALUES ('" . $checkBox . "')";
$res6 = mysqli_query($conn, $sql6);
//For insertion radio button value
$sql7 ="INSERT INTO information (radio) VALUES ('" . $gender . "')";
$res7 = mysqli_query($conn, $sql7);
如果我尝试插入这样的值('$id','" . $checkBox ."') 和 ('$id','" . $gender ."'),它在数据库中返回空值。
如果您运行多个INSERT
查询,它将使用不同的 ID 插入。无需对单行使用INSERT
多个查询。
溶液:
$query = "INSERT INTO information (user_id,email,check box,radio)
VALUES ($id,'$email','$checkbox','$gender')";
mysqli_query($conn,$query);
更新:
您还遇到获取最后一个插入 ID 的问题。您无法获取记录,因为:
$id = mysqli_fetch_array($res2)['id'];
您还可以使用 PHP 获取最后一个插入 ID,如下所示:
$res1 = mysqli_query($conn, $sql1);
$id = mysqli_insert_id($conn); // use after ist query.
您修改的代码:
$sql1 ="INSERT INTO student (name,fathername) VALUES ('$name','$fathername')";
$res1 = mysqli_query($conn, $sql1);
$id = mysqli_insert_id($conn); // will return last insert id
$query = "INSERT INTO information (user_id,email,check box,radio) VALUES ($id,'$email','$checkbox','$gender')";
mysqli_query($conn,$query);