PHP布尔错误(T_BOOLEAN_OR)

时间:2013-10-24 10:48:03

标签: php

在语法

方面,此代码有任何问题
    $i=0;
while ($r=$sth->fetch(PDO::FETCH_ASSOC))||($a=$sth_temp->fetch(PDO::FETCH_ASSOC)) {
  $i++;
  $itemcount=countitemsofuser($r['id']);
  echo "\n<tr>";
  echo "<td><a class='editid' href='$scriptname?action=editsoftware&amp;id=".$r['id']."'>{$r['id']}</a></td>\n";
  echo "<td>{$r['manufacturerid']}</td>\n";
  echo "<td>{$r['stitle']}</td>\n";
  echo "<td>{$r['sversion']}</td>\n";
  echo "<td>{$a['stype']}</td>\n";

感谢您的支持。

1 个答案:

答案 0 :(得分:2)

你有一个关闭)太多:

while ($r=$sth->fetch(PDO::FETCH_ASSOC))||($a=$sth_temp->fetch(PDO::FETCH_ASSOC)) {
                                   //here

应该是:

while ($r=$sth->fetch(PDO::FETCH_ASSOC)||($a=$sth_temp->fetch(PDO::FETCH_ASSOC)) {

即便如此,这段代码并不是我所说的好的代码。您正在从两个语句中的任何一个中获取数据,而不是同时从两个语句中获取数据...... 从不两者,实际上,由于PHP使while条件短路。让我们用if:

替换while
if ($r = $sth->fetch(PDO::FETCH_ASSOC) || $a = $sth_temp->fetch(PDO::FETCH_ASSOC))
    //if fetched, $r is truthy, and this branch will be executed
   //    the second expression (right of the || operator) need never be evaluated

由于短路评估,当第一个条件的计算结果为true时,PHP不会执行第二个表达式($a = ...)。 如果第一次获取调用是真实的,则while循环条件为真,只是因为意味着:如果这或那是真的。在评估第二个表达式时没有意义,条件的结果是给定的:它是真的。

因此,基本上,循环将遍历$sth->fetch()的所有结果集,并且一旦没有任何剩余要提取,那就是调用$sth_temp->fetch时。你可以写下这个:

while($r = $sth->fetch(PDO::FETCH_ASSOC))
{
    //process $r
}
while(false || $a = $sth->fetch(PDO::FETCH_ASSOC))
{//the false is what $sth->fetch() would be after a while in your code
    //process $a
}

不是你想要的,是吗?即便如此:因为您使用了||运算符,您承认在某些情况下,您正在执行的2个fetch调用之一可能会失败,而 in while循环,您只需假设为$a$r分配了关联数组:

$itemcount=countitemsofuser($r['id']);
//...
echo "<td>{$a['stype']}</td>\n";

这只是所有错误的阴影。如果您想同时处理数据,请使用&&

while($r = $sth->fetch(PDO::FETCH_ASSOC) && $a = $sth_temp->fetch(PDO::FETCH_ASSOC))
{
}

避免短路评估的问题。但是,当这些提取调用之一返回false时,您将必须处理剩余的数据,如下所示:

$leftRow = $a ? $a : $r;//get the fetched data from the resultset that isn't empty
$left = ($a ? $sth_temp : ($r ? $sth : false));//get the object on which to fetch
if ($left)
{//if there are some left:
    do
    {//begin with row that was already fetched
        //process $leftRow
    } while($leftRow = $left->fetch(PDO::FETCH_ASSOC));//and keep fetching
}

但那太糟糕了,不是吗 您更有可能通过更改查询来轻松解决此问题并更有效地 ,例如使用JOIN ...