<?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/