Getting data from database showing it as json response - php

In mysql table I have set of record. I want to fetch them wanna showlike below json response.
"results":[
{
"timestamp":"2014-03-04 17:26:14",
"id":"440736785698521089",
"category":"sports",
"username":"chetan_bhagat",
"displayname":"Chetan Bhagat"
}
I am getting above values i.e. timestamp,id,category,username from database. How can I show the result in form of json response like above?
UPDATE:
I fetch data in this way:
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT url,img_url,sentiment,title,category from frrole_cateogry_article where category='".$category."' AND today <= '".$today."' AND title != '' AND img_url != '' order by url desc limit 3 ");
while ($row = #mysqli_fetch_array($result))
{
$url = $row['url'];
$img_url = $row['img_url'];
$screen_name = $row['screen_name'];
}

try this...
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT url,img_url,sentiment,title,category from frrole_cateogry_article where category='".$category."' AND today <= '".$today."' AND title != '' AND img_url != '' order by url desc limit 3 ");
while ($row = #mysqli_fetch_array($result))
{
json_encode($row);
}

Fetch your results in the traditional way:
$data['results'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
Then convert it all to JSON. Bam!
$results = json_encode($data);
This is far easier than trying to format JSON in your SQL query.
See for more details:
http://php.net/manual/en/pdostatement.fetchall.php
http://php.net/manual/en/function.json-encode.php
Since you're use mysqli instead of PDO, and using it in a procedural fashion, you'd fetch rows a different way:
while ($data['results'][] = mysql_fetch_assoc($result));
Then you can json_encode() as I showed above.

Related

Parsing MySQL to JSON array, with data manipulation in PHP

I'm tring to parse a MySQL request to a JSON file, with this PHP function,
<?php
//Define possible Argument request
$format = $_GET['format'];
if($format=='json') {
header("Content-type: text/json");
}
//Define database credential
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
try {
//Open connection to mysql_db from defined Database credentials
$connection = mysqli_connect($servername, $username, $password, $dbname) or die ("Error " . mysqli_error($connection));
//Fetch table rows from mysql db
$sql = "SELECT TS, time1, time2, time3 FROM time ORDER BY TS";
$result = mysqli_query($connection, $sql) or die ("Error in Selecting " . mysqli_error($connection));
//Create an array
$series0 = array();
$series0['name'] = 'TS';
$series1 = array();
$series1['name'] = 'time1';
$series2 = array();
$series2['name'] = 'time2';
$series3 = array();
$series3['name'] = 'time3';
while($r = mysqli_fetch_array($result))
{
$series0['data'][] = $r['TS'];
$series1['data'][] = $r['time1'];
$series2['data'][] = $r['time2'];
$series3['data'][] = $r['timez3'];
}
$result = array();
array_push($result,$series0);
array_push($result,$series1);
array_push($result,$series2);
array_push($result,$series3);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($connection);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Who gives me this JSON output:
[{
"name": "TS",
"data": ["00:08:31.227","00:09:02.434","00:09:38.573"]
},{
"name":"time1",
"data":["00:05:11.220","00:05:05.420","00:03:32.540"]
},{
"name":"time2",
"data":["00:04:11.820","00:08:05.660","00:01:24.330"]
},{
"name":"time3",
"data":["00:02:11.990","00:09:05.570","00:15:25.200"]
}]
Now the problem is that I have to convert the times from "HH:MM:SS.fff", to seconds (SS.fff), but trying to apply my conversion function I came to an error becouse I cant applay my formulas to an array, is there a way to intercept the data and manipulate it before they goes inside the array?
And a second minor problem, becouse the final array will get 100+ dataseries, is there a way to don't assign manually the name to the series, but give them the same name as the column of MySQL table from where they came from??
Thank for all the suggestions,
Best regards.
You can use mysql TIME_TO_SEC function.
mysql> SELECT TIME_TO_SEC('22:23:00');
-> 80580
mysql> SELECT TIME_TO_SEC('00:39:38');
-> 2378
so change
$sql = "SELECT TS, time1, time2, time3 FROM time ORDER BY TS";
to
$sql = "SELECT TS, TIME_TO_SEC(time1), TIME_TO_SEC(time2), TIME_TO_SEC(time3) FROM time ORDER BY TS";

Select Query with OOP PHP ORM

for a customer I have to make little adjustments to an application what is build on OOP PHP. I have no experience at all with OOP, and normally I only use PHP for small functions. I would like to select data from my database, to use it in a build function and variable. My code under will explain
public function readTwitter(){
$accounts = array();
$hastags = array('coldplay');
\ORM::for_table('feed_items')->where('portal_reference', 'tw')->delete_many();
foreach($accounts as $account) {
$feed = $this->twitter->getFeedByAccount($account);
foreach($feed as $post){
$this->twitter->savePost($post);
}
}
foreach($hastags as $hashtag) {
$feed = $this->twitter->getFeedByHashtag($hashtag);
foreach($feed->statuses as $post){
$this->twitter->savePost($post);
}
}
}
So in this version of the application the foreach loop will check if the var is filled in, what is now done with an array, and use it in the function readTwitter() What I like to have is a select query which selects one specific row out of my database to use it instead of an array, written in my application as OOP as follow (written in procedural php):
$dbCon = mysqli_connect("localhost", "root", "root", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `questions` WHERE `location` = 'wall' ORDER BY `questions`.`id` DESC ";
$query = mysqli_query($dbCon, $sql);
if ($query) {
$row = mysqli_fetch_row($query);
$hashtags = $row[2]; //instead of array('coldplay');
}
public function readTwitter(){
$dbCon = mysqli_connect("localhost", "root", "root", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `vragen` WHERE `location` = 'wall' ORDER BY `vragen`.`id` DESC ";
$query = mysqli_query($dbCon, $sql);
if ($query) {
$row = mysqli_fetch_row($query);
$accounts = $row[3];
$hashtags = $row[2];
\ORM::for_table('feed_items')->where('portal_reference', 'tw')->delete_many();
$feed = $this->twitter->getFeedByAccount($accounts);
foreach($feed as $post){
$this->twitter->savePost($post);
}
$feed = $this->twitter->getFeedByHashtag($hashtags);
foreach($feed->statuses as $post){
$this->twitter->savePost($post);
}
}
}
I have tried to combine the code and it works like I want, but I dont think this is the right way for OOP, right?

Return PHP MySQL select as json

So I have a SQL database with a number of objects in that contain name price and images, I would like to know how I can select them using php and output the result into json
<?php
$db = mysqli_connect ('localhost', 'root', '', 'car_rental') or die ("SQL is Off");
$car = (isset($_GET['car']) ? $_GET['car'] : null);
mysqli_select_db($db,"car_rental");
$SQL = "SELECT * FROM `products` WHERE name LIKE \'%$car%\'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['sku'] . "<BR>";
print $db_field['name'] . "<BR>";
print $db_field['img'] . "<BR>";
print $db_field['price'] . "<BR>";
}
?>
This is my current code car variable will change dependent on car selected
thanks
For getting all values in json format, you need to use like that:
<?
$newArr = array();
while ( $db_field = mysql_fetch_assoc($result) ) {
$newArr[] = $db_field;
}
echo json_encode($newArr); // get all products in json format.
?>
UPDATE 1:
You are mixing mysqli extension with mysql. Change mysql into mysqli
UPDATE 2:
Why are you connecting database twice in code?
Modified Code:
<?php
$link = mysqli_connect("localhost", "root", "", "car_rental");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$car = (isset($_GET['car']) ? $_GET['car'] : null);
$query = "SELECT * FROM `products` WHERE name LIKE '%$car%'";
if ($result = mysqli_query($link, $query)) {
$newArr = array();
/* fetch associative array */
while ($db_field = mysqli_fetch_assoc($result)) {
$newArr[] = $db_field;
}
echo json_encode($newArr); // get all products in json format.
}
?>
Side Note:
Also on PHP error reporting in development phase for saving your time.

php display mysql table from user input? in the part of Json Restful web services?

I am new to PHP.
I followed this to Display JSON data from Mysql Tables
Here I am getting one table as output at a time..
So,in this I want to display tables from user input.
like
www.google.com/myjson.php?/tablename
www.google.com/myjson.php?=tablename
Here is the code
<?php
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("test_json",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from employee", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id_employee'] = $row['id_employee'];
$row_array['emp_name'] = $row['emp_name'];
$row_array['designation'] = $row['designation'];
$row_array['date_joined'] = $row['date_joined'];
$row_array['salary'] = $row['salary'];
$row_array['id_dept'] = $row['id_dept'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
Here its for the part of Table name of employee
so this should be like
www.google.com/myjson.php?/employee
please suggest me of this kind,because I have n number of tables to Display and I want to use them in the Android/iphone.
<?php
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("test_json",$db);
$tableNm = isset($_GET['tablename']) ? trim($_GET['tablename']) : '';
if($tableNm){
//Replace * in the query with the column names.
$result = mysql_query("select * from $tableNm", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($row as $key=>$val){
$row_array[$key] = $val;
}
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
}
//Close the database connection
mysql_close($db);
Assumes you have input url's in the below formats.
$url ="www.google.com/myjson.php?/tablename";
//or
$url ="www.google.com/myjson.php?=tablename";
You can parse it using parse_url and str_replace to retrieve the table name.
Then assign tablename into query and make it run.
$url = parse_url($url);
if ($url['query'] <> '') {
$table = str_replace(array("/","="),'',$url['query']);
}
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("test_json",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from $table", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($row as $key=>$val){
$row_array[$key] = $val;
}
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
mysql_close($db);
P.S. Usage of mysql_* functions is not recommended.
Instead you can use mysqli* or pdo* functions.

getting data from database as a json response

Here I am trying to get some data from database and want to display it as a json response so that user can fetch each field.
Here is how user can perform query
http://localhost/safari/index.php?getbranch=true
this should give branch details from tables.
Here is PHP code to do it
<?php
if(isset($_GET['getbranch']))
{
$getbranch = $_GET['getbranch'];
if($getbranch == 'true')
{
getbranch($getbranch);
}
}
function getbranch($getbranch)
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'safari');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT division, branch,branchofficename,branchofficecode,status from tbl_branchoffice");
while ($row = #mysqli_fetch_array($result))
{
$result1 = json_encode($row);
}
echo $result1;
}
What's wrong wit this?
JSON response:
[{"0":"3","sno":"3","1":"2","division":"2","2":"2","branch":"2","3":"SAFFARI TRAVELS","branchofficename":"SAFFARI TRAVELS","4":"gfgbhghfhf","branchofficecode":"gfgbhghfhf","5":"active","status":"active"},
{"0":"4","sno":"4","1":"2","division":"2","2":"chennai","branch":"chennai","3":"chennai","branchofficename":"chennai","4":"br01","branchofficecode":"br01","5":"active","status":"active"},{"0":"5","sno":"5","1":"3","division":"3","2":"delhi","branch":"delhi","3":"delhi","branchofficename":"delhi","4":"br02","branchofficecode":"br02","5":"notactive","status":"notactive"},{"0":"6","sno":"6","1":"2","division":"2","2":"bangalore","branch":"bangalore","3":"bangalore","branchofficename":"bangalore","4":"br03","branchofficecode":"br03","5":"active","status":"active"},{"0":"7","sno":"7","1":"3","division":"3","2":"pune","branch":"pune","3":"pune","branchofficename":"pune","4":"br04","branchofficecode":"br04","5":"notactive","status":"notactive"}]
Change your while loop
$result1 = array();
while ($row = #mysqli_fetch_array($result))
{
array_push($result1 , $row);
}
by doing so, you have collected all result in $result1
now you can encode it
echo $result1 = json_encode( $result1);
I will prefer to use array, ignor json_encode line code,
foreach($result1 as $resultset){
//resultset contains one single row of table
foreach($resultset as $column => $columnValue){
//assuming your table column name as 'city'
if($column == 'city' && $columnValue == 'pune' ){
//displaying array of table which satisfies the condition
var_dump($resultset );
}
}
}
$result1 = array();
if(isset($_GET['getbranch']))
{
$getbranch = $_GET['getbranch'];
if($getbranch == 'true')
{
getbranch($getbranch);
}
}
function getbranch($getbranch)
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'safari');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT division,
branch,branchofficename,branchofficecode,status from tbl_branchoffice");
while ($row = #mysqli_fetch_array($result))
{
$result1[] = $row;
}
echo json_encode($result1);
}
First collect each row from the result into the array result1 and then finally output the json_encode of $result1 array

Categories