Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysqli insert_id()

Tags:

php

class

mysqli

I don't know, what's wrong in my code. I try to get the latest insert id, it's echoing 0. Any idea?

public function __construct() {
  $this->mysqli = new mysqli(MYSQLI_SERVER, MYSQLI_USER, MYSQLI_PWD, MYSQLI_DBNAME) or die ('Error with connecting to the database!');;
}
public function insert_id(){
   return $this->mysqli->insert_id;  
}

$db->query("INSERT INTO user(f_name, l_name) VALUES('$f_name', '$l_name')");
var_dump($db->insert_id()); // return 0?
like image 638
tonoslfx Avatar asked Apr 30 '11 19:04

tonoslfx


People also ask

What is Insert_id?

Definition and Usage If you have a table with an AUTO_INCREMENT attribute for a column and, if your last MySQLi function call executes INSERT or UPDATE statement. The mysqli_insert_id() function returns the auto generated id of the last executed query.

How to get last INSERT id IN MySQLi?

The mysqli_insert_id() function / mysqli::$insert_id returns the id (generated with AUTO_INCREMENT) used in the last query. Return value: The value of the AUTO_INCREMENT field that was updated by the previous query.

What is the use of mysqli_insert_id?

The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.

How to get last inserted record IN MySQLi using PHP?

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.


1 Answers

You should use it as follow:

<?php
$mysqli = new mysqli(SQLI_SERVER, MYSQLI_USER, MYSQLI_PWD, MYSQLI_DBNAME);
if ($result = $mysqli->query("INSERT INTO user(f_name, l_name) VALUES('$f_name', '$l_name');")) {
   echo 'The ID is: '.$mysqli->insert_id;
}
?>
like image 82
Adnan Avatar answered Oct 15 '22 10:10

Adnan