0

I want to execute a query that insert the insert id to one of the colums

And I want to know how to get the insert id I read this answer Get inserted id from mysql insert procedure but its talk about how to get the insert id after the query, And I want to get it when I do the query

I try to do:

    $stmt = $db->prepare("INSERT INTO `files` (`name`, `fname`) VALUES (?, LAST_INSERT_ID() + ?)") or die($db->error);
    $stmt->bind_param('ss', $name, $uniqid);

But its dosent work, I always get 56, also the contcat dosent work, what I need to do?

Community
  • 1
  • 1
sdfds dffdsf
  • 61
  • 1
  • 2
  • 7

2 Answers2

0

It is simply easier and better to save it after the insert. It is also highly unlikely you will get the correct id before the actual insert happens.

The most reliable way would be to use transactions.

  • Start a transaction
  • Insert the row
  • Update the insert id
  • Commit the transaction
Sougata
  • 56
  • 10
0

The + is not a string concatenation operator in MySQL. Use CONCAT(string1, string2, ...).

In the wire protocol, mysql returns the same value as LAST_INSERT_ID() to the client after each query, unsolicited, and most libraries provide a way to access the most recently returned value. You didn't mention, but it looks like you're using mysqli in php, so you're looking for this:

$last_id = $db->insert_id;

It may look as if this is going to send a second query to ask the database for the id, but it isn't. It's returning the previously stored value.

http://php.net/manual/en/mysqli.insert-id.php

Michael - sqlbot
  • 169,571
  • 25
  • 353
  • 427