Mysql connection error

Asked

Viewed 104 times

-1

I’m using this code:

<php?
$sql = mysql_query("SELECT `id`, `detail`, `time` FROM `news` ORDER BY `time` DESC LIMIT 5");
$return = mysql_fetch_assoc($sql); 
while($row = $return) { ?> 
    Data: <?php echo date("d/m/Y", $row['time']); ?> | 
    Noticia: <?php echo $row['detail']; } ?>

And when I run this code, the page keeps loading and does not return the database information.

Database:

Banco de Dados

The connection to the database is on another page, I used the require(); to pick up the connection.

Connection:

<?php error_reporting(0); $mysql = mysql_connect('localhost', 'root', ''); mysql_select_db('central');

And the page just loads and returns nothing.

Thank you so much!

  • Just advice, avoid the use of functions mysql_*, use mysqli_* (note who a letter "i"). I don’t mean that it solves the problem. What you should solve are the answers below. This is just a warning to avoid further problems as these functions have been removed in the latest versions of PHP.

2 answers

6


The problem is in the following 2 lines:

//...
$return = mysql_fetch_assoc($sql); 
while($row = $return) { ?> 
//...

The function mysql_fetch_assoc must be within the while, that is, like:

while($row = mysql_fetch_assoc($sql))

That’s because the function mysql_fetch_assoc returns an associative matrix that corresponds to the obtained line and moves the internal pointer of the data to the next line.

For example, if your query returns 10 lines, the function mysql_fetch_assoc will get the data from the first line, change the internal pointer to the second line and so the cycle runs 10 times until at 11th the result is false, since there are no more lines.

When there are no more lines, the function returns false interrupting the cycle while.

1

I don’t know PHP, but I believe the method mysql_fetch_assoc($sql); must exist within the while() { }, so it will load a new row every turn in while.

Try something like that:

while($row = mysql_fetch_assoc($sql)) { }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.