Search code examples
phpmysqlfor-loopmysql-num-rows

mysql_num_rows not working sort of


I got this

for($i = 1; $i < 301; $i++)
{
    $r8 = mysql_query("SELECT * FROM full_dump WHERE id_fd='".$last_id."' AND field_".$i." LIKE '%JAL?%' order by field_".$i." desc limit 0,1")or die(mysql_error());
    if ( mysql_num_rows($r8) == 1){
        while($row = mysql_fetch_array($r8))
        {
            $i4 = $i+1;
            $jalfd = trim($row['field_'.$i4.'']);
        }
    }
    else {
        $jalfd = "N/A";
    }
}

It is part of a pile_upload script. All works but not this. When I upload a file it may or may not contain the word JAL? and the next line has its value. No matter what, the end value of jalfd is N/A. When I do

echo mysql_num_rows($r8);

I get the following when I have JAL? in the text file (you'll see a 1 in there)

000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

an when I don't have JAL? (there is no 1)

000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

I even tried

if ( intval(mysql_num_rows($r8)) == 1){

with no luck.


Solution

  • No matter what, the end value of jalfd is N/A

    With your Logic, the value of $jalfd after the end of the loop only depends upon your 300th loop iteration. On every iteration you are overwriting it. If your 300th iteration resulted in rows not being 1 you will get $jalfd="N/A" regardless of what the previous values were.

    A simple fix using your design itself, will be to initialize the value

    $jalfd = "N/A";
    

    before your loop starts, and remove the else section completely. It wont be needed then.