Created
April 30, 2019 17:31
-
-
Save melissacabral/7917e998e39c7cedca30482b3dc70379 to your computer and use it in GitHub Desktop.
Make a JSON object from a mysql query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php //connect to DB | |
require('config.php'); | |
include_once('includes/functions.php'); | |
//get 10 of the recent published posts out of the DB | |
$query = "SELECT posts.title AS post_title, posts.body AS description, posts.image AS url, users.username | |
FROM posts, users | |
WHERE posts.user_id = users.user_id | |
AND posts.is_published = 1 | |
ORDER BY date DESC | |
LIMIT 10"; | |
//run it | |
$result = $db->query($query); | |
//check it | |
if(! $result){ | |
die($db->error); | |
} | |
if( $result->num_rows >= 1 ){ | |
$data = array(); | |
while($row = $result->fetch_assoc()){ | |
$data[] = $row; | |
} | |
} //end if there are rows | |
print(json_encode($data, JSON_UNESCAPED_SLASHES));?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment