PDA

View Full Version : How to print Out Mysql ID after Posting


ajloun
12-14-2009, 04:39 AM
Hello

How do you Make my Code prints Out the ID of the Inserted Data Immeditaly after Getting the Successful Message . .

$com=$_POST['comment'];

$sql="INSERT INTO ".$DB->prefix("com")." (com)VALUES('$com')";
$result=mysql_query($sql);

if($result){
echo "Successful.. and the ID for this Query is : ...<BR>";
}
else {
echo "ERROR";
}

Fou-Lu
12-14-2009, 04:46 AM
You mean the auto-increment key?
Use mysql_insert_id() (http://php.ca/manual/en/function.mysql-insert-id.php) to get the last created primary key. Only works on auto_increment keys, otherwise you're expected to already know the primary key data.

ajloun
12-14-2009, 05:14 AM
Aha .. thank you .. that was easys
echo "ID of last inserted record is: " . mysql_insert_id();

:)

Maybe this will help Someone els too

<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db("test_db",$con);

$sql = "INSERT INTO person VALUES ('Børge','Refsnes','Sandnes','17')";
$result = mysql_query($sql,$con);
echo "ID of last inserted record is: " . mysql_insert_id();

mysql_close($con);
?>