tags:

views:

75

answers:

1

I have a simple insert statement using PDO php class.

the 'id' column is identity (doy) with autoincrement.

$statement = $db->prepare('INSERT INTO demographics (id,location_id,male,ethnicity_id,birthyear) VALUES (:id,:location_id,:male,:ethnicity_id,:birthyear)');

$statement->bindParam(':id',$demo->id,PDO::PARAM_INT,4);
$statement->bindParam(':location_id', $demo->locationid,PDO::PARAM_INT);
$statement->bindParam(':male',$demo->male,PDO::PARAM_BOOL);
$statement->bindParam(':ethnicity_id',$demo->ethnicityid,PDO::PARAM_INT);
$statement->bindParam(':birthyear',$demo->birthyear,PDO::PARAM_INT);
$statement->execute();  

print_r($demo);

Even though the statement executes correctly (row is correctly written), $demo->id is null.

I have a very similar statement for a different table, and it correctly returns the id column.

Any thoughts?

+1  A: 

If id is autoincremented, you don't need to specify it when inserting into the table. What value are you giving to $demo->id?

If you need the id of the inserted entry, you could retrieve it using PDO::lastInsertId, then set the object's $id field with the value.

oli
Right, I'm not setting the id value, but I do need to retrieve it. The value I'm giving to $demo->id is null. My understanding is bindParam() will set the AI values.I was aware of PDO::lastInsertId, but I don't want to run the risk of getting the wrong id, due to a race condition.
Alan