vitto
vitto

Reputation: 19476

Get a column value (like id) after mysql INSERT

Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?

<?php

$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());

$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());

$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";

?>

Upvotes: 1

Views: 4289

Answers (3)

Sampson
Sampson

Reputation: 268434

The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.

$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");

print mysql_insert_id();

Upvotes: 1

Eric Mickelsen
Eric Mickelsen

Reputation: 10377

Use this: http://php.net/manual/en/function.mysql-insert-id.php Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.

Upvotes: 3

jishi
jishi

Reputation: 24634

There is builtin support for it, mysql_insert_id() or something.

Upvotes: 0

Related Questions