我正在尝试这段代码:
if ($result = $this->mysqli->prepare("SELECT * FROM `mytable` WHERE `rows1`=?"))
{
$result->bind_param("i",$id);
$result->execute();
while ($data = $result->fetch_assoc())
{
$statistic[] = $data;
}
echo "<pre>";
var_dump($statistic);
echo "</pre>";
}
但它抛出以下错误
[2012 年 6 月 15 日星期五 12:13:11] [错误] [客户端 127.0.0.1] PHP 致命错误:
调用[myfile.php]中未定义的方法 mysqli_stmt::fetch_assoc()
我也尝试过:
if ($result = $this->mysqli->prepare("SELECT * FROM `mytable` WHERE `rows1`=?"))
{
$result->bind_param("i",$id);
$rows = $result->execute();
while ($data = $rows->fetch_assoc())
{
$statistic[] = $data;
}
echo "<pre>";
var_dump($statistic);
echo "</pre>";
}
这使得:
[2012 年 6 月 15 日星期五 12:22:59] [错误] [客户端 127.0.0.1] PHP 致命错误:
对非对象调用成员函数 fetch_assoc()
[myfile.php]
我还能做些什么来获得结果或者我做错了什么?我需要来自数据库的关联数组,看起来像$data[0]["id"] = 1
事实上你can很容易做到这一点,你只是不能用mysqli_stmt对象,你必须提取底层mysqli_result,您只需调用即可做到这一点mysqli_stmt::get_result()。注意:这需要 mysqlnd(MySQL 本机驱动程序)扩展,该扩展可能并不总是可用。
然而,下面关于推荐 PDO 而不是 MySQLi 的观点仍然有效,这是一个很好的例子:MySQLi 用户层 API 没有任何意义。我断断续续地使用 MySQLi 花了几年时间才发现上述机制。现在,我承认将语句和结果集概念分开确实有意义,但在这种情况下,为什么语句有一个fetch()
方法?值得深思(如果您仍然在 MySQLi 和 PDO 之间犹豫不决)。
为了完整起见,这里有一个(松散地)基于问题中原始代码的代码示例:
// Create a statement
$query = "
SELECT *
FROM `mytable`
WHERE `rows1` = ?
";
$stmt = $this->mysqli->prepare($query);
// Bind params and execute
$stmt->bind_param("i", $id);
// Extract result set and loop rows
$result = $stmt->get_result();
while ($data = $result->fetch_assoc())
{
$statistic[] = $data;
}
// Proof that it's working
echo "<pre>";
var_dump($statistic);
echo "</pre>";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)