How can I retrieve data from a database using PHP? - php

I have a problem with retrieving data from a database using PHP statements. At the moment the output looks like:
[{"Bez":"Cino"},{"Bez":"Extra"},{"Bez":"Panini"},{"Bez":"And so on"}]
"Bez" is the label of the column and we don't want it to be displayed. We just want to display the cell's contents so it should look like:
[Cino,Extra,Panini,And so on]
The php is:
<?php
$username = "root";
$database = "kaffeehaus";
mysql_connect('localhost', $username);
#mysql_select_db($database) or die("Geht nicht!");
$query = "SELECT Bez FROM kategorie";
$result = mysql_query($query) or die(mysql_error("error"));
$num = mysql_numrows($result);
mysql_close();
$rows = array();
while ($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
?>

Replace
$rows[] = $r;
With
$rows[] = $r['Bez'];
...though to be honest, I'd replace the whole "fetch" part with:
while($r = mysql_fetch_row($result))
$rows[] = $r[0];
That's because mysql_fetch_row is generally faster than mysql_fetch_assoc.

Replace
while ($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
with this:
while ($r = mysql_fetch_array ($result, MYSQL_ASSOC))
{
$rows[] = $r['Bez'];
}

Use mysql_fetch_row() instead (or mysql_fetch_array($result, MYSQL_NUM);). It fetches a numerical array so the column names are not shown.
Then, your output will look something like this:
[{"0":"Cino"},{"1":"Extra"},{"2":"Panini"},{"3":"And so on"}]

Remove the json_encode part:
echo json_encode($rows); ?>
And use bez as row key:
echo ($rows['bez']); ?>

And how does it work if there are more than one cell?
Our php looks like
<?php
$username = "root";
$database = "kaffeehaus";
mysql_connect('localhost', $username);
#mysql_select_db($database) or die("Geht nicht!");
$ID_Kategorie = $_GET["Kategorie"];
$query = "SELECT * FROM artikel WHERE ID_Kategorie=$ID_Kategorie";
$result=mysql_query($query) or die("error");
$num = mysql_numrows($result);
mysql_close();
$rows = array();
while ($r = mysql_fetch_assoc($result))
{
$rows = $r;
}
echo json_encode($rows); ?>
And the output like:
[{"ID_Artikel": "12","ID_Kategorie":"19","Bez":"blabla","Beschreibung":"blabla"}]
But it schould look like:
[{"12","19","blabla","blabla"}]

Related

Store a MySQL column to an array then print in PHP

I am trying to store a column named imgPath from a table named images in my database to an array in PHP. Then I want to print it out so I can see that it worked. You can see what the table looks like below:
Below is the code I am using to not succeed lol:
$db = mysqli_connect('localhost', 'userdatabase', 'PASSData', 'sftdatabase');
$result = mysqli_query($db,"SELECT imgPath FROM images");
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row['imgPath'];
}
print_r($result_array);
I have tried using print_r($result); right before creating the array and I get:
How can I get the path? (example: img/art/10/download.jpg)
Simple mistake,
Change,
while($row = mysql_fetch_assoc($result))
To,
while($row = mysqli_fetch_assoc($result))
Notice the i for mysqli is missing in the first.
$db = mysqli_connect('localhost', 'userdatabase', 'PASSData', 'sftdatabase');
$result = mysqli_query($db,"SELECT imgPath FROM images");
$result_array = [];
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['imgPath'];
}
print_r($result_array);

Printing multiple table queries using json_encode in php

I need to print multiple database queries using json_encode(). I have this code below that outputs database records using json_encode. This works fine.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('SELECT username,firstname,lastname FROM user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
echo json_encode($data);
?>
I need to add another database query so that I can print them together using the same json_encode. Here is the database query that I want to add so that I can print them together using json_encode:
<?php
include('db.php');
$result = $db->prepare('SELECT price AS price1,goods AS product FROM provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
echo json_encode($data_pro);
?>
How can I accomplish this?
I think this might hit what you're looking for.
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('select username,firstname,lastname from user');
$result->execute(array());
$data = array();
while ($row = $result->fetch()) {
$data[] = $row;
}
$result = $db->prepare('select price as price1,goods as product from provision_table');
$result->execute(array());
$data_pro = array();
while ($row = $result->fetch()) {
$data_pro[] = $row;
}
// Combine both arrays in a new variable
$all_data['user'] = $data;
$all_data['pro'] = $data_pro;
echo json_encode($all_data);

Convert mysql select results to json (array of arrays)

I need to encode a table content to JSON in order to insert it into a file.
The output has to be as following :
{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}
Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.
The only thing I could manage for the moment is this :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
$index++;
}
echo json_encode($return_arr);
And here is the output I get :
[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]
Thanks a lot !!!
UPDATED
Working code :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}
echo json_encode($return_arr);
}
You were close. I noticed you want final output to be an object not an array, because the outer brackets are {} not []. So you need a different object type, and you need to use each row's name as the key for storing that row.
$return_obj = new stdClass();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
$return_obj->$name = [$row]; // for PHP < 5.4 use array($row)
}
echo json_encode($return_obj);
This loop is enough, to create the desired JSON:
$return_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
}
echo json_encode($return_arr);
I was working on it a lot of time and Create mash/mysql-json-serializer package.
https://github.com/AndreyMashukov/mysql-json-serializer
You can select Json_array of json_objects and etc. It support ManyToMany, oneToMany, manyToOne relations
SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res
<?php
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>

json formatting_adding a tag to it

here is the PHP file that im using to generate the JSON with:
<?
$databasehost = "wbw.com";
$databasename = "wtest";
$databaseusername ="w";
$databasepassword = "123";
$query = "SELECT * FROM `and` LIMIT 0 , 30";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query.'\n';
echo mysql_error();
}
else
{
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
?>
The problem with it is that it generates a result like this:
[{"Reg_user_name":"nn","Username":"ns","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1//306ad73427e262r9","Device
Name":"office"},{"Reg_user_name":"nn","Username":"nn","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1/e/306ad73427e262e7","Device
Name":"LAB lighting"}]
BUT in order to use the JSONobject and get the elements in it I need to give JSON like follows:
["Information":{"Reg_user_name":"nn","Username":"ns","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1//306ad73427e262r9","Device
Name":"office"},{"Reg_user_name":"nn","Username":"nn","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1/e/306ad73427e262e7","Device
Name":"LAB lighting"}]
I want to know that what I have to add in the PHP file to get that data with the added "information:" tag to it automatically using the above PHP file.
If you only want one index, you can change this
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
into this
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$json = array(
'information' => $rows,
);
print json_encode($json);
just add string index to the array the json encoder will automatically convert it
check this
while($r = mysql_fetch_assoc($sth))
{
$rows['information'][] = $r;
}
echo json_encode($rows);

Converting a mysql query to a JSON object using php?

I am trying to convert a mySQL query into a JSON object. This works:
<?php
// load in mysql server configuration (connection string, user/pw, etc)
include 'mysqlConfig.php';
$year = $_GET['year'];
// connect to the database
#mysql_select_db($dsn) or die( "Unable to select database");
// outputs the db as lines of text.
$result = mysql_query("SELECT COUNTY, COUNT(TYPE) AS 'type' from data WHERE DATE between '2000-01-01' and '2000-12-31' GROUP BY COUNTY");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysql_close();
?>
But I get this output:
[{"COUNTY":"Carlow","type":"121"},{"COUNTY":"Cavan","type":"130"},{"COUNTY":"Clare","type":"112"},{"COUNTY":"Cork","type":"833"},{"COUNTY":"Donegal","type":"264"},{"COUNTY":"Dublin","type":"2457"},{"COUNTY":"Galway","type":"287"},{"COUNTY":"Kerry","type":"227"},{"COUNTY":"Kildare","type":"300"},{"COUNTY":"Kilkenny","type":"139"},{"COUNTY":"Laois","type":"123"},{"COUNTY":"Leitrim","type":"39"},{"COUNTY":"Limerick","type":"370"},{"COUNTY":"Longford","type":"85"},{"COUNTY":"Louth","type":"257"},{"COUNTY":"Mayo","type":"231"},{"COUNTY":"Meath","type":"268"},{"COUNTY":"Monaghan","type":"136"},{"COUNTY":"Offaly","type":"97"},{"COUNTY":"Roscommon","type":"115"},{"COUNTY":"Sligo","type":"113"},{"COUNTY":"Tipperary","type":"249"},{"COUNTY":"Waterford","type":"205"},{"COUNTY":"Westmeath","type":"118"},{"COUNTY":"Wexford","type":"246"},{"COUNTY":"Wicklow","type":"235"}]
whereas this is the format I am looking for:
{"Carlow":3,"Cavan":4,"Clare":5,"Cork":3,"Donegal":4,"Dublin":5,"Galway":4,"Kerry":5,"Kildare":5,"Kilkenny":12,"Laois":4,"Leitrim":4,"Limerick":4,"Longford":4,"Louth":4,"Mayo":5,"Meath":3,"Monaghan":5,"Offaly":4,"Roscommon":3,"Sligo":3,"Tipperary":4,"Waterford":2,"Westmeath":2,"Wexford":4,"Wicklow":2}
Any ideas?
It should be:
while($r = mysql_fetch_assoc($result)) {
$rows[$r['COUNTRY']] = $r['type'];
}
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
Should be
while($r = mysql_fetch_assoc($result)) {
$rows[] = array($r['COUNTY'], $r['type']);
}

Categories