0
I’m studying PDO
to be able to redo the functions of a crud that I use in mysqli
, but I have a problem, when I do an Insert with this function the first time it inserts the value in the database, but if I call the function again it only returns false and does not insert the value, this is the function:
public function getConnection() {
$this->dbConn = null;
try {
$this->dbConn = new PDO('mysql:host='.$this->dbHost.';dbname='.$this->dbName, $this->dbuser, $this->dbPass );
$this->dbConn->exec('Set names utf8');
} catch (PDOException $e) {
$e->getMessage();
}
return $this->dbConn;
}
function PDOCreate( $table, array $data, $ReturnId = false ) {
$fields = implode(',', array_keys($data));
$values = "'".implode("', '", $data)."'";
$field = "";
foreach ($data as $key => $value) {
$field .= "$key=:$key, ";
}
$field = trim($field, ', ');
$query = "INSERT INTO {$table} SET $field";
$stmt = $this->getConnection()->prepare( $query );
foreach ($data as $key => &$value) {
$stmt->bindParam( $key, $value );
}
if( $ReturnId && $stmt->execute() ) {
return $this->dbConn->lastInsertId();
} else {
return $stmt->execute();
}
}
to call this function I am doing so: PDOCreate('lojas', array("id" => 2, "nome"=> "teste"));
The title of the question is already strange does not match the description and the most important you have two calls from
execute()
in code 1)if( $ReturnId && $stmt->execute() )
and 2)$stmt->execute();
. I did not understand well what the problem is but that if in the end needs to be structured better.– rray
even if I call the function several times it only runs 1 time (and to run again I have to delete the line inserted in the database)
– Hebert Lima
Do you have a field like auto increment or a field like Unique key? see if the
execute()
picks up some mistake– rray
yes, in this table the ID field is auto_increment and has two Unique fields
– Hebert Lima
execute()
only returns false– Hebert Lima
If you try to include twice the same record the key Unique will bar. Leave your code like this:
if(!$stmt->execute()){ echo '<pre>'; print_r($stmt->errorInfo());}
so displayed the error message.– rray
you’re right! @rray Duplicate key! vlw
– Hebert Lima
but how can I treat these exceptions?
– Hebert Lima
With
$stmt->errorInfo()[0]
according to http://php.net/manual/en/pdostatement.errorinfo.php– Juven_v