- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在尝试这段代码:
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>";
}
但它抛出以下错误
[Fri Jun 15 12:13:11 2012] [error] [client 127.0.0.1] PHP Fatal error: Call to undefined method mysqli_stmt::fetch_assoc() in [myfile.php]
我也试过:
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>";
}
这使得:
[Fri Jun 15 12:22:59 2012] [error] [client 127.0.0.1] PHP Fatal error: Call to a member function fetch_assoc() on a non-object in [myfile.php]
我还能做些什么来获得结果或我做错了什么?我需要来自数据库的 assoc 数组,看起来像 $data[0]["id"] = 1
最佳答案
事实上,您可以很容易地做到这一点,只是不能用mysqli_stmt
做到这一点。对象,你必须提取底层 mysqli_result
,您只需调用 mysqli_stmt::get_result()
即可完成此操作.注意:这需要 mysqlnd(MySQL native 驱动程序)扩展,它可能并不总是可用。
但是,下面关于推荐 PDO 而不是 MySQLi 的观点仍然成立,这是一个很好的例子来说明原因:MySQLi userland 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>";
关于php - 如何从准备好的语句中获取 assoc 数组中的所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11048622/
我是一名优秀的程序员,十分优秀!