gpt4 book ai didi

php - 从数组绑定(bind)值?

转载 作者:行者123 更新时间:2023-12-01 22:19:20 25 4
gpt4 key购买 nike

所以我有这个不完整的方法来将对象保存在数据库中:

public function save() {
$variables = get_object_vars($this);
$attributes = [];

foreach ($variables as $variable => $value) {
$attributes[] = $value;
}

$variableString = implode(", ", $attributes);

foreach ($variables as $variable => $value) {
$attributes[] = ":" . $value;
}

$valueString = implode(", ", $attributes);

$sql = "INSERT INTO products (" . $variableString . ") VALUES (" . $valueString . ")";
$query = $this->pdo->prepare($sql);
// ...
}

如何使用我已经创建的数组绑定(bind)这样的值?

$query->execute(array(
':username' => $username,
':email' => $email,
':password' => $password
));

最佳答案

我会这样做:

// This gets an associative array
$variables = get_object_vars($this);

// Init
$columns = [];
$placeholders = [];
$bindings = [];

// Loop through variables and build arrays
foreach ($variables as $column => $value)
{
$columns[] = $column;
$placeholder = ':' . $column;
$placeholders[] = $placeholder;
$bindings[$placeholder] = $value;
}

// Create strings
$columnString = implode(',', $columns);
$placeholderString = implode(',', $placeholders);

// Prepare query
$sql = "INSERT INTO products (" . $columnString . ") VALUES (" . $placeholderString . ")";
$query = $this->pdo->prepare($sql);

// Execute query
$query->execute($bindings);

基本上,您需要预先准备好所需的部分,然后通过它们。

我应该提到这可能是一种脆弱的方式,因为它假设您的类的属性总是在您的数据库表中。它基本上需要一个 $myModel->non_column = 123; 语句在某个地方推送并中断您的查询。

似乎您正在尝试构建自己的 Active Record 实现?可能想看看一些大玩家是如何做到这一点的,或者只是使用他们的。

关于php - 从数组绑定(bind)值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41352234/

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