简体   繁体   English

mysqli_insert_id返回0

[英]mysqli_insert_id returning 0

I have to use a reference to a record in another table (FK). 我必须使用对另一个表(FK)中的记录的引用。 The record in the other table may or not exist, so I can either use its ID or insert a new one and then use its ID. 另一个表中的记录可能存在或不存在,因此我可以使用其ID或插入新的ID,然后使用其ID。

I have the following code: 我有以下代码:

$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;       

My levels table has an autoinc "idlevel" field and running the same SQL with MySQL Workbench/command line interface inserts the record just fine. 我的关卡表中有一个autoinc“ idlevel”字段,并且使用MySQL Workbench /命令行界面运行相同的SQL即可插入记录。 However, mysqli_insert_id returns 0 and no records are inserted. 但是, mysqli_insert_id返回0,并且不插入任何记录。

What am I doing wrong? 我究竟做错了什么?

Edit: after jterry's suggestion, I called die() and it returned: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''levelstring')". 编辑:在jterry的建议之后,我调用die()并返回:“您的SQL语法有错误;请检查与您的MySQL服务器版本相对应的手册,以找到在'levelstring')附近使用的正确语法”。 So I changed this: 所以我改变了这个:

$rez = mysqli_query($con, "INSERT INTO `db_site`.`levels` ('levelstring') values ('$level');");

into this: 到这个:

$rez = mysqli_query($con, "INSERT INTO `db_site`.`levels` (levelstring) values ('$level');");

Everything is ok now. 现在一切都很好。

try this , you should use backticks around column name not quotes. 尝试此操作,您应该在列名(而不是引号)周围使用反引号。

$rez = mysqli_query($con, "INSERT INTO `db_site`.`levels` ( `levelstring`) 
                           VALUES ('$level') ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM