2013-10-24 210 views
0

經過消毒和驗證後,可以正常工作。我試圖將數據插入到我的數據庫,但它口口聲聲說錯誤:「對不起,我們不能夠正確地爲您註冊...筆芯形式」無法使用PDO將數據插入到數據庫中

$qry = "INSERT INTO users (email, firstName, surname, userName, password, userDOB) values (?, ?, ?, ?, ?, ?)"; 

$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo())); 

$q->bindParam(1, $email); 
$q->bindParam(2, $name); 
$q->bindParam(3, $surname); 
$q->bindParam(4, $username); 
$q->bindParam(5, $password); 
$q->bindParam(6, $userDOB); 

$q->execute(); 
if(!$q->execute()) { 
echo "<h1> Sorry, we were not able to sign you up... Refill the form properly </h1>"; 
} 
else { 
echo "<h1> Congratulations, $name ! You have been successfully signed up! </h1>"; 
} 

任何幫助,這將使這項工作將不勝感激。

+0

有沒有錯誤?你應該趕上PDO例外,以獲得更詳細的錯誤報告 –

+0

http://stackoverflow.com/questions/3726505/how-to-squeeze-error-message-out-of-pdo –

+0

做一些像'.. 。} else {die($ conn :: errorInfo); }'所以DB可以告訴你錯誤是什麼。固定的消息可以顯示給最終用戶,但是在調試時,除非它們也包含問題的實際細節,否則不要使用它們。 –

回答

0

不知道是否是問題所在,但是您要撥打​​兩次。
無論如何,你唯一的問題是缺乏錯誤報告。啓用它並運行每個運營商只有一次:

error_reporting(E_ALL); 
ini_set('display_errors', 1); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

$sql = "INSERT INTO users (email, firstName, surname, userName, password, userDOB) 
        values (?, ?, ?, ?, ?, ?)"; 
$stm = $conn->prepare($sql)); 
$stm->execute([$email,$name,$surname,$username,$password,$userDOB]); 
if ($stm->rowCount()) 
{ 
    echo "<h1> Sorry, we were not able to sign you up... Refill the form properly </h1>"; 
} else { 
    echo "<h1> Congratulations, $name ! You have been successfully signed up! </h1>"; 
} 
0

謝謝你們一大堆。它的工作原理,但是這是寫這段代碼和避免SQL注入的最佳實踐嗎?

try { 
     $conn = new PDO('mysql:host=localhost; dbname=userdetails', 'root', ''); 
     $conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     echo 'Connected!'; 
    } 
catch(PDOException $pe) { 
     echo('Connection error, because: ' .$pe->getMessage()); 
    } 

//Insert data to Database if values are not empty and sanitized 
if (!empty($_POST["firstName"]) && !empty($_POST["surname"]) && !empty($_POST["email"]) 
&& !empty($_POST["userName"]) && !empty($_POST["password"]) && $dob_day > 0 && $dob_month > 0 && $dob_year > 0) 
{ 
    $qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values (?, ?, ?, ?, ?, ?)"; 

    $q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo())); 

    $q->bindParam(1, $email); 
    $q->bindParam(2, $name); 
    $q->bindParam(3, $surname); 
    $q->bindParam(4, $username); 
    $q->bindParam(5, $password); 
    $q->bindParam(6, $userDOB); 

    try { 
    $q->execute(); 
       echo "<h1> Congratulations, $name ! You have been successfully signed up! </h1>"; 
    } 
    catch(PDOException $pe) { 
     echo('Connection error, because: ' .$pe->getMessage()); 
    } 
} 
+0

是的,保護是好的,但錯誤報告和整體效率可能會更好。 –

+0

謝謝@YourCommonSense。 –

相關問題