计数行,并且只有当准备好的PDO超过0行时才执行while循环

时间:2017-07-01 19:33:57

标签: php mysql pdo prepared-statement

我正在尝试使用准备好的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
    }
}

2 个答案:

答案 0 :(得分:2)

如下:

$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(); 

答案 1 :(得分:0)

您无需检查行数。只需改写:

$stmt = $pdo->prepare('...');
$stmt->execute([$categories_id, 1]);
$rows = 0;
while ($products_row = $stmt->fetch(PDO::FETCH_ASSOC) {
    // You can increment $rows only if some other condition is met if you want
    $rows++;
    // show row info
}
switch ($rows) {
    case 0:
        // No rows were retrieved.
        // run the 'different function' you mentioned in the comments
        break;
    case 24:
        print "There are two dozen rows in your results";
        break;
}

根据要求,如果没有结果,while循环将永远不会执行。如果有,它将循环每一个。