【问题标题】:Radio button and check-box values saved aginast different Ids针对不同 ID 保存的单选按钮和复选框值
【发布时间】:2016-02-13 20:39:43
【问题描述】:

我正在尝试针对同一个 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 . "'),它会在数据库中返回空值。

【问题讨论】:

  • Y 不在一个插入查询中?
  • INSERT INTO 信息 (user_id,email,check box,radio) VALUES ('$id','$email','$checkbox','$gender')
  • @devpro 哦,谢谢!我在没有任何具体原因的情况下运行两个不同的查询。仍然有一个小问题,这两个字段都不适用于最后一个插入 id 即'$id'。 ?
  • 恭喜兄弟...编码愉快
  • @devpro 和你一样 :)

标签: php mysqli sql-insert


【解决方案1】:

如果您运行多个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);

【讨论】:

  • 你的意思是在 mysqli_query($conn,$query);我应该把你建议的行 $id = mysqli_insert_id($conn); ?
  • 我在回答 @bc110402307-syed-zeeshan-haide 中提到的 $res1 执行后不不不
  • 并删除这个 $res2 = mysqli_query($conn, $sql2); //这里获取插入的ID $id = mysqli_fetch_array($res2)['id']; @bc110402307-syed-zeeshan-haide
  • 还是不行。我正在这样写 $sql2 = "SELECT last_insert_id() as id"; $res1 = mysqli_query($conn, $sql1); //在这里插入 $id = mysqli_insert_id($conn); //这里获取你插入的ID $id = mysqli_fetch_array($res2)['id'];
  • oooooooooo paaaaaa ggggggggg !马斯拉赫尔何盖亚!!谢谢!!我运行一个查询两到三遍! :P
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
  • 2011-10-18
  • 2012-02-24
  • 1970-01-01
相关资源
最近更新 更多