tags:

views:

289

answers:

2

I need to get back the postid (auto-incrementing PK) of a row when i insert it.

I am currently using this to get it

//get postid to return
if($result = $db -> query('SELECT postid FROM posts WHERE title = \''.$title.'\' LIMIT 1')){
  $row = $result->fetch_assoc();
  $json['postid']  = $row['postid'];
  $result->free();

where $title is the title name of the newly-inserted post.

Is there part of the mysqli class that will allow me to do this in one query?? Does $db -> query() return any information that will make this simpler and more secure?

I have tried looking through the mysqli documentation, but I could not find what i wanted. I'm sure it is there somewhere.

Multiple titles will screw this up, and although they are not allowed, you cant be too safe

+2  A: 

Does your table have an AUTO_INCREMENT column? If so you can use mysql_insert_id() or mysqli->insert_id to get that value, and then use it to select the row. More info here.

Jordan
or you can write a query to get the id yourself and then put it in the inserted data.
Arthur Thomas
Arthur: That's true, but there's always a chance that another client will be trying to do the same thing at the same time and you'll end up with a collision.
Jordan
Jordan: Thank you very much, works perfect. I had seen this method, but did understand know how worked. TY!
Douglas
Jordan: If the query is `SELECT LAST_INSERT_ID()` then it's safe. The value is stored/returned per session.
VolkerK
Jordan: I do not use mysql so I am not sure but hopefully it doesn't work like that. The postgresql serial (autonumber) ensures each number is unique no matter what. But I dunno about mysql :)
Arthur Thomas
A: 

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

MindStalker