I have the following code:
public function createNewGuide($userID,$guideName)
{
$sql =" INSERT INTO myTable(name, updated)
VALUES ('$guideName', 'NOW()')";
//Process query
$this->query($sql); // This inserts the new row
$this->query('LAST_INSERT_ID()'); // This throws an error
return $this->query_result;
}
My query function looks like this:
private function query($sql)
{
$this->query_result = mysql_query($sql, $this->conn)
or die("Unable to query local database <b>". mysql_error()."</b><br>$sql");
}
I get the following error:
MySQL Database Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LAST_INSERT_ID()'
I've googled and looked at similar problems, but not found an answer :(
I have not tried the PHP function mysql_insert_id(), as I really would like to do this using SQL.
The guys have already answered that you were missing the SELECT prefix.
By the way, you should watch your INSERT statement... it has a clear door for SQL injection if
$guideName
is not escaped.If you have multiple Database links into the same enviroment, you should always specify the Link Identifier.
In case of
mysql_insert_id
php function you should always call it usingmysql_insert_id( $link_id );
In case you call it by SQL query using
SELECT LAST_INSERT_ID( link_id )
.If I were you. I would get your insert/select last_insert_id to work from the command line or query browser first, before php. At minimum, this will at least confirm or deny correct sql syntax.
I think your table has
datetime
/timestamp
column and see your query hasNOW()
varchar
value instead ofdatetime
value, so yourSQL query
should have returnfalse
.If the query return
false
you will not get last inserted id (always for current connection).I agree with whoever says you should use
mysql_insert_id
, but if you want to useLAST_INSERT_ID
, you can use this: