2010-03-23 46 views
0

我有一個簡單的插入語句使用PDO php類。PDOStatement :: bindParam()不從MySQL插入設置AI值?

'id'列是自動增量的標識(doy)。

$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); 

即使語句正確執行(行被正確寫入),$ demo-> id爲null。

我有一個非常類似的聲明不同的表,它正確地返回id列。

有什麼想法?

回答

1

如果id是自動增加的,則在插入表時不需要指定它。你給$demo->id什麼價值?

如果您需要插入條目的ID,您可以使用PDO::lastInsertId檢索它,然後使用該值設置對象的$id字段。

+1

對,我沒有設置id值,但我確實需要檢索它。我給$ demo-> id的值爲null。我的理解是bindParam()將設置AI值。 我知道PDO :: lastInsertId,但由於競爭條件,我不想冒着得到錯誤ID的風險。 – Alan 2010-03-23 18:29:31