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.
Related
through a cURL connection, I can pick up data, from Json files, placed on a remote server. In particular, the codes of some products, which thanks to a foreach
foreach($data['results'] as $key=>$val){
$codici_hotel = $val['hotel_code'];
echo $codici_hotel.",";
}
I can see on video:
1074d0,19f726,1072ba,107104,183444,112438,15d8ab,1b326e,19d885,189b95,1071bf,107155,193e61,10aab2,138752,18dd7d,19d7f9,117b0d,1071b8,1398c4,107039,110851,107124,110669
Now I need to use that string to run a select on a local database, such as:
$sql = "SELECT * FROM hotels WHERE code = ('$codici_hotel')";
What is the correct sql string?
Thanks for your help
CODE UPDATE USED
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT name FROM hotels WHERE code IN ('$codici_hotel')";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$nome_hotel = $row2["name"] ;
}
} else {
echo "0 results";
}
$conn2->close();
echo $nome_hotel;
You have to convert your all codes in string enclosed with '. Then use IN clause of mysql. change your code as below
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$sql = "SELECT * FROM hotels WHERE code IN ($codici_hotel)";
I'm currently stuck with some PHP code. I want to access a table in my database and retrieve the data in a JSON format. Therefore, I tried the following code :
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysql_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
However, it's getting me an empty page. It worked once but only with a special number of row in the table, so not very efficient as you might guess.
Does anybody have an idea why i'm getting those weird results?
EDIT 1 :
I Just tried to add this to my code :
echo json_encode($resultArray);
echo json_last_error();
And it's returning me 5. It seems to be an error from the data encoding in my table. Therefore I added that code :
$tempArray = array_map('utf8_encode', $row)
array_push($resultArray, $tempArray);
And I got the following output : [null,null,null]0 (The zero comes from the echo json_last_error();)
So here I am, can anybody help me with this ?
I would start by changing if ($result = mysql_query($con, $sql)) to if ($result = mysqli_query($con, $sql)) because they are different database extensions
Another thing would be to change while($row = $result->fetch_object()) to while ($row = mysqli_fetch_object($result)) { (Procedural style vs. Object oriented style)
If you still see blank screen, try adding error_reporting(E_ALL); at the top of your script, and you'll be able to know exactly where the bug is
<?php
$con = mysqli_connect("......","username","pwd","DBName")
or die("Failed to connect to MySQL: " . mysqli_connect_error());
$sql = "SELECT * FROM users";
$query = mysqli_query($con, $sql) or die ("Failed to execute query")
if ($result = $query)
{
$resultArray = array();
while($row = $result->fetch_object())
{
array_push($resultArray, $row);
}
$result->close()
echo json_encode($resultArray);
}
mysqli_close($con);
?>
This code works for me, try it out:
<?php
$con = mysqli_connect("......","username","pwd","DBName");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM users";
if ($result = mysqli_query($con, $sql))
{
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>
EDIT 1:
As a test replace this code:
while($row = $result->fetch_object())
{
$resultArray[] = $row;
}
echo json_encode($resultArray);
with this code:
while($row = $result->fetch_assoc())
{
print_r($row);
}
What output do you get?
I finally found a solution ! That was indeed an encoding problem, the json_encode() function accepts only strings encoded in utf8. I changed the interclassement of my table to utf8_general_ci and I modified my code as follows :
<?php
//Create Database connection
$db = mysql_connect(".....","username","pwd");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("DBName",$db);
//Replace * in the query with the column names.
$result = mysql_query("SELECT * FROM users", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['name'] = utf8_encode($row['name']);
$row_array['lastName'] = utf8_encode($row['lastName']);
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
And I got the expected output.
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.
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
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.