Php / Pdo插入不起作用:语法错误?

时间:2013-10-14 08:27:42

标签: php syntax pdo

我正在编写一些代码,使用PDO将一些数据输入到mysql dtabase中。此代码有效(验证数据是否全部存在):

echo $usertype . '<br>';
echo $firstname . '<br>';
echo $lastname . '<br>';
echo $company . '<br>';
echo $jobtitle . '<br>';
echo $address . '<br>';
echo $email . '<br>';
echo $telephone . '<br>';
echo $mobile . '<br>';
echo $dobday . '<br>';
echo $dobmonth . '<br>';
echo $dobyear . '<br>';
echo $gender . '<br>';
echo $ethnicity . '<br>';
echo $password . '<br>';
echo $credits . '<br>';

但是这段代码没有(我已经检查了数据库连接,它确实连接了,而且名为users的表确实存在):

$STH = $dbh->prepare("INSERT INTO users (firstname, lastname, company, jobtitle, usertype, address, email, telephone, mobile, dobday, dobmonth, dobyear, gender, ethnicity, password, credits) values (:firstname, :lastname, :company, :jobtitle, :usertype, :address, :email, :telephone, :mobile, :dobday, :dobmonth, :dobyear :gender, :ethnicity, :password, :credits)");
$STH->bindParam(':firstname', $firstname);
$STH->bindParam(':lastname', $lastname);
$STH->bindParam(':company', $company);
$STH->bindParam(':jobtitle', $jobtitle);
$STH->bindParam(':usertype', $usertype);
$STH->bindParam(':address', $address);
$STH->bindParam(':email', $email);
$STH->bindParam(':telephone', $telephone);
$STH->bindParam(':mobile', $mobile);
$STH->bindParam(':dobday', $dobday);
$STH->bindParam(':dobmonth', $dobmonth);
$STH->bindParam(':dobyear', $dobyear);
$STH->bindParam(':gender', $gender);
$STH->bindParam(':ethnicity', $ethnicity);
$STH->bindParam(':password', $password);
$STH->bindParam(':credits', $credits);
try{
    $STH->execute();
    redirect_to(formsuccess.php);
    }
catch(PDOException $e) { 
    echo "I'm sorry, Dave. I'm afraid I can't do that.";  
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
    redirect_to(databaseentryfail.php); 

    }

请你能帮我解决这个问题吗,我知道这件事让我感到愚蠢......

霍克斯顿

2 个答案:

答案 0 :(得分:2)

不是取代h2ooooooo的好地方并回复,但只是说你可能会一次又一次犯同样的错误。避免这种情况的一种方法是通过格式化使代码更具可读性:

$STH = $dbh->prepare("INSERT INTO users (
  firstname
, lastname
, company
, jobtitle
etc

是的,这意味着更多的LOC,但它也可以减少花在追逐愚蠢错误上的时间,因为缺少一个领先的逗号会跳出你的页面。

还有一个很小的好处,你可以很容易地在页面上发现你的SQL语句。

(是的,这是一个评论而不是一个答案,但它是我能够说明我的观点的唯一方式)

答案 1 :(得分:1)

您错过了:dobyear:gender之间的逗号:

  

$ STH = $ dbh-&gt; prepare(“INSERT INTO users(firstname,lastname,company,jobtitle,usertype,address,email,telephone,mobile,dobday,dobmonth,dobyear,gender,ethnicity,password,credits) values(:firstname,:lastname,:company,:jobtitle,:usertype,:address,:email,:telephone,:mobile,:dobday,:dobmonth,:dobyear:gender ,:ethnicity, :密码,:积分)“);