我正在使用 PHP 5.1.6 和 MDB2 并尝试将我的 prepare/execute/fetchAll 包装到一个类中,这样我就可以用一行执行一个选择查询。以下代码显示了我创建的类并直接执行相同的查询:
<?php
include_once "MDB2.php";
class db {
private static $dsn = array(
'phptype' => "mysqli",
'username' => "username",
'password' => "pass",
'hostspec' => "localhost",
'database' => "dbname"
);
private static $instance = NULL;
private static $statement = NULL;
private static $resultset = NULL;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if (!self::$instance) {
self::$instance =& MDB2::factory(self::$dsn);
}
return self::$instance;
}
public static function execQuery($sql, $types, $values) {
if (self::$instance === NULL) {
self::getInstance();
}
self::$statement = self::$instance->prepare(
$sql, $types, MDB2_PREPARE_RESULT);
self::$resultset = self::$statement->execute(array($values));
if (PEAR::isError(self::$resultset)) {
// (this is where it fails)
echo('Execute Failed: ' . self::$resultset->getMessage());
return false;
}
return self::$resultset->fetchAll(MDB2_FETCHMODE_ASSOC);
}
}
echo "<pre>";
$dsn = array(
'phptype' => "mysqli",
'username' => "username",
'password' => "pass",
'hostspec' => "localhost",
'database' => "dbname"
);
$sql = "select * from testtable where id = ? order by id LIMIT ?"
$t = array('text','integer');
$v = array('ABC',3);
// GOING DIRECT
$db =& MDB2::factory($dsn);
$stmt = $db->prepare($sql, $t, MDB2_PREPARE_RESULT);
$res = $stmt->execute($v);
$out = $res->fetchAll(MDB2_FETCHMODE_ASSOC);
print_r($out);
// GOING THROUGH CLASS
print_r( db::execQuery($sql, $t, $v) );
?>
go direct 的输出按预期工作,但第二次尝试通过类失败,并显示 PEAR 错误消息“MDB2 错误:未找到”。我看不出这两种方法有什么区别。
如果我只通过一个 SQL 语句,该类可以正常工作?替换并且不要使用 'array()' 来保存类型和值。如果我改变这些,它的工作原理:
$sql = "select * from testtable where id = ? order by id"
$t = 'text';
$v = 'ABC';