All,
I’m trying the code below, and I think that as I have written it, the value of $inserted never becomes TRUE, I am not sure why. When I run the program, I get thousands of empty records created, and I have to manually shut down the server.
function createRecord(){ // Query creates a new empty record in table, returns the auto-incremented ID.
$dbConnection=$this->dbConnect();
$inserted=false;
$IDQuery=null;
while (!$inserted){
$insertQuery=$dbConnection->prepare("INSERT INTO $this->table () VALUES ()");
$inserted=$insertQuery->execute();
if ($inserted){
$IDQuery=$dbConnection->prepare("SELECT LAST_INSERT_ID()");
$IDQuery->execute();
}
}
$result=$IDQuery->fetch(PDO::FETCH_ASSOC);
$ID=$result["Last_Insert_ID()"];
return $ID;
}
Many thanks in helping me with this.
Cheers,
JDelage
EDIT: I can’t recreate the problem on a stand alone piece of code, so I think the problem is not related to this part of the code.
Instead of running a query for the last insert id you should use PDO::last_insert_id.
http://php.net/manual/de/pdo.lastinsertid.php
I’m not sure why you’d need to use the loop to insert your row. Try and inspect the prepared and executed statement with
debugDumpParams(), you may want to usebindParam()for the prepared statement also instead of injecting the variables into the string like that.Edit: Did you make sure that the table you are trying to insert to has a column set for AUTO_INCREMENT? Otherwise the PDO driver will not return meaningful data for
last_insert_id().