gpt4 book ai didi

php - 计算行数,仅当准备好的 PDO 多于 0 行时才执行 while 循环

转载 作者:行者123 更新时间:2023-11-29 02:13:38 26 4
gpt4 key购买 nike

我正在尝试使用准备好的 PDO 语句执行 while 循环,但我只希望它在有任何行时执行。目前我正在使用它,但它似乎缺少第一个结果,大概是因为它移动了指针。

正确的做法是什么?

$stmt = $pdo->prepare('SELECT * FROM products p 
INNER JOIN products_to_categories c
ON p.products_id = c.products_id
WHERE c.categories_id = ?
AND products_status=?
ORDER BY p.products_sort_order,p.products_name');
$stmt->execute([$categories_id,1]);
if(($category_row = $stmt->fetch(PDO::FETCH_ASSOC)) != null) {
$no_results = count($stmt->fetch(PDO::FETCH_ASSOC));
while ($products_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// show row info
}
}

最佳答案

比如:

$stmt = $pdo->prepare('SELECT * FROM products p INNER JOIN products_to_categories c ON p.products_id = c.products_id
WHERE c.categories_id = ? AND products_status=? ORDER BY p.products_sort_order,p.products_name');
$stmt->execute([$categories_id,1]);
$products_row="some_random_string";
while ($products_row = $stmt->fetch(PDO::FETCH_ASSOC) && $product_row!="some_random_string" && $product_row!=false) {
// show row info
}

既然你谈到了行数,

$result = $con->prepare("SELECT count(*) FROM `products`"); 
$result->execute();
$number_of_rows = $result->fetchColumn();

关于php - 计算行数,仅当准备好的 PDO 多于 0 行时才执行 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44864699/

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