Make a json object properly by retrieving data by MYSQL - php

I am making a php project and I am currently hosted it in my local xammp server.
I need to connect this to an android application using volley library.
So I need to make a json object.In orders I have stored picture of the product and orders.php page that I retrieve it via orderno.
In orders.php page I can see all my orders with images.
When trying to make the json object I need get this image url.I try to get it via order no but all the times i can't get the correct url.
Can anyone tell me how to solve this?
This is for making that json object.
This is the link to the image current json which I got
I want to make my image URL like below image:

There were multiple issues with your PHP code. However, I tried the resolve most of them. Still if you see any issues let me know, I will try to help you. I will highlight the changes I did to the code, for you to understand.
Here goes the PHP code to retrieve values:
<?php
// array for JSON response
$response = array();
include("config.php");
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die(mysqli_error());
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error());
$result = mysqli_query($con,"SELECT * FROM ORDERS");
if (!empty($result)) {
// check for empty result
if (mysqli_num_rows($result) > 0) {
// user node
$response["orderdata"] = array();
while($row = mysqli_fetch_array($result))
{
$orderdata = array();
$i = $row["ITEM_ID"];
$url = "http://localhost/Online_shopping/admin/'$i'.jpg";
$orderdata["url"] = $url;
$orderdata["item_id"] = $row["ITEM_ID"];
$orderdata["price"] = $row["PRICE"];
$orderdata["size"] = $row["SIZE"];
array_push($response["orderdata"], $orderdata);
}
// success
$response["response_code"] = 200;
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["response_code"] = 999;
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["response_code"] = 999;
// echo no users JSON
echo json_encode($response);
}
?>
You need to first setup a connection with your database which is located in a particular server.
Using that connection, you need to query in your table to get the data.
mysql_query, mysql_fetch_array is deprecated. You have to use mysqli instead of mysql.
Lastly, you can go through this post to learn simple basic operations using PHP.

Related

How can I open with PHP a SQlite Database and get the requestet information in a json document?

I will use data form my database to use it later in a JS function. To get the data form the database I use sql request in php, then copy it in json but I dont get the value of my request.
I'm opening my database With following code:
<?php
$db = new PDO("sqlite:Playerbase.db");
$info = $db ->query("SELECT Gamertag FROM player WHERE Highscore = 999");
$info_json = json_encode($info);
file_put_contents("Highscoreliste.json", $info_json);
echo '<script type="text/javascript">Highscoreliste();</script>';
//I want to open the .json in this js funktion and use the informaton from the request.
header("Location: index.html");
?>
But I dont get the real data in my .json, the value of the .json is:
{"queryString":"SELECT Gamertag FROM player WHERE Highscore = 999"}
Why am I just getting the Request copied in my .json and not the value of the request ? and how can I fix it ?
Here you can find more infos, how to use PDO : https://www.php.net/manual/en/pdo.query.php
Then here, there is a example how you can add JSON data into HTML, from Php :
<?php
$pdo = new PDO("sqlite:Playerbase.db");
$stmt = $pdo->query("SELECT Gamertag FROM player WHERE Highscore = 999");
$data = $stmt->fetchAll();
header("Location: index.html");
echo '<script type="text/javascript">const JSONDATA = ' . json_encode($data) . ';';
echo 'Highscoreliste(JSONData);</script>';
?>
But a better ways is to make an Ajax request to fetch your data from your Backend.

pass variable though URL for getting JSON

I have an app which loads data from a server and publish that data in the text view but there is a scene
<?php
define('HOST','xxxxxx');
define('USER','xxxxxxx');
define('PASS','xxxxx');
define('DB','xxxxxxx');
//Connecting to Database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$sql = "select * from Leaderboard where email='test#test.com'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('name'=>$row[1],
'rank'=>$row[2],
'accuracy'=>$row[3]));
}
echo json_encode (array("list"=>$result));
mysqli_close($con);
?>
this is my PHP file which gives JSON like this
{"list":[{"name":"Vipul S","rank":"1","accuracy":"80"}]}
and I am getting these values into my android app very easily using volley library but the thing is I need something to make that email variable dynamic because I am getting user email from users phone so I need to pass a variable to PHP through my android, so is there any chance that I can pass this through my URL which is written in android
my URL is: "http://thehostels.in/judgement_files/myleaderboard.php"
so can I pass the emails from URL that will be taken by PHP file through
$email=$_GET['userEmail'];
finally what I want is to that the JSON should change according to email that changes due to URL, I hope I made sense
You can pass email id in URL as
http://thehostels.in/judgement_files/myleaderboard.php?userEmail=test#test.com
and you can use this parameter in PHP as below
$email = $_GET['userEmail'];
$sql = "select * from Leaderboard where email='$email'";
For security reason you should use proper validation for email id.

Getting a SQL syntax error

I am trying to get the two values from my application in my php code. but before doing it I am trying to check through URL. But my problem is if give the values manual I am getting right output but when I check it by passing the values I am getting an syntax error. Can any one help me in solving this.
<?php
$hostname_localhost ="localhost";
$database_localhost ="mobiledb";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
$response = array();
mysql_select_db($database_localhost, $localhost);
$day = $_POST['day'];
$Q = $_POST['Qno'];
// get a product from products table
$result = mysql_query("SELECT $Q FROM `Questions` WHERE `day`='$day'") or die(mysql_error());
//echo $result;
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["question"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["question".$i] = $row["$Q"];
$i = $i + 1;
// push single product into final response array
array_push($response["question"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No users found";
// echo no users JSON
echo json_encode($response);
}
?>
I am trying to check through URL
By this I assume you mean you are trying to go to the url:
http://localhost/yoursite/yourpage?Qno=5&day=thing
In that case, those variables will be accessed as $_GET['Qno'] and $_GET['day'].
You can use $_REQUEST['Qno'] and $_REQUEST['day'] to receive the variables both ways. Of course, your application has so many security holes I won't even touch.
I would try escaping your values. will possibly fix your error and also protect you somewhat from SQL Injection which you should google and read.
$day = mysql_real_escape_string($_GET['day']);
$Q = mysql_real_escape_string($_GET['Qno']);
In this example, we use $_GET because you are trying to obtain the value directly from the URL.
Also, we escape the string to make sure we don't break our string syntax and inject bad monsters into your database!
ALSO: Mysql_ functionality is discontinued and you should stop using it. Read the big red box here: http://php.net/manual/en/function.mysql-query.php

got stuck converting MySql output in JSON array with php

I am making an iphone app. a part of that app allows users to search for a company on location.
I have a MySql database containing the companies that can be searched for, and a php file on my website to receive the searched data, and to return the companyName and companyLocation for all the found companies to my app. it looks like this:
<?php
if (isset($_GET["companyCitySearchField"])){
$companyCity = $_GET["companyCitySearchField"];
$result = search($companyCity);
echo $result;
}
function makeSqlConnection()
{
$DB_HostName = "******";
$DB_Name = "*******";
$DB_User = "*******";
$DB_Pass = "*******";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
return $con;
}
function disconnectSqlConnection($con)
{
mysql_close($con);
}
function search($companyCity)
{
$con = makeSqlConnection();
$query = mysql_query("SELECT companyName, companyCity from Company WHERE companyCity = '$companyCity'");
$companies = array();
while ($row = mysql_fetch_assoc($query)) {
$companies['companies'][] = $row;
print json_encode($companies);
}
disconnectSqlConnection($con);
}
?>
this works fine when only one company is found. it gives me a perfect JSON array:
{"companies":[{"companyName":"Dijkstra","companyCity":"Geldermalsen"}]}
everything fine so far.
Now, I create another company in my database, also with Geldermalsen as location.
2 companies are found in the database now. the JSON array it return now, doesn't make sense:
{"companies":[{"companyName":"Dijkstra","companyCity":"Geldermalsen"}]}{"companies":[{"companyName":"Dijkstra","companyCity":"Geldermalsen"},{"companyName":"testaccount","companyCity":"Geldermalsen"}]}
for some reason, it seems to make 2 separate array's. one for the first found company, and one with both.
I have been searching the web, stackoverflow, google and even the book 'PHP and MySql for dummies' for days, and I have changed my code numerous times, and whatever I try it keeps on doing this.
Does anyone know what I should do to get one array containing all found companies with this script, instead of these 2?
any help would be very welcome, Thank you in advance!
You are echoing out JSON for each row, not for the fully built array. Move your print statement outside the loop.
$companies = array();
while ($row = mysql_fetch_assoc($query)) {
$companies['companies'][] = $row;
}
print json_encode($companies);
Or better yet, you might not want to echo out anything at all in the search function, but leave that up to the caller. It seems you already might be intending to do this here:
$result = search($companyCity);
echo $result;
The only problem is that the search() function doesn't return any value so $result would be null. You should make up your mind about where you are going to echo the result to the client and be consistent about it.

sending http request using method post in php to a mobile application that is using objective C (.xcode)

I am working on project that is taking the data from a voiceXML application and then the voiceXML application send the variable that contains the data into a .php and I am done with that part but the problem is when I want to send the variable by sending a HTTP POST Request from .php to the mobile application which is installed on the iphone that is written using objective C programming language with an extension (.xcode), I faced a problem in receiving the variable on the mobile application,
So what I tried to do for a couple of months is to send the variable first to another .php and if it works with me, I will try to fixed the problem with mobile application.
I used httpRequest () Class - method post in order to send variable but the problem is that I don't know what to write on the other .php file to receive this variable and then display it.
This is the whole code :
<?php
//----------------------- Get the variable from .vxml file -----------------------------
$serverVariable = $_GET["spelling"];
//----------------------- Creation of the Database as a buffer -------------------------
$dbhost = 'localhost';
$dbuser = 'root';
$ReceivedFlag=0;
$ReadFlag=0;
$conn = mysql_connect($dbhost, $dbuser);
$table= mysql_select_db('storagedb',$conn);
//************************** Request Table (Insertion)***************************
$getUser_sql=" INSERT INTO request VALUES (6,$serverVariable,1,0)";
$result=mysql_query($getUser_sql,$conn);
//************************** Request Table (Selection)**************************
//$ReceivedFlag="SELECT ReceivedFlag FROM request";
//$ReadFlag="SELECT ReadFlag FROM request";
while(($ReceivedFlag==1) && ($ReadFlag==0))
{
$postUser_sql= "SELECT Message FROM request";
$result1=mysql_query($postUser_sql,$conn);
echo "<TABLE BORDER=4>";
echo "<TR><TH>Message</TH></TR>";
// format results by row
while ($row = mysql_fetch_array($result1))
{
$Message = $row["Message"];
echo "<TR><TD>$Message</TD></TR>";
}
echo "Response</TABLE>";
$query = "UPDATE request SET ReadFlag=1 WHERE ReceivedFlag=1";
$result2=mysql_query($query,$conn);
}
//-------------- post the server variable to the other client -----------------------
$r = new HttpRequest('http://localhost/form.php', HttpRequest::METH_POST);
$r->addPostFields(array('user' => $Message ));
try {
echo $r->send()->getBody();
} catch (HttpException $ex) {
echo $ex;
}
?>
I used the database as a buffer since I am working on different sessions which is between the .VXML and first .php or the first .php and second .php
The form.php contains the following which just display a white page and doesn't print
the variable that is coming from the first .php:
<?php
$clientVariable=$_POST['Message']; //to print out the data
print ($clientVariable);
?>
So what I have to do in order to receive the variable correctly and display it in the second php?
I appreciate your help.
Regards,
Heba
If your variable contains sensitive data, I would use a session. If not, you can simply use GET:
Using a session:
session_start();
$_SESSION['myvariable'] = 'Insert variable here';
Then in php2:
session_start();
echo $_SESSION['myvariable'];
Or you can use GET:
header("Location: /php2.php?myvar=insertcontent");
Then in php2:
echo $_GET['myvar'];

Categories