Search code examples
phpmysqlsqlauto-increment

How can I detect just AUTO_INCREMENTed value with PHP?


Hello !

I'd like to know, what value have just assigned A_I method in my MySQL table. I can't look for it by specifying other values, because at least two of them could be the same. I'm really stuck.

Let's say I'm using this simple code to INSERT new VALUES:

INSERT INTO my_table (`Auto_Incremented_Value`, `My_Column`) VALUES (NULL, '$my_value');

Now I need to know what is the last value of Auto_Incremented_Value column, because I have to use this value in order to assign it to another table as a link to that object.

In real I allow some people to upload images on my server & these are associated with some products which they belong to. I have two tables to handle this.The first one (products table) uses AUTO_INCREMENT & the second one (images table) doesn't, because I store there full path to the uploaded image, small description & link to the assigned product. I need to store the Auto_Incremented_Value as the link in my images table .

P.S. I'd be pleased if I could solve it with PHP.

Thanks!


Solution

  • You should use MySQLI Insert ID for this.

    $query = "INSERT INTO my_table (`Auto_Incremented_Value`, `My_Column`) VALUES (NULL, '$my_value')";
    $mysqli->query($query);
    
    printf ("New Record has id %d.\n", $mysqli->insert_id);