I have this php script that gives me a json response.
<?php
include("init.php");
$string="";
$newString="";
$get_posts = "select * from books_table";
$run_posts = mysqli_query($con,$get_posts);
$posts_array = array();
while ($posts_row = mysqli_fetch_array($run_posts)){
$row_array['title'] = $posts_row['title'];
$row_array['author'] = $posts_row['author'];
$row_array['bookUrl'] = $posts_row['bookUrl'];
$row_array['imageUrl'] = $posts_row['imageUrl'];
$row_array['displayDate'] = $posts_row['displayDate'];
$row_array['numberOfPages'] = $posts_row['numberOfPages'];
array_push($posts_array,$row_array);
}
$string = json_encode($posts_array,JSON_UNESCAPED_UNICODE);
echo $string;?>
And the json I get
[{"title":"Clean Code","author":"Robert Martin","bookUrl":"http:\/\/amzn.to\/1DJybxH","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/clean_code.jpg\"","displayDate":"August 11, 2008","numberOfPages":"464"},{"title":"Effective Java","author":"Joshua Bloch","bookUrl":"http:\/\/amzn.to\/1Ku8Xel","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/effective_java.jpg","displayDate":"May 28, 2008","numberOfPages":"346"},{"title":"Working Effectively with Legacy Code","author":"Michael Feathers","bookUrl":"http:\/\/amzn.to\/1Jqe1PA","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/legacy_code.jpg","displayDate":"October 2, 2004","numberOfPages":"456"},{"title":"Refactoring: Improving the Design of Existing Code","author":"Martin Fowler","bookUrl":"http:\/\/amzn.to\/1Lx4cjR","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/refactoring.jpg","displayDate":"July 8, 1999","numberOfPages":"464"}]
I want to perform a query that will return the object whose title contains the word clean.
So I am using this url
[http://www.theo-android.co.uk/books/sample_data.php/q=clean][1]
Hoewever,I get the same json response as before. The object or objects are not filtered out. Why is this happening?
Thanks,
Theo.
If I understand correctly, you want sample_data.php to be able to return filtered data?
first of all, you'll need to update sample_data.php to handle the q param (I would use it as GET since it's simpler: http://www.theo-android.co.uk/books/sample_data.php?q=clean
<?php
include("init.php");
$string="";
$newString="";
$query = mysqli_real_escape_string($con,$_GET['q']); // get and escape the q param
$get_posts = "select * from books_table";
if($query != '') $get_posts .= " WHERE title LIKE '%{$query}%'"; // if $query is not empty string - query using a wild card
$run_posts = mysqli_query($con,$get_posts);
$posts_array = array();
while ($posts_row = mysqli_fetch_array($run_posts)){
$row_array['title'] = $posts_row['title'];
$row_array['author'] = $posts_row['author'];
$row_array['bookUrl'] = $posts_row['bookUrl'];
$row_array['imageUrl'] = $posts_row['imageUrl'];
$row_array['displayDate'] = $posts_row['displayDate'];
$row_array['numberOfPages'] = $posts_row['numberOfPages'];
array_push($posts_array,$row_array);
}
$string = json_encode($posts_array,JSON_UNESCAPED_UNICODE);
echo $string;?>
this way $posts_row will only have the relevant books
--ADDITION----
show book json by id
http://www.theo-android.co.uk/books/sample_data.php?id=1
<?php
include("init.php");
$string="";
$newString="";
$query = mysqli_real_escape_string($con,$_GET['q']); // get and escape the q param
$id = (int)$_GET['id']; // get and cast to int the id var from GET
$where_cond = array();
$get_posts = "select * from books_table";
if($query != '') $where_cond[] = " title LIKE '%{$query}%'"; // if $query is not empty string - query using a wild card
if($id > 0) $where_cond[] = " id = {$id}"; // if $id is a number
if(!empty($where_cond)) $get_posts .= " WHERE " . implode(" AND ",$where_cond);
$run_posts = mysqli_query($con,$get_posts);
$posts_array = array();
while ($posts_row = mysqli_fetch_array($run_posts)){
$row_array['title'] = $posts_row['title'];
$row_array['author'] = $posts_row['author'];
$row_array['bookUrl'] = $posts_row['bookUrl'];
$row_array['imageUrl'] = $posts_row['imageUrl'];
$row_array['displayDate'] = $posts_row['displayDate'];
$row_array['numberOfPages'] = $posts_row['numberOfPages'];
array_push($posts_array,$row_array);
}
$string = json_encode($posts_array,JSON_UNESCAPED_UNICODE);
echo $string;?>
because you want it to work for both id and q (and just one of them) I'm inserting each condition to an array and then implode it with AND separator
it's untested.
Related
So I have my code
function GetApi($connection,$UserId){
global $Apicall;
$Apicall = array();
$Apiidquery = mysqli_query($connection, "SELECT ID FROM ` Characterapi` WHERE UserId = '$UserId'");
while($results = mysqli_fetch_assoc($Apiidquery)){
$Apicall[] = $results['ID'];
}
}
The output of this function if I call
$Apicall[0] = 3
$Apicall[1] = 11
and this is the information I want. But now I want to use a function like
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$Keyidquery = array();
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ID = '$Apicall'");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
This code does run if i set $Apicall ="3"; The issue im having is that I want the first function to get All the IDs associated with $userId in my data base then for each Id run the second function to to get the two specific pieces of information from that query.
In response to the comment below, this is the solution which I would use. However you should be wary of using this method as it does not parameterize the values, and as such not sanitized.
<?php
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$string = "ID IN('";
$string.= implode("','", $Apicall);
$string.="')";
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ".$string.";");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
?>
I need some help with JSON and PHP. Here's my code in PHP:
include 'class.Connection.php';
$branch = $_GET["b"];
$records = array();
$sqlNailDisplay = "SELECT NAD_ID FROM tbl_NailArtDesign WHERE NAD_Available = 1";
$query0 = mysql_query($sqlNailDisplay) or die(mysql_error());
while($rSet0 = mysql_fetch_array($query0, MYSQL_BOTH)) {
$actualPrice = 0.00;
$nailart = $rSet0["NAD_ID"];
//please note, { is the ascii code for '{', } is the ascii code for '}', while " is the ascii code for '"'
$mergedData = "{"NAD_ID":"".$nailart."","";
//individual nail art details
$sqlNailArt = "SELECT * FROM tbl_NailArtDesign WHERE NAD_ID = '".$nailart."' AND NAD_Available = 1";
$query1 = mysql_query($sqlNailArt) or die(mysql_error());
while($rSet1 = mysql_fetch_array($query1, MYSQL_BOTH)) {
$NAD_Ext = $rSet1["NAD_Ext"];
$CC_ID = $rSet1["CC_ID"];
$CT_ID = $rSet1["CT_ID"];
$CST_ID = $rSet1["CST_ID"];
if(empty($CST_ID)) {
$CST_ID = "null";
}
$NAD_Descrip = $rSet1["NAD_Descrip"];
$mergedData = $mergedData."NAD_Ext":"".$NAD_Ext."","CC_ID":"".$CC_ID."","CT_ID":"".$CT_ID."","CST_ID":"".$CST_ID."","NAD_Descrip":"".$NAD_Descrip."","";
}
//product used and price details
$sqlProductsUsed = "SELECT PL_ID FROM tbl_ProductUsed WHERE NAD_ID = '".$nailart."'";
$query2 = mysql_query($sqlProductsUsed) or die(mysql_error());
while($rSet2 = mysql_fetch_array($query2, MYSQL_BOTH)) {
$PL_ID = $rSet2["PL_ID"];
$sqlProductPrice = "SELECT PP_Amount FROM tbl_ProductPrice WHERE PL_ID = ".$PL_ID." AND BL_ID = '".$branch."'";
$query3 = mysql_query($sqlProductPrice) or die(mysql_error());
while($rSet3 = mysql_fetch_array($query3, MYSQL_BOTH)) {
$price = number_format($rSet3["PP_Amount"],2);
$actualPrice = number_format($actualPrice + $price,2);
}
$mergedData = $mergedData."PL_ID":"".$PL_ID."","PP_Amount":"".$price."","";
}
$mergedData = $mergedData."NAD_Price":"".$actualPrice.""}";
$records[] = $mergedData;
} mysql_free_result($query0);
echo json_encode($records);
And this is the result I'm getting:
["{"NAD_ID":"ND0001","NAD_Ext":"jpg","CC_ID":"1","CT_ID":"1","CST_ID":"null","NAD_Descrip":"Giving you the aquatic feeling with Turquoise Marble","PL_ID":"1","PP_Amount":"9.00","PL_ID":"2","PP_Amount":"9.10","PL_ID":"3","PP_Amount":"9.00","NAD_Price":"27.10"}","{"NAD_ID":"ND0002","NAD_Ext":"jpg","CC_ID":"1","CT_ID":"1","CST_ID":"null","NAD_Descrip":"Add a twirl in your life with Lavender Twirl","PL_ID":"1","PP_Amount":"9.00","PL_ID":"2","PP_Amount":"9.10","PL_ID":"3","PP_Amount":"9.00","NAD_Price":"27.10"}"]
I need my result to look like this:
[{"NAD_ID":"ND0001","NAD_Ext":"jpg","CC_ID":"1","CT_ID":"1","CST_ID":"null","NAD_Descrip":"Giving you the aquatic feeling with Turquoise Marble","PL_ID":"1","PP_Amount":"9.00","PL_ID":"2","PP_Amount":"9.10","PL_ID":"3","PP_Amount":"9.00","NAD_Price":"27.10"},{"NAD_ID":"ND0002","NAD_Ext":"jpg","CC_ID":"1","CT_ID":"1","CST_ID":"null","NAD_Descrip":"Add a twirl in your life with Lavender Twirl","PL_ID":"1","PP_Amount":"9.00","PL_ID":"2","PP_Amount":"9.10","PL_ID":"3","PP_Amount":"9.00","NAD_Price":"27.10"}]
There an extra double quotes that I need to remove from my output.
["{" , ",*"* , }"]
Please help, I'm already at my limit and I already did searching for this, and I can't seem to get any resolution for this...
Hardcoded method:
$result = "[".substr(json_encode($records), 2, -2)."]";
$result = str_replace('","', ',', $result);
I am unsure how to display the items field. I want to display two tables of data; one that has all the items from a user and one with all the items to teh user. All I've been able to output is the item_id's(I pasted the html below). How to get all the item info from these ids, which is in the item table, and populate the HTML?
trans table
item table
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$t</td>
<td>$u</td></tr>";
}
HTML DISPLAY
Try this!
<?php
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$items = array();
foreach($itemIDs as $ID){
$sqlItem = $db->prepare("SELECT itemname FROM itemtable WHERE itemid = :itemid");
$sqlItem->bindValue(':itemid', $ID);
$sqlItem->execute();
$itemname ='';
while($rowItems = $sqlItem->fetch())
{
$itemname .=$rowItems['itemname'];
}
$items[$t] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$t]</td> <td>$u</td></tr>";
}
below is my code for testing,
<?php
$from = 1;
$sql = mysqli_query($db,"SELECT * FROM test WHERE from_id = '$from'");
while($row = mysqli_fetch_array($sql))
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$itemname ='';
foreach($itemIDs as $ID){
$sqlItem = mysqli_query($db, "SELECT itemname FROM itemtable WHERE item_id = '$ID'");
while($rowItems = mysqli_fetch_array($sqlItem))
{
$itemname .= $rowItems['itemname'].', ';
}
$items[$u] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$u]</td> <td>$u</td></tr>";
}
echo "<table>".$trans."</table>";
?>
Note : change my queries with ur need
in ur while loop
while($row = $sql->fetch())
{
$items_array = array();
$items_array = explode(",",$row["items"]);
foreach($items_array as $key => $value)
{
//modify ur query according to ur need
$query3 = "SELECT item_name
FROM item_table
WHERE item_id =".$value." ";
$result3 = mysql_query($query3);
$row3 = mysql_fetch_assoc($result3);
$item_name .= $row3['subcategory_name'].", ";
}
}
now ur array will contains item_id,
use foreach loop in ur while loop and get info of Item from item table with item_id from expolode function
Within while you will have to fire new query that will get the information of items.
For eg :
"SELECT * FROM item_info_table WHERE id IN (id1,id2, id3)"
It will return you the item information corresponding to the id's.
The data is not normalized. Get it to normalize and you'll have a much better and cleaner solution.
Hi I would like to display the number of item in the database. The following is the php code:
$jobid = $_SESSION['SESS_MEMBER_JOB'];
$data = "SELECT * FROM attributes WHERE jobid = $jobid";
$attribid = mysql_query($data) or die(mysql_error);
$count = "SELECT count(*) FROM attributes WHERE jobid = $jobid";
$database_count = mysql_query($count);
//Declare the Array
$DuetiesDesc = array();
print_r ($database_count);
But instead of getting the desired result, I get :
Resource id #14
Please Assist
Should get it out of the way that you shouldn't be using mysql_* see Why shouldn't I use mysql_* functions in PHP?
See the code below... explanations are in comments
$jobid = $_SESSION['SESS_MEMBER_JOB'];
// escape variables using mysql_real_escape_string
$data = "SELECT * FROM attributes WHERE jobid =".mysql_real_escape_string($jobid);
$attrRes = mysql_query($data) or die(mysql_error());
// I'm assuming you want all of the attributes return in this query in an array
$attributes = array();
while($row = mysql_fetch_assoc($attrRes)){
$attributes[] = $row;
}
// Now if you want the count we have all of the records in the attributes array;
$numAttributes = count($attributes);
// here is an example of how you can iterate through it..
print "<p>Found ".$numAttributes." attributes</p>";
print "<table>";
foreach($attributes as $row){
print "<tr>";
foreach ($row as $cell){
print "<td>".$cell."</td>";
}
print "</tr>";
}
print "</table>";
Try this
<?php
$jobid = $_SESSION['SESS_MEMBER_JOB'];
$data = "SELECT * FROM attributes WHERE jobid =$jobid";
$attribid = mysql_query($data) or die(mysql_error);
$count=mysql_num_rows($attribid);
echo $count;
?>
try this
$jobid = $_SESSION['SESS_MEMBER_JOB'];
$data = "SELECT *FROM attributes WHERE jobid =$jobid";
$attribid = mysql_query($data) or die(mysql_error);
$count = "SELECT count(*) FROM attributes WHERE jobid = $jobid";
$database_count = mysql_query($count);
//Declare the Array
$DuetiesDesc = array();
$database_count=mysql_fetch_assoc($database_count);
echo $database_count['count(*)'];
I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!