PDO Insert only runs once

Asked

Viewed 30 times

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.

  • 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)

  • Do you have a field like auto increment or a field like Unique key? see if the execute() picks up some mistake

  • yes, in this table the ID field is auto_increment and has two Unique fields

  • execute() only returns false

  • 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.

  • you’re right! @rray Duplicate key! vlw

  • but how can I treat these exceptions?

  • With $stmt->errorInfo()[0] according to http://php.net/manual/en/pdostatement.errorinfo.php

Show 4 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.