0

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:

$customerBox = 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.

7
  • does the query return more than 1 row? If not, that's why the "error" exists ($boxRow takes the first row, and there are no more left for the next call to fetch)... Commented Dec 24, 2010 at 4:12
  • "MY SQL STATEMENT HERE" is different than "MY SQL STATEMENT AGAIN". duh. Commented Dec 24, 2010 at 4:12
  • what mysql query are you using Commented Dec 24, 2010 at 4:14
  • ircmaxell - only 1 row is returned. I'm not sure I understand though. Doesn't $customerBox equal the same thing regardless of what is fetched from it? Commented Dec 24, 2010 at 4:17
  • rajmohan - SELECT * FROM box WHERE customer_id='$logOptions_id' Commented Dec 24, 2010 at 4:22

3 Answers 3

5

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(...){
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

+1 since you did beat me to it (even though you had deleted your answer right after I posted my)...
0

$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; } } }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.