开发者

Loop in PHP not working

$qPhysician = mysql_query("SELECT * FROM physicians");
$num = mysql_num_rows($qPhysician);
$i=0;
while($i < $num)
{
    "<tr>开发者_运维技巧";
    "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
    "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
    "</tr>";
    $i++;
}

I get blank result.

If I echo $num, I get "19" which is the number of rows in my DB. If I echo $rowPhysician['lastName'] just to test out if I get records, I get at least 1 record of last name. I don't know if there is something wrong with "while". Please help me out.


Are you missing the echo to print out the strings?

while($i < $num) {
    echo "tr";
    echo "td" . mysql_result($qPhysician,$i,"lastName") . "/td";
    echo "td" . mysql_result($qPhysician,$i,"firstName") . "/td";
    echo "/tr";
    $i++;
}


Technically, this isn't an answer, but it is easier to show the code this way:

// first, only take the records you need -- each record adds more time to
// query, so if you only need 2, only select 2.
$query = mysql_query("SELECT lastName, firstName FROM physicians");

// mysql_fetch_assoc returns an associative array of all of the columns
// mysql_fetch_row   returns a numerically indexed array.
// mysql_fetch_array returns an array with both numeric and string indexing.
// they will all return FALSE when there are no more results in the query.
while( $arr = mysql_fetch_assoc( $query ) )
{
    echo "<tr>";
    // Now, use array indexing.
    echo "<td>" . $arr[ "lastName" ] . "</td>";
    echo "<td>" . $arr[ "firstName" ] . "</td>";
    echo "</tr>";
}

It is a very rare circumstance that mysql_result is actually a better option -- usually it is better to just populate a couple of arrays in PHP and be done with the DB.


Anyways echo'ing HTML is bad practice. The more correct output could should look like

...
while($i < $num) :?>
    <tr>
      <td><?php echo mysql_result($qPhysician,$i,"lastName"); ?></td>
      <td><?php echo mysql_result($qPhysician,$i,"firstName") ?></td>
    </tr>
<?php $i++; endwhile;
...

Note that you wrote closing HTML wrong, too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜