Php – How to execute SELECT and INSERT in single query with PHP/MYSQL

identitylogicMySQLPHP

I have a table user_name with 3 fields, id, Name, Email (id is auto_increment field). I want to execute the following query in PHP, but its not returning any result.

INSERT INTO user_name (Name, Email) VALUES ('Example', 'example@xyz.com'); 
SELECT LAST_INSERT_ID() AS 'userid';

When I am executing the above query in PHP as below then its not returning anything.

$_SQL="INSERT INTO user_name (Name,Email) VALUES ('Example', 'example@xyz.com'); 
SELECT LAST_INSERT_ID() AS 'userid';";

$result_last_id = @mysql_query($_SQL);
$rs_insert = mysql_fetch_array($result_last_id);

$new_userid = $rs_insert['userid'];

Can anyone please tell me how to execute both queries into one.

Best Answer

Give a look to the mysql_insert_id() function.

mysql_query($insertStatementOnly);
$new_userid = mysql_insert_id();