php - 尝试获取插入值后返回的 ID,但 mysqli_insert_id() 返回 null

标签 php mysql

<?php 

 $value = json_decode(file_get_contents('php://input'));
 $mysql_pekare= new mysqli ("serv", "user","pass", "db");

 if(!empty($value)) {
 $stmt = $mysql_pekare->prepare("INSERT INTO users (`username`, `password`)  VALUES(?,?)"); 

 $stmt->bind_param("ss", $value->username, $value->password);
 $stmt->execute();

     if(!empty($stmt)) {

        $contacts = array(); 
        $id = mysqli_insert_id(); 
        $contact = array("objectId" =>  ($id));
        array_push($contacts, $contact);
        echo json_encode(array('results' => $contacts), JSON_PRETTY_PRINT);
     }

 $stmt->close();
 $mysql_pekare->close();

 }
 ?>

现在,当我从前端插入信息时,值(用户名+密码)会被添加到 MySQL 中,并且具有唯一的 ID,但我没有得到返回的 ID,目前我得到的是这样的:

   {
  "results": [
      {
  "objectId": null
      }
     ]
   }

最佳答案

您的 $id 很可能为 null 或不确定的错误...

//This is for procedural and needs a link
$id = mysqli_insert_id(); 
//should be
$id = mysqli_insert_id($mysql_pekare); 
//$mysql_pekare I am assuming is your connection...

//however you are using oo (or I think) so should be
$stmt->insert_id

关于php - 尝试获取插入值后返回的 ID,但 mysqli_insert_id() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38019164/

相关文章:

php - 测试PHP/MySQLi连接性

php - 如果查询运行表将被填充,是否有必要?

php - 使用数据库+ Symfony 2 和 Doctrine 中的值填充表单中的选择列表

javascript - json_encode 返回“

php - 如何告诉命名空间下的类列表

php - 将使用路径更新列的触发器

php - 我正在开始下载,未知大小

javascript - Symfony2 是否可以使用 Javascript 删除 session 变量?

php - 如何将表单模板保存到formbuilder构建的数据库中

php - 获取数据集中的最高值