MySQLi自动增加的主键ID是如何生成的?

3
$insert = "INSERT INTO event_tracker_table (event_name, event_location, location_number, event_creator_username, event_creator_email)

            VALUES (
                    '".$_POST['event_name']."',
                    '".$_POST['event_location']."',
                    '".$_POST['location_number']."',
                    '".phpCAS::getAttribute('uid')."',
                    '".phpCAS::getAttribute('mail')."'
                    )";


            $mysqli->query($insert);

如何获取MySQL生成的AUTO INCREMENT?我尝试了以下方法,但没有成功:

$statement = $mysqli->query($insert);

echo $statement->insert_id; 

http://www.php.net/manual/en/pdo.lastinsertid.php - E_p
@Pekka,自增主键的名称是“eventid”。 - Arian Faurtosh
@E_p 我没有使用pdo,我正在使用mysqli... 请仔细阅读问题。 - Arian Faurtosh
1
你想要 $mysqli->insert_id - Pekka
1
不是,你正在使用 $statement_insert_id - Pekka
显示剩余3条评论
2个回答

6

插入 ID 是 MYSQLI 对象的属性,而不是 MYSQLI 结果对象的属性:

$statement = $mysqli->query($insert);
echo $mysqli->insert_id; // correct
echo $statement->insert_id; //not correct

http://php.net/manual/en/mysqli.insert-id.php


谢谢!这个答案非常清晰简洁,而且还起作用了! - Arian Faurtosh

0

你可以使用以下代码获取auto_increment的值:

$id = mysqli_insert_id($mysqli);

请参考mysqli_insert_id以获取更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接