Jump to content

[SOLVED] multiple calls to mysql_fetch_array() giving unexpected results


labiere

Recommended Posts

I've been making some simple queries to a mysql table from within a PHP script.

Everything works as expected the first time I loop and use the mysql_fetch_array function. Once I break out of the loop and start a new loop, the function no longer appears to be iterating from where it left off.. or at all.. It's not like I just end up getting the wrong row back from the loop, Suddenly my variable $row seems to have nothing assigned to it at all.

 

 

<?php
// Connecting, selecting database
$link = mysql_connect('mysql.domain.com', 'user', 'password')
    or die('Could not connect: ' . mysql_error());
mysql_select_db('db_trial') or die('Could not select database');

// Grab a subset of rows that match an expression. This works.
$query = "SELECT * FROM products WHERE item REGEXP '^($collection)[0-9]'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Iterate through the subset of rows until some condition is met... This works.
$i=0;
do {
        $row = mysql_fetch_array($result, MYSQL_NUM);
$i++;
} while ($i != 4 * ($page - 1) + 1);

//Now that we have the correct row, use its values to create some variables.. This works
$p = 0;
$product_thumb[$p] = './images/'.$row[0].'.jpg'; // echo output is "./images/xxy32.jpg"
$product_name[$p] = $row[1]; // echo output is "WEED WHACKER"

//Now I want to continue iterating through the subset and create some more variables. This does not work!!
while ($row = mysql_fetch_array($result, MYSQL_NUM) && $p<3) {
$p++;
$product_thumb[$p] = './images/'.$row[0].'.jpg';
$product_name[$p] = $row[1];
echo $product_thumb[$p];  // output is "./images/.jpg"
echo $product_name[$p]; //nothing is output
}

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);

?>

 

Can anyone explain what is going on here?

Do you know how many rows you're supposed to be catching? maybe you're only catching a few.

 

The number of rows has worked fine so far. In my actual code I have it peppered with echo statements including a count of num_rows. I have checked the number of rows of $result in the line just before entering the final WHILE loop, and am seeing the correct numbers there.

 

 

 

Well I finally found the source of the problem.. It had to do with the order of operators in my WHILE condition:

 

while ($row = mysql_fetch_array($result, MYSQL_NUM) && $p<3) {

 

was bracketed and changed to this:

 

while (($row = mysql_fetch_array($result, MYSQL_NUM)) && ($p<3)) {

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.