Php mysqli_insert_id返回0
我必须使用对另一个表(FK)中记录的引用。另一个表中的记录可能存在,也可能不存在,因此我可以使用它的ID,或者插入一个新的记录,然后使用它的ID 我有以下代码:Php mysqli_insert_id返回0,php,mysql,mysqli,Php,Mysql,Mysqli,我必须使用对另一个表(FK)中记录的引用。另一个表中的记录可能存在,也可能不存在,因此我可以使用它的ID,或者插入一个新的记录,然后使用它的ID 我有以下代码: $con=mysqli_connect("localhost","root","test","db_site"); // get existing levels $levelIdSQL = "SELECT idlevel from levels where levelstring = $level"; $levels = mysqli
$con=mysqli_connect("localhost","root","test","db_site");
// get existing levels
$levelIdSQL = "SELECT idlevel from levels where levelstring = $level";
$levels = mysqli_query($con, $levelIdSQL);
$levelID = -1;
if ($levels['num_rows'] > 0) {
echo "<br><br>some results<br><br>";
// we already have a level, use its id when updating
$row = $levels->fetch_assoc();
$levelID = $row['idlevel'];
} else {
// we must insert this string in the levels table, then use its id
echo "<br>running query: " . "INSERT INTO `db_site`.`levels` ('levelstring') values ('$level');";
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
echo "<br><br>connected OK<br><br>";
}
$rez = mysqli_query($con, "INSERT INTO `db_site`.`levels` ('levelstring') values ('$level');");
$levelID = mysqli_insert_id($con);
}
echo "<br><br>LEVEL ID: " . $levelID;
为此:
$rez = mysqli_query($con, "INSERT INTO `db_site`.`levels` (levelstring) values ('$level');");
现在一切都好了。试试这个,您应该在列名周围使用反勾号,而不是引号
$rez = mysqli_query($con, "INSERT INTO `db_site`.`levels` ( `levelstring`)
VALUES ('$level') ");
您正在连接两次数据库。insert_id()函数在每个连接的基础上工作。我编辑了我的代码和问题,运气不好。你确定你的查询确实有效吗?您没有检查
$rez
包含的内容。另外,您的表是否有自动递增标识符字段?这是获取back值所必需的。我的表有一个auto inc字段(例如,insert在Mysql工作区中工作正常)$rez不包含任何内容,它是空的代码>运行查询后,脚本是否会因错误而终止?感谢您的帮助,并修复了它。
$rez = mysqli_query($con, "INSERT INTO `db_site`.`levels` ( `levelstring`)
VALUES ('$level') ");