2016-07-04 93 views
0

如何在使用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

你不需要它假將是巨大的檢查。每一個陳述都是成功的,不會造成任何錯誤。因此,您不需要專門的條件來測試成功。

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

這是所有的代碼,你需要