开发者

PHP variable question

This works:

$customerBox = mysql_query("MY SQL STATEMENT HERE");  
$boxRow = mysql_fetch_array($customerBox);  

$customerBox = mysql_query("MY SQL STATEMENT AGAIN");
while($item = mysql_fetch_assoc($customerBox)) {
      foreach ($item as $columnName => $value) {
          if (empty($value)) {
               print $columnName;
          }
      }
}

This does not:

$cu开发者_如何学运维stomerBox = mysql_query("MY SQL STATEMENT HERE");  
$boxRow = mysql_fetch_array($customerBox);  

while($item = mysql_fetch_assoc($customerBox)) {
      foreach ($item as $columnName => $value) {
          if (empty($value)) {
               print $columnName;
          }
      }
}

Why? I guess I don't understand how variables work yet.


The problem is because since the query returns one row, there's nothing left to fetch.

the mysql_fetch_* functions fetch the current row and then advance the row pointer to the next one. If the current row doesn't exist, it returns false. So on your second call to mysql_fetch_assoc, the pointer is on the 2nd row, but that row doesn't exist so your loop isn't executed. You have two options:

Good: Remove the while loop, and change foreach to use $boxRow instead:

foreach ($boxRow as $columnName => $value) {
    //...
}

Ok: Rewind MySQL's row pointer using mysql_data_seek:

$boxRow = mysql_fetch_array($customerBox);
mysql_data_seek($customerBox, 0);
while(...){


This may have more to do with the mysql_fetch_array() than your variable. Try to put this:

mysql_data_seek ( $customerBox , 0 );

right before the while loop starts. I am curious to see the result.


$customerBox = mysql_query("MY SQL STATEMENT HERE");
$boxRow = mysql_fetch_array($customerBox);

while($item = mysql_fetch_field($customerBox)) { foreach ($item as $columnName => $value) { if (empty($value)) { print $columnName; } } }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜