0

I am trying to get all rows in database. My code:

$sql = "SELECT * FROM lectors";

$array = array();
while($row =  mysqli_fetch_assoc(mysqli_query($con,$sql))){
    echo $row["name"];
}

While I send request, server doesn't reply. Any ideas?

4
  • Where do you initialise your $con SQL connection? Commented Feb 3, 2016 at 15:37
  • 1
    Do the mysqli_query($con,$sql) as a single step before your while, and the mysqli_fetch_assoc() in the while.... because I'm sure you've never seen a working example or anything in the PHP Docs that combines everything inside the while Commented Feb 3, 2016 at 15:39
  • @BenPearlKahan, in another php file: $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect'); Commented Feb 3, 2016 at 15:39
  • php.net/manual/en/mysqli.error.php and use that against your query Commented Feb 3, 2016 at 15:50

2 Answers 2

5
while($row =  mysqli_fetch_assoc(mysqli_query($con,$sql))){

This is a never ending loop, your query will execute fine every time and loop will never terminate.

Need I say further?

It is only as good as

while(true)
{
   // keep querying my database until i run out of resources
}

Execute the query first and loop over its result only.

And Oh,

While I send request, server doesn't reply

Because, as i said; It is busy running in a circle, has no time to reply.

Sign up to request clarification or add additional context in comments.

2 Comments

But my code works fine with loop. My problem was in lines, see below answer.
Nope it doesn't. If you did understand, that answer speaks this same language. Just that it provides a copy paste solution without much of an explanation so it fixes your problem but you still don't know what the problem was :)
1

Try to put the query in a line by itself, such as...

$sql = "SELECT * FROM lectors";
$array = array();
$res = mysqli_query($con,$sql);
while($row =  mysqli_fetch_assoc($res)){
    echo $row["name"];
}

Doing it in the method you are above will result in each execution of the loop executing the database query.

1 Comment

Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.