Connection Error with MySQL

-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 loads and does not return the database information.

Database:

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

Connection:

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

And the page only loads and returns nothing.

Thank you des de already!

    
asked by anonymous 20.09.2016 / 09:40

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 condition of while , ie:

while($row = mysql_fetch_assoc($sql))

This is because the function mysql_fetch_assoc returns an associative array that matches the obtained row and moves the internal data pointer to the next row.

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

When there are no more rows, the function returns false by stopping the while cycle.

    
20.09.2016 / 11:24
1

I do not know PHP , but I believe that the mysql_fetch_assoc($sql); method must exist within while() { } , so it will load a new line every time in the while.

Try something like this:

while($row = mysql_fetch_assoc($sql)) { }
    
20.09.2016 / 10:03