+ 1

I need help fetching posts from my database using php.

https://code.sololearn.com/w0tS17Fc1n2X/?ref=app hey so thats my code im trying to use to fetch posts from my database named "ent1010" from the table "discussion" .... what I would like to do is display in DESC order from column "posts". what im I doing wrong?!

1st Mar 2018, 3:08 PM
Antony O. Onyango
Antony O. Onyango - avatar
2 Respuestas
+ 2
You are pretty much there, you just need to adjust your sql a little like below. SELECT * FROM discussion ORDER BY posts DESC Also in the while loop, set the rows to a string and declare it that way. For example, $posts = $row['posts']; Then, echo "<p>'. $posts .'</p>"; Helps keep your code a little cleaner and easier to read. Also as a note, you should really be using PDO for best practice. See below <?php $host = 'localhost'; $user = 'username'; $pass = 'password'; $database = 'my_database'; $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false ); $pdo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options); $stmt = $pdo->prepare('SELECT * FROM table ORDER BY posts DESC'); $stmt->execute(); while ($row = $stmt->fetch()){ $posts = $row['posts']; echo $posts; } ?>
1st Mar 2018, 4:40 PM
ihateonions
0
@ihateonions thanks alot... I know I should be using PDO but I was kind of in a hurry to make it work and PDO process seemed abit complex to read and understand as I am still learning how to get to the back end so thats why I wanted to get a grasp on Mysqli first then ill take my time later.
1st Mar 2018, 6:01 PM
Antony O. Onyango
Antony O. Onyango - avatar