使用PDO时如何做到这一点?我曾经这样做但不是PDO。
我是否将$attack = $query->execute(array..
包裹在if statement
?
最好的方法是什么? 关于我的编码技巧的任何建议将不胜感激:)
这是我的代码
if(isset($_POST['submit'])){
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$spousename = $_POST['spousename'];
$bday = $_POST['bday'];
.
.
.
.*other $_POST[''] stuffs*
$q = "INSERT into crf(col_fn, col_mn, col_ln, col_sn, col_bday, col_home, col_telno, col_mobno, col_email, col_gender, col_civilstat)
VALUES(:fn, :mn, :ln, :sn, :bday, :homeadd, :telno, :mobno, :email, :gender, :civilstat);";
$query = $db->prepare($q);
try{
$attack= $query->execute(array(
":fn" => $firstname,
":mn" => $middlename,
":ln" => $lastname,
":sn" => $spousename,
":bday" => $bday,
":homeadd" => $homeadd,
":telno" => $telno,
":mobno" => $mobno,
":email" => $emailadd,
":gender" => $gender,
":civilstat"=> $civilstat
));
}catch(PDOException $e){
$e->getMessage();
}
?>
答案 0 :(得分:0)
http://php.net/manual/en/pdo.query.php
返回值
PDO :: query()返回PDOStatement对象,或者失败时返回FALSE。
因此,在if == false中包装将非常适合检查查询是否已执行
答案 1 :(得分:0)
你不需要它。每个陈述都是成功的,没有引起任何错误。因此,您不需要专门的条件来测试成功。
if(isset($_POST['submit'])){
unset($_POST['submit'])); // get rid of extra stuff in $_POST
$q = "INSERT into crf(col_fn, col_mn, col_ln, col_sn, col_bday, col_home, col_telno, col_mobno, col_email, col_gender, col_civilstat)
VALUES(:firstname, :middlename, :lastname, :spousename, :bday, :homeadd, :telno, :mobno, :email, :gender, :civilstat);";
$db->prepare($q)->execute($_POST);
echo "Success!"; // or whatever.
}
这是您需要的所有代码