gpt4 book ai didi

具有多个参数的 php PDO 查询要绑定(bind)

转载 作者:行者123 更新时间:2023-11-29 03:18:16 24 4
gpt4 key购买 nike

我目前正在学习 PHP 概念,只是不知道如何正确绑定(bind)查询。根据 PDO 手册,查询只有在类型为 string、int、float 等时才被绑定(bind)。我的第一个问题是:“我需要绑定(bind)日期吗?”如果是,使用哪些参数。否则,我需要将关系的某些属性绑定(bind)到插入以及如何处理剩余的不属于上述这些类型的属性?这是我的代码:

public function addCustomer($fname, $lname, $email, $dob, $hashedPwd, $hash)
{
$customer = new Customer($fname, $lname, $email, $dob, $hashedPwd);

$sql = $this->pdo->prepare("INSERT INTO customer(fname, lname, email, date_of_birth, password, hash, active)"
. " VALUES(:fname, :lname, :date_of_birth, :email, :password, :hash, :active)");

$sql->bindValue(':fname', $customer->getFname(), PDO::PARAM_STR);
$sql->bindValue(':lname', $customer->getLname(), PDO::PARAM_STR);
$sql->bindValue(':email', $customer->getEmail(), PDO::PARAM_STR);
$sql->bindValue(':password', $customer->getPassword(), PDO::PARAM_STR);
$sql->bindValue(':hash', $hash, PDO::PARAM_STR);
$sql->bindValue(':active', 0, PDO::PARAM_INT);

try {
$sql->execute(['date_of_birth' => $dob]);
echo "SUCCESS" . "<br>";
}catch (PDOException $e) {
$e->getMessage();
}


}

最佳答案

我通过传递一个数组并使用问号作为我的占位符来做到这一点

我还建议使用一组通用函数或数据库处理程序类,您可以简单地传递一个查询和数组(或者可能是带有数据库连接信息的第二个数组)并返回一个元素为 true 或 false 的数组0 以及元素 1 处的错误消息或来自元素 1 的数据(在选择的情况下)。

这是我的一个片段,经过修改以删除所有其他处理,但它显示了我如何参数化和准备查询。

    <?php
$query="insert into tablename(first_name,last_name) values(?,?)";
$array=array("John","Doe");

$dbconn = new PDO('mysql:host=' . $hostname . ';port=' . $dbPort . ';dbname=' . $dbName . ';charset=utf8', $username, $password, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $dbconn->prepare($query);
$result->execute($arr);
if (!$result) {
$retVal[] = false;
$retVal[] = "some sort of error on execute";
$retVal[] = $dbconn->errorInfo();
return;
}
$retVal[] = true;
$retVal[] = $dbconn->lastInsertId();

return;

?>

关于具有多个参数的 php PDO 查询要绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50558621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com