get lastInsertId with PDO

1

I'm trying to get the last record in the database and it responds with 0 (ZERO) .. lastInsertId(); .

This is my connection to the BD:

class conexion{

    public static function conectar(){
        try {
                $link = new PDO(''.DRIVER.':host='.SERVER.';dbname='.DATABASE, USERNAME, PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES  \'UTF8\''));
                $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $link;

            }catch(PDOException $e){
                echo "Fallo la conexión: " . $e->getMessage();
                }
            }
}

And this is the query:

 public static function mdlGuardarTitulos($tabla, $Anun_Registrado, $Anun_Fecha, $Anun_Titulo){

    $consulta = Conexion::conectar()->prepare("INSERT INTO tblanuncios( AutoIncrID, Anun_Registrado, Anun_Fecha, Anun_Titulo,  ) VALUES ( :AutoIncrID, :Anun_Registrado, :Anun_Titulo)");
    $AutoIncrID = null;

    $consulta -> bindParam(":AutoIncrID", $AutoIncrID, PDO::PARAM_INT);
    $consulta -> bindParam(":Anun_Registrado", $Anun_Registrado, PDO::PARAM_INT);
    $consulta -> bindParam(":Anun_Fecha", $Anun_Fecha, PDO::PARAM_STR);
    $consulta -> bindParam(":Anun_Titulo", $Anun_Titulo, PDO::PARAM_STR);

    $consulta -> execute();
    $lastInsertId = Conexion::conectar()->lastInsertId();
    return  $lastInsertId;


    $consulta -> close();
    $consulta = null;

 }

But I'm not sure if% co_of% is correct, it returns a 0, the registration if it is done correctly.

    
asked by daniel 19.10.2018 в 05:40
source

2 answers

1

I think it's better to save a reference of the connection object that you just created, instead of calling the conectar method again.

public static function mdlGuardarTitulos($tabla, $Anun_Registrado, $Anun_Fecha, $Anun_Titulo){

    $pdo=Conexion::conectar();
    $consulta=$pdo->prepare("INSERT INTO tblanuncios(Anun_Registrado, Anun_Fecha, Anun_Titulo,  ) VALUES (:Anun_Registrado, :Anun_Titulo)");

    $consulta -> bindParam(":Anun_Registrado", $Anun_Registrado, PDO::PARAM_INT);
    $consulta -> bindParam(":Anun_Fecha", $Anun_Fecha, PDO::PARAM_STR);
    $consulta -> bindParam(":Anun_Titulo", $Anun_Titulo, PDO::PARAM_STR);

    if ($consulta -> execute()) {
        $lastInsertId = $pdo->lastInsertId();
    }else{
        //Pueden haber errores, como clave duplicada
         $lastInsertId = 0;
         echo $consulta->errorInfo()[2];
    }   

    $consulta -> close();
    return  $lastInsertId;
}

Other things that I've optimized:

  • In INSERT columns of type auto_increment can be omitted
  • The last inserted id is retrieved only in case the query is successful, if an error message is not printed and 0 is returned (this is optional)
  • $consulta is closed before return . Everything that is set after return never runs.
  • close() and null are redundant. I have left only $consulta->close() .

Optimizing the PDO connection

The PDO constructor supports an array of options as the last parameter. You can then create an array that contains all the configuration options, thus avoiding a supplementary call to setAttribute . In that same array, it is convenient to indicate that the attribute ATTR_EMULATE_PREPARES is FALSE . It is an additional level of security, to completely disable the emulated preparations that can lead in certain scenarios to SQL injection attacks.

class Conexion{

    public static function conectar(){
        try {
                $pdoOptions = array(
                                        PDO::ATTR_EMULATE_PREPARES => FALSE, 
                                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                                        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES  \'UTF8\''
                                    );

                $link = new PDO(''.DRIVER.':host='.SERVER.';dbname='.DATABASE, USERNAME, PASSWORD, $pdoOptions);
                return $link;

        }catch(PDOException $e){
                echo "Fallo la conexión: " . $e->getMessage();
        }
    }
}

The character set (charset) can also be set in the connection string (DSN), as explained here . In that case, the following line: PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' must be deleted in $pdoOptions .

    
answered by 19.10.2018 / 15:33
source
0
$consulta = Conexion::conectar()->prepare("INSERT INTO tblanuncios( AutoIncrID, Anun_Registrado, Anun_Fecha, Anun_Titulo,  ) VALUES ( :AutoIncrID, :Anun_Registrado, :Anun_Titulo)");
$AutoIncrID = null;

$consulta -> bindParam(":AutoIncrID", $AutoIncrID, PDO::PARAM_INT);
$consulta -> bindParam(":Anun_Registrado", $Anun_Registrado, PDO::PARAM_INT);
$consulta -> bindParam(":Anun_Fecha", $Anun_Fecha, PDO::PARAM_STR);
$consulta -> bindParam(":Anun_Titulo", $Anun_Titulo, PDO::PARAM_STR);

$consulta -> execute();
$id = $consulta->lastInsertId();
return  $id;


$consulta -> close();
$consulta = null;
    
answered by 19.10.2018 в 12:49