开发者

Using PDO with INSERT (PHP)

开发者 https://www.devze.com 2023-03-16 20:05 出处:网络
I\'ve got $sql = $db->prepare(\"INSERT INTO `aliases` (`alias`, `domain`, `added`, `enabled`) VALUES (:alias, :domain, :added, :enabled)\");

I've got

$sql = $db->prepare("INSERT INTO `aliases` (`alias`, `domain`, `added`, `enabled`) VALUES (:alias, :domain, :added, :enabled)");
$sql->bindValue(':alias', $alias);
$sql->bindValue(':domain', $domain);
$sql->bindValue(':added', time());
$sql->bindValue(':enabled', 1);
$sql->exe开发者_JAVA百科cute();
//how do I test if it was added or #1062 - Duplicate entry '...' for key 'alias'

I assume that's correct.

My question is: How do I test if it was added successfully?


You can check the return value of $sql->execute(), like this:

if ($sql->execute()) {
    // Query succeeded.
} else {
    // Query failed.
    $errorcode = $sql->errorCode();
}

For more information, see the documentation for PDOStatement (the class of prepared statements).


See the docs about PDO Error handling and this comment

By default you have to check the return of execute. Details can then be found in errorinfo() and errorcode()

if ($sql->execute === false) {    //check return, false on error
     var_dump($sql->errorinfo();  //array containing information on error
     die()
}

But I would recommened using PDO::ERRMODE_EXCEPTION so that a PDOException is thrown on error. This makes your code a bit neater. The basic information is provided by the exception's __toString() but further information can be found (using an exception's normal methods, see link to docs above).

$db = new PDO( /* your connection string */ );
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
try {
    $sql = $db->prepare("INSERT INTO `aliases` (`alias`, `domain`, `added`, `enabled`) VALUES (:alias, :domain, :added, :enabled)");
    $sql->execute();
}

catch(PDOException $e) {
    echo $e;             //basic information is provided due to Exception::__toString()
    die();
}


if ($stmt->errorCode() == "00000")  {
  // Query succeeded.   
} else {
  // Query failed.
  echo "Error: " . $stmt->errorCode();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消