-1

I am creating a forum service ( https://www.orbitrondev.com/forum/ )

When someone creates a new thread it will execute:

// Example values
$UserID = 23123;
$ForumID = 1;
$ThreadName = 'Example title';

$sQuery = 'INSERT INTO threads (user_id, board_id, topic, time, lastPostUserId, lastPostTime)
VALUES ("' . $UserID . '", "' . $ForumID . '", "' . $ThreadName . '", "' . $time . '", "' . $UserID . '", "' . $time . '")';

The ID is in the column thread_id

Now I have to get the ID (thread_id) of the inserted row. So I can create a post, and to create a post I need the ID.

I thought about getting the last inserted thread id an adding 1 so I have the id, but SQL looks finer :P

How can I know the thread_id value for the newly inserted row?

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
D3strukt0r
  • 571
  • 1
  • 4
  • 19

2 Answers2

0

You can retrieve the most recent AUTO_INCREMENT value with the LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function. These functions are connection-specific, so their return values are not affected by another connection which is also performing inserts

http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html

mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query

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

Rajesh Chamarthi
  • 18,568
  • 4
  • 40
  • 67
0

You should use mysqli::$insert_id.

Where $mysqli is your connection;

$result = $mysqli->query($sQuery);
$lastid = $mysqli->insert_id;

Although you should use prepared statements when inserting data into the database.

Note: You need to have an auto incremented ID field in the database for this to work.


You have;

$oResult = $Database->query($sQuery);
$ThreadID = $oResult->insert_id;

which will not work.

You should use the connection to find the last inserted ID, like this;

$oResult = $Database->query($sQuery);
$ThreadID = $Database->insert_id;

Hope this helps.

Community
  • 1
  • 1
worldofjr
  • 3,868
  • 8
  • 37
  • 49