单选按钮和复选框值保存不同的ID

时间:2016-02-13 20:39:43

标签: php mysqli sql-insert

我试图获取相同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。”'),它会在数据库中返回空值。

1 个答案:

答案 0 :(得分:0)

如果您运行多个INSERT查询,它将插入不同的ID。无需对单行使用INSERT个多个查询。

<强>解决方案:

$query = "INSERT INTO information (user_id,email,check box,radio) 
VALUES ($id,'$email','$checkbox','$gender')";
mysqli_query($conn,$query);

<强>更新

获取上一个INSERT 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);