show only one id from json php - php

my question is: how i can show only id 2 from this code ? (the code show all id)
this is a file.php json encode
<?php
header('Content-type: application/json');
$server = "";
$username = "";
$password = "";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM flo";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
relative json result
([
{
"id":"1",
"Marca":"puma",
},
{
"id":"2",
"Marca":"fila",
}
]);
thx a lot

In order to display id=2 (or any other) from JSON, it's necessary to search the id, like this (will display "fila") :
<?php
$data = '[ { "id":"1",
"Marca":"puma"
},
{ "id":"2",
"Marca":"fila"
},
{ "id":"3",
"Marca":"nike"
}
]';
$json = json_decode( $data );
foreach ( $json as $record ) // VISIT EACH RECORD.
if ( $record->id == "2" )
echo $record->Marca . "<br/><br/>";
?>
Notice how each field in the data becomes a property in JSON ("id" becomes $record->id).

Related

Can't Get MySQL table entry to PHP variable

I really hope I'm not just being stupid. I'm trying to retrieve two values from a existing database, based on a user's ID. I've been trying a couple of different things, so I've got some commented code in case I was close!
I'm using a select statement to get the values, and then trying to pass them to PHP variables. I'm getting the values from the DB, just not setting them as PHP variables.
<?php
//declare database variables
header('Content-type: text/html; charset=utf-8');
$username = "ishuttle";
$password = "";
$hostname = "localhost";
$dbname = "ishuttle_taxi-location";
$conn = mysql_connect($hostname, $username, $password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
//search database for driver location
mysql_select_db('ishuttle_taxi-location');
$sql = "SELECT _id, Latitude, Longitude
FROM driver_location
WHERE _id = 2";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo "Lat :{$row['Latitude']} <br> ".
"Long: {$row['Longitude']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
$Lat = $retval[1];
$Long = $retval[2];
echo "$Lat";
?>
Cheers in advance :)
Assign the variables inside the while loop. Change
while($row = mysql_fetch_assoc($retval))
{
echo "Lat :{$row['Latitude']} <br> ".
"Long: {$row['Longitude']} <br> ".
"--------------------------------<br>";
}
to
while($row = mysql_fetch_assoc($retval))
{
$Lat = $row['Latitude'];
$Long = $row['Longitude'];
echo "Lat :{$row['Latitude']} <br> ".
"Long: {$row['Longitude']} <br> ".
"--------------------------------<br>";
}
This is wrong:
$Lat = $retval[1];
^^^^^^
$retval is your result handle from the mysql query. It's NOT an array of results.

Generating single JSON file for two tables

I am trying to create a single JSON file displaying data from two different tables. I can manage to fetch them, however I don't understand how to concatenate the two arrays. I am new to JSON. Any suggestions/tutorials would be very helpful. Thanks in advance.
Here the expected JSON:
{
"array1":[
{"days":"1","id":"1","image":"image1.jpg, image2.jpg, image3.jpg, image4.jpg"},{"days":"2","id":"1","image":"elephanta.jpg,image2.jpg,image1.jpg,imagica.jpg"},
{"days":"3","id":"1","image":"image3"},{"days":"4","id":"2","image":"image4"}
],
"array2":[
{"id":"1","image_1":"image1.jpg"},
{"id":"2","image_1":"image2.jpg"},
{"id":"3","image_1":"image3.jpg"}
]
}
but the JSON that I get is this:
{
"array1":[
{"days":"1","id":"1","image":"image1.jpg, image2.jpg, image3.jpg, image4.jpg"},{"days":"2","id":"1","image":"elephanta.jpg,image2.jpg,image1.jpg,imagica.jpg"},
{"days":"3","id":"1","image":"image3"},{"days":"4","id":"2","image":"image4"}
]},
{"array2":[
{"id":"1","image_1":"image1.jpg"},
{"id":"2","image_1":"image2.jpg"},{"id":"3","image_1":"image3.jpg"
}
]}
PHP code:
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from image_data";
$sql1 = "select * from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageArray = array();
$imageArray1 = array();
$imageArray["array1"] = array();
$imageArray1["array2"] = array();
while($row =mysqli_fetch_array($result))
{
$tmp = array();
$tmp["days"] = $row["id"];
$tmp["id"] = $row["place_id"];
$tmp["image"] = $row["image"];
array_push($imageArray["array1"], $tmp);
// $imageArray[] = $row;
}
while($row =mysqli_fetch_array($result1))
{
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["image_1"] = $row["image"];
array_push($imageArray1["array2"], $tmp);
// $imageArray[] = $row;
}
echo json_encode($imageArray);
echo ",";
echo json_encode($imageArray1);
//close the db connection
mysqli_close($connection);
?>
If you want the 2 sub arrays to belong to the same array then use only one array and address the 2 sub arrays like this when loading them
$imageArray["array1"][] = $tmp;
and
$imageArray["array2"][] = $tmp;
Amended code
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from image_data";
$sql1 = "select * from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageArray = array(); // <- removed other arrays
while($row =mysqli_fetch_array($result))
{
$tmp = array();
$tmp["days"] = $row["id"];
$tmp["id"] = $row["place_id"];
$tmp["image"] = $row["image"];
$imageArray["array1"][] = $tmp; // <- address array like this
}
while($row =mysqli_fetch_array($result1))
{
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["image_1"] = $row["image"];
$imageArray["array2"][] = $tmp; // <- address array like this
}
echo json_encode($imageArray); // <- only one json_encode
//close the db connection
mysqli_close($connection);
?>
I would have done it this way using stdObject and selecting the specific data from the tables, and using mysqli_fetch_obect() so there is a lot less you have to do woman-draulically
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
// only select what you want
$sql = "select id,place_id,image from image_data";
$sql1 = "select id,image from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageObject = new stdObject();
while($row =mysqli_fetch_object($result))
{
$imageObject->array1[] = $row;
}
while($row =mysqli_fetch_object($result1))
{
$imageObject->array2[] = $row;
}
echo json_encode($imageObject);
?>

Query MySQL using Joomla syntax

The following query is returning the result I expected:
$link=mysqli_connect('localhost','user','pass');
if(!$link){
echo "No connection!";
exit();
}
if (!mysqli_set_charset($link, 'utf8'))
{
echo 'Unable to set database connection encoding.';
exit();
}
if(!mysqli_select_db($link, 'database')){
echo "No database";
exit();
};
$res = $link->query("SELECT rules FROM xmb9d_viewlevels WHERE id=10");
while ($row = $res->fetch_array()) {
echo " cenas = " . $row['rules'] . "\n";
};
But, since I'm using Joomla 2.5.16 and I'm trying to keep its syntax, I tried:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$res = $db->query("SELECT rules FROM #__viewlevels WHERE id=10");
while ($row = $res->fetch_assoc()) {
echo " cenas = " . $row['rules'] . "\n";
};
This isn't working. It is only displaying the text " cenas =".
What is wrong with this code?
Try the following:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('rules'))
->from($db->quoteName('#__viewlevels'))
->where($db->quoteName('id')." = ".$db->quote('10'));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result) {
echo " cenas = " . $result->rules;
}

How do I output certain index values from a foreach array?

This is the structure in the database:
items |itemLink
----------------------
Kill Bill|Kill Bill link
Preman |Preman link
This is the code:
$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$items = 'SELECT items FROM menus';
$itemLink = 'SELECT itemLink FROM menus';
$itemQuery = $db->query($items);
$linkQuery = $db->query($itemLink);
$fetchItem = $itemQuery->fetchAll(PDO::FETCH_ASSOC);
$fetchLink = $linkQuery->fetchAll(PDO::FETCH_ASSOC);
$merged = array_merge($fetchItem,$fetchLink);
foreach($merged as $entry) {
foreach( $entry as $key => $value ) {
}
}
From the above code, how do I output only the items' datas?
Using the example above you could then do something like this to answer you question
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["FirstName"] . " " . $row["LastName"] . "<br>";
}
mysql_close($conn);
?>
I would use something like this, not two arrays for something that could be one query. I have shown three methods, using var_dump or print_r will show how each works.
$conn = mysql_connect($hostname, $username, $password);
if (!$conn) {
die('Could not connect to MySQL: ' . mysqli_connect_error());
}
$db_selected = mysql_select_db('sample', $conn);
if (!$db_selected) {
die("Can\t use db : ' . mysql_error()");
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
$result = mysql_query('Select * from names ');
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
print_r($row);
}
mysql_close($conn);

How can I create a json object in php

I am working in android and php.
I want to return a json object to android program from php program.
If these is a entry in a database then it is working properly. But when there is no record in database then it goes wrong.
I would welcome suggestions
I want to make json object like this ([{"id":"5"}])
This is my php program:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
//what should i right here to make jsonobject like this:- ([{"id":"5"}])
echo myjsono;
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
?>
How about something like this: (replace with your own variables)
if (empty($row)){
$arr = array('success' => 'false');
} else {
$arr = array('success' => 'true');
}
echo json_encode($arr);
If you want your android app to receive an object with a special id in the case of a not found condition I would return this:
{"id":"0"}
Then in your android app check if the id == 0 and that will tell you no records were found.
This is very correct solution for my question:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
// {"messages":{"message":[{"id": "17","user": "Ryan Smith","text": "This is an example of JSON","time": "04:41"}]};}
**echo '('.'['.json_encode(array('id' => 0)).']'.')';** //**note this**
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
//mysql_close($con);
//echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>

Categories