phpmysqliinsert-id

Mysqli con function


why insert_id return 0

thanks

This is my connect function :

  function baglan(){ 
$mysqli = mysqli_connect('localhost', 'aa', 'aa', 'aa')or die("aa");    
    $mysqli->set_charset("utf8");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
return $mysqli;
}

call my functon and print last insert id

$query="INSERT INTO `aa` (`aa`,  `aa`, `aa`) VALUES (NULL,   '".$_GET['aa']."',  '' );";

    $result = baglan()->query($query)->insert_id; 
    $aa = baglan()->insert_id;

Solution

  • insert_id is specific to a particular database connection. You're opening a new connection every time you call baglan(). You should just call it once and keep the connection in a variable.

    $con = baglan();
    $con->query($query);
    $aa = $con->insert_id;