Help with PHP While function

元气小坏坏 提交于 2019-12-02 23:37:18

问题


Why is this not working?

<?php 
$select = "select * from messages where user='$u'";

$query = mysqli_query($connect,$select) or die(mysqli_error($connect));

$row = mysqli_num_rows($query);

$result = mysqli_fetch_assoc($query);

$title = mysqli_real_escape_string($connect,trim($result['title']));

$message = mysqli_real_escape_string($connect,trim($result['message']));

while(($result = mysqli_fetch_assoc($query))){
echo $title;
echo '<br/>';
echo '<br/>';
echo $message;
}

?>

where as this works -

<?php

echo $title;

?>

SORRY TO SAY, BUT NONE OF THE ANSWERS WORK. ANY OTHER IDEAS?


回答1:


If your mysqli query is returning zero rows then you will never see anything printed in your while loop. If $title and $message are not set (because you would want reference them by $result['title'] & $result['message'] if that are the field names in the database) then you will only see two <br /> tags in your pages source code.




回答2:


If the while loop conditional is not true then the contents of the while loop will never execute.

So if there is nothing to fetch from the query, then you won't see any output.




回答3:


Does you code display anything, or skip the output entirely? If it skips entirely, then your query has returned 0 rows. If it outputs the <br /> s, then you need to check your variables. I could be wrong, not knowing te entire code, but generally in this case you would have something like echo $result['title'] instead of echo $title




回答4:


Try this:

<?php 

$result = mysql_query($query);
while($row = mysqli_fetch_assoc($result)){
   echo $title.'<br/><br/>'.$message;
}

?>



回答5:


If $title and $message come from your mysql query then you have to access them through the $result array returned by mysqli_fetch_assoc.

echo $result['title'];
echo $result['message'];



回答6:


Also if your using mysqli you'd be doing something like this:

$mysqli = new mysqli("localhost", "user", "password", "db");

if ($result = $mysqli->query($query)) {

    while ($row = $result->fetch_assoc()) {
      print $row['title'];
    }

    $result->close();
}



回答7:


Does this work;

<?php 
$select = "select * from messages where user='$u'";

$query = mysqli_query($connect,$select) or die(mysqli_error($connect));

$row = mysqli_num_rows($query);

while(($result = mysqli_fetch_assoc($query))){
    echo $result['title'];
    echo '<br/>';
    echo '<br/>';
    echo $result['message'];
}

?>

Basically I've made sure that it's not picking the first result from the query & then relying on there being more results to loop through in order to print the same message repeatedly.



来源:https://stackoverflow.com/questions/4685717/help-with-php-while-function

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