MySQL insert id in php | Coding Tag
×

MySQL Insert Id Function in PHP

3313

In PHP mysql_insert_id() function is used for those table which contains auto-generated field. When function is executed then last query in a row returns the id value. Function returns zero value if there were no auto-generated field.

How mysql_insert_id() work ?
Step 1: we create a table in a database with auto-generated field.
CREATE TABLE  tbl_student_inf

(
stu_ id NOT NULL AUTO_INCREMENT,
stu_name VARCHAR(250) NOT NULL,

PRIMARY KEY('stu_id')
)
Step 2: Create a connection file (connection.php)
<?php

mysql_connect("localhost","root","") or die ("Connection not exist" . mysql_error());
mysql_select_db("tutorial") or die ("table does not exists" ." " . mysql_error());

?>
Step 3: PHP code (student_information.php) page
<?php

include("connection.php");

// include data base  connection file in a php page

$qry = "INSERT INTO tbl_student_inf (stu_name) VALUES ('John')";
mysql_query($qry);
$calculate_last_id = mysql_insert_id();
echo "New record inserted successfully. Last inserted ID in a table is: " .  $calculate_last_id;

?>
Result:



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments