Fonction PHP mysqli_insert_id ()

Définition et utilisation

Si vous avez une table avec un attribut AUTO_INCREMENT pour une colonne et, si votre dernier appel de fonction MySQLi exécute l'instruction INSERT ou UPDATE. lemysqli_insert_id() La fonction retourne l'ID généré automatiquement de la dernière requête exécutée.

Syntaxe

mysqli_insert_id($con)

Paramètres

Sr. Non Paramètre et description
1

con(Mandatory)

Il s'agit d'un objet représentant une connexion à MySQL Server.

Valeurs de retour

La fonction PHP mysqli_insert_id () renvoie la valeur de la colonne "Auto Increment" dans la dernière requête Dans le cas où il s'agit d'une opération INSERT ou UPDATE. Si la dernière requête exécutée n'est pas INSERT ou UPDATE ou, si la table n'a pas de colonne / champ avec l'attribut "AUTO_INCREMENT", cette fonction renvoie 0 .

Version PHP

Cette fonction a été introduite pour la première fois dans la version 5 de PHP et fonctionne dans toutes les versions ultérieures.

Supposons que nous ayons créé une table nommée Cricketers dans la base de données mydb, où l'ID de champ est PRIMARY KEY et AUTO INCREMENTED as -

CREATE TABLE Cricketers(
   ID INT PRIMARY KEY AUTO_INCREMENT,
   First_Name VARCHAR(255), 
   Last_Name VARCHAR(255), 
   Date_Of_Birth date, 
   Place_Of_Birth VARCHAR(255), 
   Country VARCHAR(255)
);

Exemple

L'exemple suivant montre l'utilisation de la fonction mysqli_insert_id () (dans le style procédural) -

<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   //Inserting a record into the employee table
   $sql = "insert into Cricketers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India')";
   mysqli_query($con, $sql);
   //Insert ID
   $id = mysqli_insert_id($con);
   print("Insert ID: ".$id ."\n");

   $sql = "insert into Cricketers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica')";
   mysqli_query($con, $sql);
   $id = mysqli_insert_id($con);
   print("Insert ID: ".$id);

   //Closing the connection
   mysqli_close($con);
?>

Cela produira le résultat suivant -

Insert ID: 1
Insert ID: 2

Exemple

Dans le style orienté objet, la syntaxe de cette fonction est $ con> insert_id (); Voici l'exemple de cette fonction dans le style orienté objet $ minus;

<?php
   //Creating a connection
   $con = new mysqli("localhost", "root", "password", "mydb");

   //Inserting a record into the employee table
   $con -> query("insert into Cricketers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka')");
   //Insert ID
   $state = $con->insert_id;
   print("Insert ID: ".$state."\n");

   //Inserting a record into the employee table
   $con -> query("insert into Cricketers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India')");
   //Insert ID
   $state = $con->insert_id;
   print("Insert ID: ".$state);

   //Closing the connection
   $con -> close();
?>

Cela produira le résultat suivant -

Insert ID: 3
Insert ID: 4

Exemple

Voici un autre exemple de la fonction mysqli_insert_id -

<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   //Query to SELECT all the rows of the Cricketers table
   mysqli_query($con, "SELECT * FROM Cricketers");
   print("Insert ID (select query): ".mysqli_insert_id($con)."\n");

   //Query to INSERT multiple rows into the Cricketers table
   mysqli_query($con, "INSERT INTO Cricketers VALUES (5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'), (6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India') ");
   print("Insert ID: (multiple inserts) ".mysqli_insert_id($con)."\n");

   //Query to UPDATE the rows of the employee table
   mysqli_query($con, "UPDATE Cricketers set COUNTRY = 'S.Africa' where ID = 2");
   print("Insert ID (update query): ".mysqli_insert_id($con)."\n");

   //Query to INSERT a record into the employee table
   mysqli_query($con, "INSERT INTO employee VALUES ('Sarmista', 'Sharma', 28, 'F', 15000,  101)");
   print("Insert ID: (table with out auto incremented key) ".mysqli_insert_id($con)."\n");

   //Closing the connection
   mysqli_close($con);
?>

Cela produira le résultat suivant -

Insert ID (select query): 0
Insert ID: (multiple inserts) 6
Insert ID (update query): 0
Insert ID: (table with out auto incremented key) 0

Exemple

L'exemple suivant montre l'utilisation de la fonction mysqli_insert_id avec les requêtes SELECT, UPDATE, INSERT et DELETE -

<?php
   $connection_mysql = mysqli_connect("localhost", "root", "password", "mydb");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   
   mysqli_query($connection_mysql,"INSERT INTO Employee (name) VALUES('PHP')");
   echo "New record has id: " . mysqli_insert_id($connection_mysql); 
   
   mysqli_close($connection_mysql);
?>

Cela produira le résultat suivant -

New record has id: 0