Jump to content

Generate JSON with PHP from MySQL DB?


Texan78
Go to solution Solved by Texan78,

Recommended Posts

Hello, 

 

I am trying to query a MySQL database to output it in a JSON format without having it write to a new file I.E. file.json. I can create a script that creates a json array but, I need the output in a JSON format. The script I have been working with below connects to the DB but, it is not populating with data. It just gives me this output. I added the DB connection check to check if the script was connecting to the DB.

Connected successfully{"streamers":[]}

 

 

This is the code I am currently working with. Is there anyone who could tell me what I am missing and could improve on. DB info removed for security reasons.

<?php

header('Content-type:application/json;charset=utf-8');

//Make connection to database
$db=new PDO('mysql:dbname=streamdb;host=localhost;','root',''); 

// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully";

//Prepare the query for analyzing 
$sql=$db->prepare('select * from maintable');

$response = array();
$streamers = array();
$result=mysql_query($sql);
while($sql=mysql_fetch_array($result)) 
{
$displayname=$row['DisplayName'];
$streamkey=$row['StreamKey'];

$streamers[] = array('DisplayName'=> $displayname, 'StreamKey'=> $streamkey);

}

$response['streamers'] = $streamers;

echo stripslashes(json_encode($response));

?>

-Thanks!

Link to comment
Share on other sites

  • Solution

I got it sorted with this solution and seems to work great and is lightweight. 

<?php
$pdo = new PDO('mysql:dbname=_streamdb;host=localhost;','root','password', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
$result = $pdo->query('SELECT DisplayName, StreamKey, StreamURL, gpsStatus, UserLat, UserLon, UserHeading, UserLocation, UserLocation, streamStatus, CurrentViewers, TimeStamp FROM maintable');
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json;charset=utf-8');
echo json_encode(['streamers' => $rows],
        JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

?> 
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.