Search code examples
phpmysqlmysql-insert-id

mysql_insert_id() not returning a value -


I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.

The insert works too.

My table is as follows: idint(9) NOT NULL auto_increment,

and id is set as primary

What am I doing wrong? $conn = mysql_connect($host,$username,$password); mysql_select_db($database, $conn) or die( "Unable to select database"); include "update_activity.php"; updateActivity("logged in", "On Break");

    $date = date("m/d/y"); $starttime = time();
    $sesh = $_SESSION['fname']." ".$_SESSION['lname'];
    $q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";

    $query = mysql_query($q, $conn);
    $id = mysql_insert_id($conn);

    echo var_dump($id); exit;

edited to show my more recent attempts


Solution

  • Have read all comments given and your replies to each. Only one of these is possible:

    1. Either the query works properly OR
    2. You are not getting the generated primary key.

    Both of these can never be true.

    Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?

    To diagnose the problem, we have to go though the normal way.

    1. Dump your generated query before calling mysql_query.
    2. Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.

      error_reporting(E_ALL);
      ini_set('display_errors','on');
      
      echo "before calling: $q\n";
      $query = mysql_query($q, $conn);
      if(!$query)
      {
          echo "Error:" . mysql_error($conn);
          return;
      }
      echo " generated id:" . mysql_insert_id($conn);