gpt4 book ai didi

php - 为什么 fetch_all 语句之后的 fetch 语句没有任何值?

转载 作者:行者123 更新时间:2023-11-29 18:43:06 24 4
gpt4 key购买 nike

我想在循环中输出myTable的编号并输出myTable的field1。

但是,如果我运行以下代码,只会打印 10 个“test :”。

如果我删除 [$rows = $statement->fetchAll(PDO::FETCH_ASSOC);] 并将 for() 的 $count 更改为 10,它工作正常,但这不是我想要的。

<?php
$db = new PDO("mysql:host=localhost;dbname=mydb;charset=utf8;", myid, mypw);
$statement = $db->query('select field1 from myTable limit 10');
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
$count = count($rows);
echo "count : $count<br><br>";
for($i = 0; $i < $count; $i++)
{
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo 'test : '.$row['field1'].'<br>';
}
?>

我想避免使用以下方法来计算 myTable 的数量。因为不必要地添加了看起来相似的查询语句。

$count = $db->query('SELECT count(*) FROM qudtls_mutter')->fetchColumn();

最佳答案

结果,来自

$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

将是关联数组,您需要对其进行计数。

您可以简单地使用 $statement->rowCount():int这将返回上次查询的计数。

然后你可以将它与FOR混合使用

for ($i=0; $i<$statement->rowCount(); $i++) {

}

对于其他用途,您可以使用WHILE

while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {

}

要使用foreach,只需:

foreach ($statment as $row) {

}

关于php - 为什么 fetch_all 语句之后的 fetch 语句没有任何值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44816774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com