Вопрос

I have this exact same issue, but that answer is old, and I've read other places the use of mysql_insert_id() is depreciated and should be avoided in new code.

The database is InnoDB and the primary key for this table is set to auto_increment.

Can anyone see what I'm doing wrong here? I should note I'm a beginner and learning on my own, so I apologize is this is glaringly obvious.

$query  = "INSERT INTO VENUES (province,city,venue)" . "VALUES " . "('$province','$city','$venue')";
$result = $db->query($query);
if ($result) {
    echo "$result row(s) sucessfully inserted.<br/>";
} else {
    echo "$db->error<br/>";
}

$result = $db->query("select last_insert_id()");
echo $result->num_rows //returns 1
echo $result; //nothing beyond this line happens

UPDATE: I am using mysqli.

Это было полезно?

Решение

The correct way to get the last inserted id, when using mysql_* is to make a call to mysql_insert_id().

What you are reading is partially correct - mysql_insert_id is in the process of being deprecated, but it's not just that function. All mysql_* functions are being deprecated. Instead you should use either PDO or mysqli_*.

In your code snippet, it is unclear which database access library you are using. Since your calls seem to be bound to an object, it is likely you are using PDO or mysqli.

For PDO you can use PDO::lastInsertId.
For mysqli, use mysqli->insert_id.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top