saftutorials.com
MYSQL LAST ID

PHP provides a mysql_insert_id() function which is used to fetch last inserted id. When we perform INSERT or UPDATE in a table with an AUTO_INCREMENT_FIELD, commonly we need last affected row id so we can get that id mysql_insert_id() function.


Below is a simple example to insert records into student table, it will also print last inserted record id.

<html>
 <head>
  <title>Insert a Record in MySQL Database</title>
 </head>
 <body>
    <?php
     if(isset($_POST['submit'])) {
        $database_host = 'localhost:3036';
    $database_user = 'root';
    $database_pass = '';
    $conn = mysql_connect($database_host, $database_user, $database_pass);
 
    if(! $conn ) {
      die('Could not connect: ' . mysql_error());
    }else{
      echo 'Connected successfully\n';
    }
  
    $selected_or_not = mysql_select_db( 'xyz_school' );
    if(! $selected_or_not ) {
      die('Not Selected xyz_school database');
    }else{
      echo 'Selected xyz_school database';
    }
        
        $student_name = $_POST['student_name']
        $student_address = $_POST['student_address'];
        $student_enrollment_no = $_POST['student_enrollment_no'];

$sql = 'INSERT INTO student '.
        '(student_name,student_address, student_enrollment_no, join_date) '.
        'VALUES ( $student_name, $student_address, $student_enrollment_no, NOW() )';
        
        $retval = mysql_query( $sql, $conn );
        
        if(! $retval ) {
           die('Could not update data: ' . mysql_error());
        }
$last_inserted_id = mysqli_insert_id($conn);
        echo "Inserted data successfully. Last inserted record ID is: " . $last_inserted_id;
        
        mysql_close($conn);
     }else {
    ?>
   <form method="post" action="<?php $_PHP_SELF ?>">
 <table width="400" border="0" cellspacing="1" cellpadding="2">
 
<tr>
<td width="100">Student Name</td>
<td><input name="student_name" type="text" id="student_name"></td>
</tr>
 
<tr>
<td width="100">Enrollment No </td>
<td><input name="student_enrollment_no" type="text" id="student_enrollment_no"> </td>
</tr>
 
<tr>
<td width="100">Address </td>
<td><textarea name="student_address" id="student_address"></textarea></td>
</tr>
 
<tr>
<td width="100"> </td>
<td><input name="submit" type="submit" id="submit" value="Submit"></td>
</tr>
 
 </table>
   </form>
    <?php
     }
    ?>
 </body>
</html>




Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic