我需要访问一个DB,以便将查询获得的信息存储为一个数组,并通过API推送更多从外部获得的数据,最后存储更新后的数组。我的查询的核心在于每个客户的id,这个id是之前从API获得的,利用这个id我发起我的查询,看看DB中是否有信息,然而并不是每个客户都有数据存储在DB中,由于我很遗憾的是直接在生产中工作,所以我不敢测试如果我尝试推送空的 $newData
因为怕搞砸了(这就是为什么我不采用 array_push()
在测试代码中,我将在下面发布,但一个。var_dump($newData)
. 我试过好几种方法来跳过这个循环,每当出现这种情况时,我目前正在使用另一个 var_dump($msg)
来测试,但我无法设置正确的条件,所以消息从未出现。
这是我的查询和更新上述数组的代码。
$stmt = $conn->prepare('SELECT a.`zone`, b.`source_customer_billing_zone_id`, b.`source_external_subscriber_id`, SUM((CEIL(b.`duration`))/60) AS minutos, SUM((b.`source_customer_cost`)/100) AS total
FROM `billing`.billing_zones a INNER JOIN cdr b
ON a.`id` = b.`source_customer_billing_zone_id`
WHERE source_external_subscriber_id = :source_external_subscriber_id
GROUP BY b.`source_external_subscriber_id`, a.`zone`
ORDER BY total desc');
$stmt->execute(array('source_external_subscriber_id' => $source_external_subscriber_id));
foreach ($stmt as $row) {
$newData = [
'name' => $row['zone'],
'sku' => $row['source_customer_billing_zone_id'],
'units' => $row['minutos'],
'subtotal' => $row['total'],
'tax' => 21,
'account' => $account
];
array_push($invoice['products'], $newData);
}
$invoice
是我从API中创建的数组 我必须把DB信息附加到这个数组上 每当 $source_external_subscriber_id
在DB中有条目的情况下,它可以完美地工作,但如果id不存在,我不知道如何跳过该id的循环。
目前,我已经尝试了好几种方法,但似乎都不奏效。$msg
永远不会显示。
/* 1 */
foreach ($stmt as $row) {
if (!empty($row) && $row != "") {
$newData = [
'name' => $row['zone'],
'sku' => $row['source_customer_billing_zone_id'],
'units' => $row['minutos'],
'subtotal' => $row['total'],
'tax' => 21
];
var_dump($newData);
}else{
$msg = "There are no entries";
var_dump($msg);
}
}
/* 2 */
if (!empty($stmt)) {
foreach ($stmt as $row) {
$newData = [
'name' => $row['zone'],
'sku' => $row['source_customer_billing_zone_id'],
'units' => $row['minutos'],
'subtotal' => $row['total'],
'tax' => 21
];
var_dump($newData);
}
}else{
$msg = "There are no entries";
var_dump($msg);
}
/* 3 */
if (!is_array($stmt)) {
$msg = "There are no entries";
var_dump($msg);
}else{
foreach ($stmt as $row) {
$newData = [
'name' => $row['zone'],
'sku' => $row['source_customer_billing_zone_id'],
'units' => $row['minutos'],
'subtotal' => $row['total'],
'tax' => 21
];
var_dump($newData);
}
}
-UPDATE-
当尝试我想到的第三种解决方案时,总是显示出 $msg
因为它并不是一个真正的数组。当我转储变量的时候,出现的是查询。我不知道该怎么做.谢谢大家的帮助!
你可以使用 PDOStatement
's rowCount
来查找是否有任何命中,然后再对其进行迭代。
if ($stmt->rowCount()) {
foreach (...) {
}
else
{
print("Display error message here");
}
另一种选择是不直接遍历语句,而是先取行,然后再决定怎么做。
$rows = $stmt->fetchAll();
if ($rows)
{
foreach ($rows as $row)
{
..
}
}
else
{
// display error message
}