如何遍历PDO语句并在if语句上写入数据

时间:2015-07-14 19:41:46

标签: php mysql foreach while-loop

对于令人费解的头衔感到抱歉,但我不确定如何解释它。我有一个包含138个用户的数据库,但是用户133-138已从数据库中删除以用于管理目的。出于商业目的,我不想改变其他人的行为。 "用户ID。"我编写了一些脚本来从MySQL获取PDO对象的销售信息。我指望"计数(结果)"在foreach循环中PDO,当计数等于' result2'时,它将数据写入mPDF中的表。

这是问题开始的地方,它完全有效,直到达到计数133,其中没有用户。它不打印任何东西(因为它不应该),但是也会跳过剩余的数字。它没有为用户139-146完成循环。我该如何解决?

这是我的代码:

$stmt = $con->prepare("select u.user_id, u.fname, u.lname, d.saledate, d.custname, d.straddr, d.city, d.state, d.zip
from users u
inner join dplgalionsales d
on u.lname = d.agent_last_name
where saledate > DATE_SUB(NOW(), INTERVAL 1 MONTH)
order by u.user_id asc, saledate asc");
$stmt->execute();
$res = $stmt->fetchAll();
$count = 1;
foreach($res as $result) {
    $size = count($result['user_id']);
    $mydate = date('m/d/Y');
    $dateadd = date('m/d/Y', strtotime($mydate. ' + 3 days'));  
    $html_table = '<div>Week Ending: ' .$mydate. '<br>Payroll Issued: ' .$dateadd. '</div><br>';
    $html_table .= '<table border="1" cellspacing="0" cellpadding="2" width="100%"><tr><th>Date</th><th>Customer Name</th><th>Address</th></tr>';
    while($count < $size) {
        if($val == $result['user_id']) {
            $html_table .= '<tr><td>' .$result['saledate']. '</td><td>' .$result['custname']. '</td><td>' .$result['straddr']. ' ' .$result['city']. ' ' .$result['state']. ' ' .$result['zip']. '</td></tr>';
        }
        $count += 1;
    }
    $html_table .= '</table>'; //ends HTML table
    $mpdf = new mPDF();
    $mpdf->SetTitle('DPL Galion Sales');
    $mpdf->WriteHTML($html_table);
    if(is_dir('../reports/'.$count.'')) {
        $mpdf->Output('../reports/'.$count.'/DPLOH/'.date('m-d-Y').'_DPLOH_SalesID_'.$count.'.pdf','F');
    }
}
exit;

1 个答案:

答案 0 :(得分:1)

抱歉,我一开始没有收到您的密码。

这样做

$res = $stmt->fetchAll(PDO::FETCH_GROUP);
foreach($res as $user_id => $user_data) {
    $mydate = date('m/d/Y');
    $dateadd = date('m/d/Y', strtotime($mydate. ' + 3 days'));  
    $html_table = '<div>Week Ending: ' .$mydate. '<br>Payroll Issued: ' .$dateadd. '</div><br>';
    $html_table .= '<table border="1" cellspacing="0" cellpadding="2" width="100%"><tr><th>Date</th><th>Customer Name</th><th>Address</th></tr>';
    foreach ($user_data as $result) {
        $html_table .= '<tr><td>' .$result['saledate']. '</td><td>' .$result['custname']. '</td><td>' .$result['straddr']. ' ' .$result['city']. ' ' .$result['state']. ' ' .$result['zip']. '</td></tr>';
    }
    $html_table .= '</table>'; //ends HTML table
    $mpdf = new mPDF();
    $mpdf->SetTitle('DPL Galion Sales');
    $mpdf->WriteHTML($html_table);
    if(is_dir('../reports/'.$user_id.'')) {
        $mpdf->Output('../reports/'.$user_id.'/DPLOH/'.date('m-d-Y').'_DPLOH_SalesID_'.$user_id.'.pdf','F');
    }
}