【问题标题】:PDO prepare statement for inserting array into db issue用于将数组插入数据库问题的 PDO 准备语句
【发布时间】:2013-11-02 22:54:48
【问题描述】:

我正在使用 PDO 创建用户注册系统,并尝试将用户表单数据插入到数据库表中。很简单,但是错误的值被输入到数据库中。输入到数据库中的值是:username、:password、:email_address、:city 等,而不是从我的表单传递给函数的值。关于我做错了什么的任何想法?我尝试使用 bindParam 和 bindValue 但结果相似,并且根据其他帖子我得出结论,使用数组是最好的方法。帮忙!

    function add_user($username, $password, $email, $fName, $lName, $address, $city, $state, $zip, $phone ) {
global $db;
$sql = "INSERT INTO alumni_user_info 
        (username, password, email_address, first, last, address, city, state, zip_code, phone)
        VALUES
        (':username', ':password', ':email_address', ':first', ':last', ':address', ':city', ':state', ':zip_code', ':phone')";

$sth = $db->prepare($sql);      

$result = $sth -> execute(array(':username' => $username, ':password' => $password, ':email_address' => $email, ':first' => $fName, ':last' => $lName, ':address' => $address, ':city' => $city, ':state' => $state, ':zip_code' => $zip, ':phone' => $phone)); 


if ($sth->execute()) {
$success = "Registration successful";
return $success;

} else {
var_dump($result->errorInfo());
$success = "Registration failed";
return $success;
}

【问题讨论】:

标签: php arrays pdo insert prepare


【解决方案1】:

不要在参数中使用引号。它将被转义,因为您已经绑定了参数。

$sql = "INSERT INTO alumni_user_info 
    (username, password, email_address, first, last, address, city, state, zip_code, phone)
    VALUES
    (:username, :password, :email_address, :first, :last, :address, :city, :state, :zip_code, :phone)";

如果你这样做':username' PDO 会将其视为字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 2016-04-05
    • 2011-07-13
    相关资源
    最近更新 更多