我真的需要bindParam吗?
我正在尝试做一些 PDO CRUD 来学习一些 PDO。我有一个关于bindParam 的问题。这是我现在的更新方法:
public static function update($conditions = array(), $data = array(), $table = '')
{
self::instance();
// Late static bindings (PHP 5.3)
$table = ($table === '') ? self::table() : $table;
// Check which data array we want to use
$values = (empty($data)) ? self::$_fields : $data;
$sql = "UPDATE $table SET ";
foreach ($values as $f => $v)
{
$sql .= "$f = ?, ";
}
// let's build the conditions
self::build_conditions($conditions);
// fix our WHERE, AND, OR, LIKE conditions
$extra = self::$condition_string;
// querystring
$sql = rtrim($sql, ', ') . $extra;
// let's merge the arrays into on
$v_val = array_values($values);
$c_val = array_values($conditions);
$array = array_merge($v_val, self::$condition_array);
$stmt = self::$db->prepare($sql);
return $stmt->execute($array);
}
在我的“self::$condition_array”中,我从 ? 中获得了所有正确的值。所以查询看起来像这样:
UPDATE table SET this = ?, another = ? WHERE title = ? AND time = ?
正如你所看到的,我不使用bindParams,而是将正确的值以正确的顺序($array)直接传递到execute($array)方法中。这就像一个魅力,但是这里不使用 use bindParam 安全吗?
如果没有那我该怎么办呢?
来自瑞典
托比亚斯的感谢
I'm trying to do a little PDO CRUD to learn some PDO. I have a question about bindParam. Here's my update method right now:
public static function update($conditions = array(), $data = array(), $table = '')
{
self::instance();
// Late static bindings (PHP 5.3)
$table = ($table === '') ? self::table() : $table;
// Check which data array we want to use
$values = (empty($data)) ? self::$_fields : $data;
$sql = "UPDATE $table SET ";
foreach ($values as $f => $v)
{
$sql .= "$f = ?, ";
}
// let's build the conditions
self::build_conditions($conditions);
// fix our WHERE, AND, OR, LIKE conditions
$extra = self::$condition_string;
// querystring
$sql = rtrim($sql, ', ') . $extra;
// let's merge the arrays into on
$v_val = array_values($values);
$c_val = array_values($conditions);
$array = array_merge($v_val, self::$condition_array);
$stmt = self::$db->prepare($sql);
return $stmt->execute($array);
}
in my "self::$condition_array" I get all the right values from the ?. SO the query looks like this:
UPDATE table SET this = ?, another = ? WHERE title = ? AND time = ?
as you can see I dont use bindParams instead I pass the right values in the right order ($array) directly into the execute($array) method. This works like a charm BUT is it safe not use use bindParam here?
If not then how can I do it?
Thanks from Sweden
Tobias
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,它很安全。
bindParam()
将参数与变量关联起来,当您希望在调用execute()
时使用变量的值时,请使用它。否则你正在做的事情就很好。PDO bindParam()
上的 PHP 文档Yes, it is safe.
bindParam()
associates a parameter with a variable, use it when you want value of a variable to be used whenexecute()
is called. Otherwise what you are doing is fine.PHP Docs on
PDO bindParam()