DarrenVortex
DarrenVortex

Reputation: 195

INSERT query doesn't return an object

I'm simply trying to retrieve the inserted row's unique ID. Why doesn't this code work?

include('lib_connection.php');
$con = dbconnect();
$res = $con->query("insert into schools(school,city) values('CyFair High School','houston') ");
echo $res->insert_id;
$con->close();

I only get:

Notice: Trying to get property of non-object in C:\Program Files (x86)\wampserver\www\hwsource\do_test.php on line 5

dbconnect() works fine. The query also executes fine and inserts the values in the DB, but I don't get an object returned. I simply get a boolean true. If Insert doesn't return an object, then how can I retrieve the inserted ID?

Upvotes: 0

Views: 621

Answers (4)

Ger
Ger

Reputation: 949

Amend

echo $res->insert_id;

to

echo $con->insert_id;

It's an old question at this stage, but the best answers remain ambiguous, so I thought I'd clarify, using the actual variable names in the question, and the usual currently implemented PHP versions.

My answer works if $con is a mysqli object, which it probably is (and not the older mysql -- the 'i' stands for 'improved'). Thus, when performing its query method it

returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.[Source]

This explains the error message, as the query is an INSERT.

I came here as a result of a textbook instructing me to get the insert_id from the result and not the mysqli object itself, but I can't find any justification for this in the documentation for past or present versions of MySQL.

Upvotes: 0

Miroslav Stopka
Miroslav Stopka

Reputation: 107

Try

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");  //use your data
$mysqli->query("insert into schools(school,city) values('CyFair High School','houston') ");
echo $mysqli->insert_id
$mysqli->close();

UPDATED: instead of $con->close() try mysql_close($con);

Upvotes: 1

Jay Bhatt
Jay Bhatt

Reputation: 5651

If you are using PDO you need to set the fetch mode to PDO::FETCH_OBJECT...Also if your code is returning an array you can simply cast it to object like this (object) $res.

Upvotes: 0

ITroubs
ITroubs

Reputation: 11215

If i am right to asume that your dbconnection uses the plain and simple mysql functions then just replace

echo $res->insert_id;

with:

echo mysql_insert_id();

Upvotes: 0

Related Questions