PHP-如何在有条件的情况下foreach SQL语句

时间:2018-10-10 06:50:56

标签: php sql mysqli

我想知道如何根据其状态预备一个sql count语句。当我试图回显它时,所有状态都变成数字1。我想将其放入循环中,而不是执行五次语句。

<?php
$statuses = array("In-process", "Approved", "Draft", "Approved" , "Rejected"); 

foreach ($statuses as $stat) {  
    $stmt = $db->prepare(
        "SELECT COUNT(status) FROM `m2_exception_requests`
         WHERE created_by= ? and   status = ?"
    ) or die($db->error);  

    $stmt->bind_param("ss", $user_id , $stat);
    $stmt->execute();
    $result = $stmt->store_result(); 

    if  ($stat = 'In-process') {
        $Inprocess1 =  $result;
    }
    if  ($stat = 'Approved') {
        $Approved1 =  $result;
    }
    if  ($stat = 'Draft') {
        $Draft1 = $result;
    }      
}

3 个答案:

答案 0 :(得分:2)

您可以使用GROUP BY来获取每种状态下的记录数;下面是简单的SQL查询;您将其转换为参数绑定;

SELECT status, COUNT(status) FROM `m2_exception_requests` WHERE `created_by` = ? AND `status` IN ("In-process", "Approved", "Draft", "Approved1" , "Rejected") GROUP BY `status`

答案 1 :(得分:2)

这是一个动态且SQL注入安全的解决方案:

这将使用INGROUP BY子句来生成结果。

$statuses = array("In-process", "Approved", "Draft", "Approved" , "Rejected");

$clause = implode(',', array_fill(0, count($statuses), '?')); //create your question marks
$types = 's' . str_repeat('s', count($statuses)); //create you bindings

$query = "SELECT COUNT(status) 
  FROM `m2_exception_requests`
  WHERE created_by = ? 
  AND status IN($clause)
  GROUP BY status";

$stmt = $db->prepare($query);
$stmt->bind_param($types, $user_id, ...$statuses);
$stmt->execute();
$resArr = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if(!$resArr) exit('No rows');
var_export($resArr);
$stmt->close();

祝你好运!

答案 2 :(得分:0)

您可以尝试一下。

<?php
$statuses = array("In-process", "Approved", "Draft", "Approved1" , "Rejected"); 

$statusVal = [];
foreach ($statuses as $stat) {  
    $stmt = $db->prepare(
        "SELECT COUNT(status) FROM 
            `m2_exception_requests`
            WHERE created_by= ? 
            and   status = ?"
    ) or die($db->error);  

    $stmt->bind_param("ss", $user_id , $stat);
    $stmt->execute();
    $count = $stmt->rowCount(); 

    $statusVal[$stat] = $count;
}

var_dump($statusVal);

您将获得像这样的值

[
    "In-process" => 1,
    "Approved" => 2,
    "Draft" => 3,
    "Approved1" => 4,
    "Rejected" => 5
]