PDO 在多个函数中的使用 - 预准备语句的重用
我有一个类“test”,有 2 个函数,一个用于创建准备好的语句,一个用于执行一次或多次。问题是我如何在第一个函数中设置绑定并填写另一个函数的变量。
class test {
private static $moduleSql = "SELECT
id,
module
FROM
phs_pages
WHERE
prettyurl = :prettyUrl AND
mainId = :mainId
";
private static function pre() {
$db = Db_Db::getInstance();
self::$preModuleSql = $db->prepare(self::$moduleSql);
self::$preModuleSql->bindParam(':prettyUrl', $prettyUrl);
self::$preModuleSql->bindParam(':mainId', $mainId);
}
private static function getClassByDb($mainId = 0, $id = 0) {
$prettyUrl = self::$parts[$id];
self::$preModuleSql->execute();
self::$preModuleSql->debugDumpParams();
$result = self::$preModuleSql->fetch(PDO::FETCH_ASSOC);
// get lower level classes
if (isset(self::$parts[$id + 1])) {
self::getClassByDb($result['id'], $id + 1);
} else {
return $result;
}
}
}
I have a class "test" with 2 functions, one to create the prepared statement and one to execute one or more times. The problem is how do i set the binding in the first one and fill in the vars on the other function.
class test {
private static $moduleSql = "SELECT
id,
module
FROM
phs_pages
WHERE
prettyurl = :prettyUrl AND
mainId = :mainId
";
private static function pre() {
$db = Db_Db::getInstance();
self::$preModuleSql = $db->prepare(self::$moduleSql);
self::$preModuleSql->bindParam(':prettyUrl', $prettyUrl);
self::$preModuleSql->bindParam(':mainId', $mainId);
}
private static function getClassByDb($mainId = 0, $id = 0) {
$prettyUrl = self::$parts[$id];
self::$preModuleSql->execute();
self::$preModuleSql->debugDumpParams();
$result = self::$preModuleSql->fetch(PDO::FETCH_ASSOC);
// get lower level classes
if (isset(self::$parts[$id + 1])) {
self::getClassByDb($result['id'], $id + 1);
} else {
return $result;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要在第一个函数中绑定任何参数,您需要在执行准备好的语句之前在第二个函数中绑定任何参数。
编辑:顺便说一句,你也可以调用 execute 包含一个数组,其中包含作为键的参数和要发送的值。
You don´t need to bind any parameters in your first function, you need to do that in your second function, right before you execute the prepared statement.
Edit: By the way, you can also call execute with an array that contains your parameters as keys and the values you want to send.
这个类定义有很多问题..呃。
它应该如下所示:
这样,所有在构造函数中接受实现 iRepository 的对象的对象都可以按名称获取语句。
你的班级不应该承担比它需要的更多的责任。如果它是用于存储准备好的语句,那么它应该与将参数绑定到它们并执行某些操作无关。
这是 Foo 类会做的事情:
There are so many things wrong with this class definition .. ehh.
It should look like this :
This way all the object which have accepted in the constructor an object which implements
iRepository
canfetch
statements by name.You class should not have more responsibilities then it needs. If it is for storing prepared statements , then it should have nothing to do with binding parameters to them and executing something.
Here is what Foo class would do :