Return MySQL data in JSON format - php

I am a novice when it comes to working with JSON/PHP. I have been trying to get this to work based off this answer.
How to generate .json file with PHP?
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 since I am pulling dynamic data. 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 from the example link above 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!

First, use PDO only. No mysql_* functions.
Then your code should look like this:
$pdo = new PDO('mysql:host=...', 'username', 'password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$result = $pdo->query('SELECT DisplayName, StreamKey FROM ...');
$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);
The PDO::ERRMODE_EXCEPTION sets PDO to throw all errors as exceptions, so they can be handled in an easy and consistent way.
The PDO::FETCH_ASSOC sets fetchAll() to return rows as arrays where column names are used as array keys.
The json_encode() will take care of producing a valid JSON output. Since you are not embedding JSON into HTML, there is no need for escaped slashes and we will make it nicely indented for easier debugging.

So as I said in a comment, the problem is probably that "$row" is not initialized. It should probably be:
while($row=mysql_fetch_array($result))
Also, you used mysql_ functions which are not compatible with PDO. You should do your request using $db->query.
As you asked for suggestions, I may give you a trick that I use.
I think that it's a lot of code for just retrieving a table that is basically the content of the result of your query (in $result). And I guess you have similar code for almost every request. So what I do in general is that I build a generic function called extractResult that directly makes an array of lines from the result of a query.
Here is the function:
/**
* Extract a php array from the result of a db query.
* This result can be directly parsed in JSON for instance.
*/
function extractResult($res) {
$arr = array();
while($line = $res->fetch()) {
$count = count($line)/2;
for ($i=0; $i<$count; $i++) {
unset($line[$i]);
}
array_push($arr, $line);
}
return $arr;
}
Note: the for loop with the "unset" is made to remove the entries with digits. What's returned by a fetch is something like this:
Array("DisplayName" => "Loulou", 0 =>"Loulou", "StreamKey" => 12, 1 => 12)
So it removes the numerical duplicates.
So you could use it like this and your code becomes way lighter:
<?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";
$result=$db->query('select display_name AS DisplayName, stream_key AS StreamKey from maintable');
$response = array();
$response['streamers'] = extractResult($result);
echo json_encode($response);
?>
Note that you have to specify the columns name that you want directly in the request! :)
Don't know if it's nteresting, but I always use this trick so building JSON from DB is so much easier and lighter. :) Good luck.

Here you can check the working code
<?php
$con=mysqli_connect($servername,$username,$password,$databasename);
if (mysqli_connect_errno())
{
echo "Connection Error" . mysqli_connect_error();
}
$query = "SELECT * FROM TableName";
$result = mysqli_query($con,$query);
$querydata = array();
while($data = mysqli_fetch_array($result)) {
$querydata[] = $data;
}
echo json_encode($querydata);
mysqli_close($con);
?>

Related

I am using PHP ODBC to write to an access database, but it won't write to the database

I'm trying to use PHP/ODBC to connect to an access file. The problem is that I can read from the database but I can't write to it using the below:
$conn = odbc_connect('SKW-DB','','');
if (!$conn)
{
exit ("ODBC Connection Failed ". $conn);
}
$stmt = "INSERT INTO PRODUCT (ProductCode, ProductName) VALUES ('TestCode', 'TestEntry')";
$result = odbc_exec ($conn,$stmt);
echo "Result1: ";
echo $result;
$result returns nothing. Again, I am able to read from the database, connectivity isn't an issue. I just can't write to it.
That's because you're simply ASSUMING the query can never fail. It did fail, and returned a boolean false. echo false literally prints out nothing.
Try this instead:
$result = odbc_exec($conn, $stmt);
if ($result === false ) {
die(odbc_errormsg($conn));
}
And what you get back from odbc_exec() cannot be echoed out anyways. On success, it returns a statement handle, which is NOT something you can simply print out.
Sounds like you need a little more debugging code.
First, try var_dumping the $result instead of echoing it.
var_dump($result);
There's certain PHP variable types that echo can't/won't display.
Next -- chances are your query's causing an error of some sort, so try using the odbc error reporting functions after making your query
$result = odbc_exec ($conn,$stmt);
echo "Result1: ";
var_dump( $result );
if($result)
{
var_dump( odbc_error($conn) );
var_dump( odbc_errormsg($conn) );
}

unable to print oracle database query data in php

I want to print a value that taken from oracle database. but it is showing error.
Below is my code.
<?php
// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('FUNREAD', 'clock24', '10.6.8.51:1525/DRFUNPD1');
if (!$conn)
{
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$atp1 = oci_parse($conn, 'select count(*) as count from ATP1.PENDING_MESSAGE');
oci_execute($atp1);
$atp1 = oci_fetch_array($atp1);
echo $atp11;
?>
But I am not getting right output. Below output I am getting.
Resource id #4
You're trying to echo a resource result, where what you need to do is to either retrieve the first row and output that, or loop over the results and output them:
while ($row = oci_fetch_array($atp1)) {
print_r($row);
}
Note that fundamentally it's probably a good idea not to re-use the $atp1 variable for both the query and the result set, use something more descriptive, e.g.:
$query = oci_parse($conn, 'select count(*) as count from ATP1.PENDING_MESSAGE');
oci_execute($query);
while ($row = oci_fetch_array($query)) {
print_r($row);
}
I'm pretty much copying this straight out of the manual (since I haven't used Oracle functions in PHP before)...

Json Encoding Issue in Database Connection [duplicate]

This question already has answers here:
php warning: mysqli_close() expects parameter 1 to be mysqli
(2 answers)
Closed 2 years ago.
I am having a slight problem when I try to connect to a db remotely and I would be really grateful for any tips. Here is the code:
$con=mysqli_connect($port, $username, $password, $database);
$sql = "SELECT name, date FROM `view_tickets`;";
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
mysqli_close($result);
mysqli_close($con);
I want to result in json to be able to run this from a mobile app. At the moment nothing is displaying on the browser (I am running Xampp). I added some prints and can confirm that the connection is successful and the array is being filled properly. I managed to print it out using print_r(array_values($resultArray));
Is something wrong with my json?
I don't know if this helps but noticed that I am getting the following warning;
Warning: mysqli_close() expects parameter 1 to be mysqli, object given in /Applications/XAMPP/xamppfiles/htdocs/www/service.php on line 39
This corresponds to mysqli_close($result);
Any ideas?
Here is optimised version of your code.
Note that tempArray is remove (there is no need of it)..
mysqli_close($result) is replaced with unset($result) because $result is not a connection object. How ever unsetting is not required if this is the end of your code because after the end of the script php will unset all variables by it self..
$con=mysqli_connect($port, $username, $password, $database);
$sql = "SELECT name, date FROM `view_tickets`;";
$resultArray = array();
if ($result = mysqli_query($con, $sql)) {
// Loop through each row in the result set
while($row = $result->fetch_object()){
$resultArray[] = $row;
}
}
unset($result);
mysqli_close($con);
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
The mysqli_close needs to connection given to close, but you're give the function your result from your Query!
Change it to
mysqli_close($con);
Then it should be working, if not just comment
I had an issue with the encoding of the character set. Databases can have different encoding, make sure it is utf8

Data transfer from one database to another using php and json

I want to make a data transfer from one database to another using PHP and JSON. The first MySQL connection gets and prints the data (which is working), but the second MySQL connection doesn't insert the data in the 2nd database. I don't know how to execute the INSERT QUERY in order to start filling up the other database(retrieve data from json encode).
This is what I get from the first database:
[{"0":"1","productid":"1","1":"0","parent":"0","2":"","language":"","3":"iPod Shuffle","prodname":"iPod Shuffle","4":"1","prodtype":"1","5":"","prodcode":"","6":"","prodfile":"","7":"
And here is my UPDATED code:
<?php
include 'config/config.php';
//include(dirname(__FILE__) . "/settings.inc.php");
//database 1
$data = array();
$conn = #mysql_connect($GLOBALS['VCS_CFG']["dbServer"],$GLOBALS['VCS_CFG']["dbUser"], $GLOBALS['VCS_CFG']["dbPass"]);
if ($conn){
if (mysql_select_db($GLOBALS['VCS_CFG']["dbDatabase"])) {
$SQL = "SELECT * FROM vc_products";
$q = mysql_query($SQL);
while($row = mysql_fetch_array($q))
{
$json_output[] = $row;
}
echo json_encode($json_output);
$data = json_encode($json_output);
}
mysql_close($conn);
}
// database 2
$con = #mysql_connect($GLOBALS['_DB_SERVER_'],$GLOBALS['_DB_USER_'], $GLOBALS['_DB_PASSWD_']);
if ($con) {
if (mysql_select_db($GLOBALS['_DB_NAME_'])) {
$sql = "INSERT INTO ps_order_detail(product_name) VALUES('".$data[0][8]."')";
$Q = mysql_query($sql);
foreach ($data as $key => $value)
{
$Q -> bind_param(
's', // the types of the data we are about to insert: s = string ( i = int )
$value['prodname']
);
$Q->execute();
}
$Q->close();
}
mysql_close($conn);
}
?>
I don't see you are executing any insert query ¿?
You are just building the string.
A few problems:
You are encoding twice instead of encoding and decoding;
You need to add error handling (PDO and mysqli can throw exceptions, very useful);
You need to get rid of the error supressor operator #;
You should switch to PDO or mysqli and prepared statements to avoid sql injection problems and because the mysql_* functions are deprecated.
Not related, but why would you encode and decode to json in the same script when you really want to use the original array?

custom function for mysqli queries

I'm trying my hand at custom functions in PHP in order to streamline a lot of stuff I'm otherwise doing manually. I'm damn new to custom functions so I'm not sure the limitations. Right now I'm trying to get data with MySQLi using custom functions Here's the code, and then I'll explain the issue:
function connect_db($db = 'db_username') {
iconv_set_encoding("internal_encoding", "UTF-8");
mb_language('uni');
mb_internal_encoding('UTF-8');
# $mysqli = new mysqli('host',$db,'password',$db);
if(mysqli_connect_errno())
{
die('connection error');
}
}
This one seems to be working fine. It's the next function I'm having more trouble with.
edit: Updated thanks to Jeremy1026's response
function do_query($db = 'default_db', $query) {
connect_db();
$result = $mysqli->query($query);
if(!$result){
trigger_error("data selection error");
}
while($row = $result->fetch_assoc()){
$result_array[] = $row;
}
return $result_array;
}
My host forces database names and usernames as the same, so if the db name is 'bob' the username to access it will be 'bob' as well, so that's why $db shows up twice in the connection.
The problem I'm having is that these two functions are in functions.php and being called from another page. I want to be able to pull the results from the query in that other page based on the column name. But I also need to be able to do this with formatting, so then maybe the while() loop has to happen on that page and not in a function? I want this to be as universal as possible, regardless of the page or the data, so that I can use these two functions for all connections and all queries of the three databases I'm running for the site.
God I hope I'm being clear.
Big thanks in advance for any suggestions. I've googled this a bit but it's tough to find anything that's not using obsolescent mysql_ prefixes or anything that's actually returning the data in a way that I can use.
Update: I'm now getting the following error when accessing the page in question:
Fatal error: Call to a member function query() on a non-object in /functions.php`
with the line in question being $result = $mysqli->query($query);. I assume that's because it thinks $query is undefined, but shouldn't it be getting the definition from being called in the page? This is that page's code:
$query = "SELECT * FROM `table`";
$myArray = do_query($db, $query);
echo $myArray['column_name'];
In your 2nd function you aren't returning any data, so it is getting lost. You need to tell it what to return, see below:
function do_query($db = 'default_db', $query) {
connect_db();
$result = $mysqli->query($query);
if(!$result){
trigger_error("data selection error");
}
while($row = $result->fetch_assoc()){
$result_array[] = $row;
}
return $result_array;
}
Then, when using the function you'll do something like:
$myArray = do_query($db, 'select column from table');
$myArray would then be populated with the results of your query.
This is a half-answer. The following single function works in place of the two.
function query_db($database, $new_query) {
$sqli = new mysqli('host', $database, 'password', $database);
$sqli->set_charset("utf8");
global $result;
if($result = $sqli->query($new_query)){
return $result;
}
}
By adding global $result I was able to access the results from the query, run from another page as
query_db("username","SELECT * FROM `column`");
while($row = $result->fetch_assoc()){
print_r($row);
}
It's more streamlined than I have without functions, but it's still not idea. If I have the connection to the database in another function, it doesn't work. If I try to put the while loop in the combined function, it doesn't work. Better than nothing, I guess.

Categories