开发者

PHP non eof-recordset returning empty values

i'm having a strange problem with php + recordsets. my code:

    $rc = mysql_query("select * from myTable",$db);
    if (!$row = mysql_fetch_assoc($rc))
    {
        $eof=true;
    }else{
        echo "there is data!<br>";
        $rs = mysql_fetch_array($rc);
        echo $rs[id];
        echo $rs[txt];
    }

the strange thing - the query is c开发者_C百科orrect - it's echoing "there is data" but when echoing the actual field values returns empty strings .. :(

any ideas what could be wrong?


In your else block, you are re-fetching some data from the database, using mysql_fetch_array().

But a first row has already been fetched earlier, by mysql_fetch_assoc().


So, basically :

  • In the if's condition, you are fetching a first row
  • If it succeed, you enter the else block
    • where you try to fetch a second row
    • and using the returned (or not) data, without testing the success of that second fetch.


You should probably do only one fetch -- using either mysql_fetch_assoc or mysql_fetch_array -- but not two.


you already fetched data, use mysql_num_rows() instead

$rc = mysql_query("select * from myTable",$db);
if (mysql_num_rows($rc))
{
    echo "there is data!<br>";
    $rs = mysql_fetch_array($rc);
    echo $rs[id];
    echo $rs[txt];

}else{
    $eof=true;
}


Be consistent in your use of if mysql_fetch_assoc($rc)...

$rs = mysql_fetch_array($rc); 

will return an enumerated array, so $rs['id'] doesn't exist only $rs[0], $rs[1], etc.

Use

$rs = mysql_fetch_assoc($rc);

to return an associative array with $rs['id']

Your first test also fetches and discards a row

And quote the indexes in $rs: $rs['id'] rather than $rs[id]

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜