我有两个查询,但是pdo->结果显示的是原始结果,而不是下一个结果。我想要结果query_1 =(a1,a2,a3),然后query_2 =(b1,b2,b3)。但是结果显示a1,a2,a3,然后再次显示a1,a2,a3。
DbGlobal.php:
class DbGlobal
{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct()
{
try
{
$this->_pdo = new PDO('mysql:host='. ConfigGlobal::get('mysql/host') .';dbname='. ConfigGlobal::get('mysql/db'), ConfigGlobal::get('mysql/username'), ConfigGlobal::get('mysql/password'));
//$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
die($e->getMessage());
}
}
public static function getInstance()
{
if(!isset(self::$_instance))
{
self::$_instance = new DbGlobal();
}
return self::$_instance;
}
public function query($sql, $params = array())
{
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql))
{
$x = 1;
if(count($params))
{
foreach($params as $param)
{
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else
{
$this->_error = true;
}
}
return $this;
}
}
QueryPage_1.php
$varname = 'Settings_SideBarButtons';
$vararray = array("UniqueId,", "Url,", "Dirr,");
$varstring = implode($vararray);
${$varname} = DbGlobal::getInstance()->query("SELECT ".$varstring." FROM
".$varname." WHERE a='1'");
在数据库中:
UniqueId => a1
Url => a2
Dirr => a3
结果正确:
print_r($Settings_SideBarButtons->results());
//output:
Array
( [0] => stdClass Object
( [UniqueId] => a1
[Url] => a2
[Dirr] => a3
)
)
然后,我在同一个查询脚本中使用了另一个具有不同varname的查询。
QueryPage_2.php
$varname = 'Core_Settings';
$vararray = array("UniqueId,", "Url,", "Dirr,");
$varstring = implode($vararray);
${$varname} = DbGlobal::getInstance()->query("SELECT ".$varstring." FROM
".$varname." WHERE a='1'");
在数据库中:
UniqueId => b1
Url => b2
Dirr => b3
但是结果是:
print_r($Core_Settings->results());
//output:
Array
( [0] => stdClass Object
( [UniqueId] => a1
[Url] => a2
[Dirr] => a3
)
)
我已经确认第二个查询中显示的结果是第一个查询中的结果。
我使用PDO对象不正确吗?我是否必须PDO-> freeresult();不知何故?
答案 0 :(得分:0)
糟糕。容易犯的错误:第二个$ vararray中有一个额外的数据库字段,该字段不在数据库中。 PDO错误未打印,因为它已在我的查询语句类中被注释掉。
所以请记住打开错误报告工具。
这是我上面的代码的PDO错误修复:
private function __construct()
{
try
{
$this->_pdo = new PDO('mysql:host='. ConfigGlobal::get('mysql/host') .';dbname='. ConfigGlobal::get('mysql/db'), ConfigGlobal::get('mysql/username'), ConfigGlobal::get('mysql/password'));
$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //added this
}
catch (PDOException $e)
{
die($e->getMessage());
}
}