Loop in PHP not working

对着背影说爱祢 提交于 2019-12-12 04:43:23

问题


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


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6721894/loop-in-php-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!