I want to pass multiple values through my url as below.
http://example.com/shopping_cart_json_api.php?uid=5710,55
I have created the php encode file as below however I am unable to get proper result out.
<?php
require('adminpanel/includes/application_top.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = explode(",", $_GET["uid"]);
$sth = mysql_query(" SELECT drug_medicines.fld_id,
drug_medicines.fld_image, drug_medicines.ld_product_name,
drug_medicines.fld_best_price,drug_cart.ld_userid,
drug_cart.fld_qunty, drug_cart.fld_totalprice
FROM drug_medicines
INNER JOIN drug_cart
ON drug_medicines.fld_id=drug_cart.fld_productid
WHERE fld_userid='" . $id . "' ||'" . $id . "'");
$rows = array();
while ($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
?>
Format should be like this.
WHERE fld_userid='".$id[0]."' OR fld_userid= '".$id[1]."'");
For values more than 2 use
WHERE fld_userid IN (" . implode(',', $id) . ")"
As per your URL you might have more values in future so you should use IN function of mysql
fld_userid IN ($id);
Use IN in mysql query.
<?php
require('adminpanel/includes/application_top.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = explode(",", $_GET["uid"]);
$sth = mysql_query("
SELECT
drug_medicines.fld_id,
drug_medicines.fld_image, drug_medicines.ld_product_name,
drug_medicines.fld_best_price,drug_cart.ld_userid,
drug_cart.fld_qunty, drug_cart.fld_totalprice
FROM
drug_medicines
INNER JOIN
drug_cart
ON
drug_medicines.fld_id=drug_cart.fld_productid
WHERE
fld_userid IN (" . $_GET["uid"] . ")");
$rows = array();
while ($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
?>
You should use IN for more flexibility.
"... WHERE fld_userid IN (" . implode(',', $id) . ")"
Which will output:
"... WHERE fld_userid IN (5710,55)"
Related
i have little problem here, i want to generate some data to specific JSON format from Mysql using PHP, this is my PHP code
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
// echo(json_encode($names));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
?>
With this code, the result was
[
[1478616679000, 1478616677000, 1478616675000, 1478616673000, 1478616671000],
[28.4126, 28.5361, 28.4126, 28.4126, 28.2891]
]
Yes, that is valid JSON but, i want to use this JSON for chart in highcharts.com, so i need the JSON format like this
[
[1257811200000, 29.00],
[1257897600000, 29.04],
[1257984000000, 28.86],
[1258070400000, 29.21],
[1258329600000, 29.52],
[1258416000000, 29.57],
[1258502400000, 29.42],
[1258588800000, 28.64],
[1258675200000, 28.56],
[1258934400000, 29.41],
[1259020800000, 29.21],
[1259107200000, 29.17],
[1259280000000, 28.66],
[1259539200000, 28.56]
]
Gladly if someone can help me, i'm stuck for a days try to solving this issue
If you want the code like that, you must fix the code:
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
must be something like this:
while($row = $result->fetch_array()){
$rows[] = array(
(float)$row['ai0_hist_value'],
strtotime($row['meas_date'])*1000);
}
echo (json_encode($rows));
You were saving in $data2 an array with two arrays, the text and the data. You must save a row for each pair of 'text' and 'data'.
Could construct the formatted series data to begin with like below:
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$seriesData[] = [ strtotime($row['meas_date'])*1000, (float)$row['ai0_hist_value'] ];
}
echo (json_encode($seriesData));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
This will generate the array you want, there is no need to do all that fiddling with the data from the database
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
$rows = array();
if ($result = $db->query($sql)) {
while($row = $result->fetch_array()){
$rows[] = array(strtotime($row['meas_date'])*1000,
$row['ai0_hist_value']
);
}
}
echo json_encode($rows);
Now you will need to convert the text to float in the javascript. This is because JSON is passed as text and not any other data type, so it has to be converted, if necessary in the receiving javascript.
I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here
I have a MySQL query like this written in PHP:
$merkki = $_GET["merkki"];
// Retrieve all the data from the table
//to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '}';
Result is correct, but how I can get a comma after each record? If I echo (,) after each row my code doesn't work. I need it formatted as described below.
{
"":"--",
"series-1":"1 series",
"series-3":"3 series",
"series-5":"5 series",
"series-6":"6 series",
"series-7":"7 series"
}
What's the best way to do this?
Immediately stop using your code. It is vulnerable to SQL injection. Think of what would happen if the value of merkki was 1 OR 1=1. The statement would return all records:
SELECT * FROM Control_Mallit WHERE merkki_id = 1 OR 1=1
You need to bind parameters to your query using mysqli_ or PDO functions (mysql_ functions are being deprecated. Also, use a column list and do not SELECT *.
Here is a possible solution using mysqli_ (not tested):
<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$array = array();
/* create a prepared statement */
$stmt = mysqli_prepare($link, "SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, 'i', $_GET[merkki]);
/* execute query */
$result = mysqli_stmt_execute($stmt);
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
echo '{' . implode(',', $array) . '}';
?>
Edit
Following your original code, this solution should work:
$merkki = $_GET["merkki"];
$array = array();
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '{' . implode(',', $array) . '}';
Try:
$merkki = $_GET["merkki"];
$merkki = mysql_real_escape_string($merkki);
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
$numRows = mysql_num_rows($result);
$row = 1;
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
if ($row < $numRows) {
echo ',';
}
$row++;
}
echo '}';
It just uses the row count to determine if it should echo a comma or not based on whether or not it is on the last result.
Also, be sure to escape any input you pass to mysql queries or you are vulnerable to SQL injection. See about switching to PDO or Mysqli in the future.
I'd just stick everything in an array and use json_encode() to output it, eg
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[$row['id']] = $row['malli'];
}
echo json_encode($data);
Small example here - http://codepad.viper-7.com/My27XJ
Also, you should not be using the deprecated mysql extension. Instead, I recommend PDO, eg
$db = new PDO(/* connection details */);
$stmt = $db->prepare('SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?');
$stmt->bindParam(1, $_GET['merkki']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// and so on
I tried combining as suggested in a previous link but Im still getting a error. I am fairly new to php so that is why i have two querys.
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/vhockey/public_html/vhatest/connect.php on line 88
The table is "season12" and the table is "p"
Here is my connect.php file except server info...
function index_team_stats($subconference) {
$return = array();
$query = "SELECT id, teamname, teamnameseason, teamabr
FROM teams
WHERE subconference = '" . $subconference . "'
ORDER BY teamnameseason";
$teams = result_array($query);
foreach ($teams as $team)
{
$query = "SELECT gp, w, l, ol, p
FROM season12
WHERE team = '" . $team['teamnameseason'] . "'
ORDER BY p DESC
LIMIT 0,20'; ";
$results = result_array($query);
if ($results)
{
$results[0]['team'] = str_replace($team['teamnameseason'], '', $team['teamname']);
$results[0]['teamabr'] = $team['teamabr'];
$results[0]['teamid'] = $team['id'];
$return[] = $results[0];
}
}
return $return;
}
function get_team_name($teamnameseason) {
$query = "SELECT teamname FROM teams WHERE teamnameseason = '" . $teamnameseason . "'";
$row = mysql_fetch_row(mysql_query($query));
return str_replace($teamnameseason, '', $row[0]);
}
function result_array($query) {
$results = mysql_query($query) or die("error on: " . $query . " saying: " . mysql_error());
$return = array();
while ($row = mysql_fetch_assoc($results)) {
$return[] = $row;
}
return $return;
}
Here is an image of the info ![All info sorted by team PTS from highest to lowest
Should show Penguins, FLyers, Islanders, Rangers, Devils..
Use a JOIN. An example is below. You may need to tweak based on your specific needs.
SELECT teams.id, teams.teamname, teams.teamnameseason, teams.teamabr, season12.gp,
season12.w, season12.l, season12.ol, season12.p
FROM teams, season12
INNER JOIN season12
ON teams.teamname=season12.team
WHERE teams.subconference = '$subconference'
ORDER BY season12.p
LIMIT 0,20
Please note this code is not tested and may require modification.
You can use php sort function http://php.net/usort
$callback = new function ($el1, $el2) {
if ($el1['points'] == $el2['points']) {
return 0;
}
return ($el1['points'] < $el2['points']) ? -1 : 1;
}
$sorted_result = usort($results, $callback);
I am wanting to not echo out the comma at the end of the echo after the last row. How can I do that? Here is my code:
<?php
header("Content-type: application/json");
echo '{"points":[';
mysql_connect("localhost", "user", "password");
mysql_select_db("database");
$q = "SELECT venues.id, venues.lat, venues.lon, heat_indexes.temperature FROM venues, heat_indexes WHERE venues.id = heat_indexes.venue_id";
$res = mysql_query($q) or die(mysql_error());
while ($point = mysql_fetch_assoc($res)) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
mysql_free_result($res);
echo ']}';
?>
Could you not use json_encode() instead, rather than hand-crafting the JSON?
$result = array();
//snip
while ($point = mysql_fetch_assoc($res)) {
$result[] = $point['lat'];
$result[] = $point['lon'];
$result[] = $point['temperature'];
}
//snip
header("Content-type: application/json");
echo json_encode( array('points' => $result) );
Use a count query to get the number of rows to begin with.
$query= "SELECT COUNT(*) FROM venues";
$count= mysql_query($q);
Then introduce a conditional and a count decrease each time through...
while ($point = mysql_fetch_assoc($res)) {
$count = $count - 1;
if ($count == 1) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
} else {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
Json encode would probably be your best bet, but you could also use trim();
Rather than echoing in the while loop, append to a variable. Once outside the while loop, use $output = trim($output, ',') to remove trailing commas.
About the comma problem, I always target the first item instead of the last:
$first = true;
while ($point = mysql_fetch_assoc($res)) {
if ($first)
{
$first = false;
}
else
{
echo ",";
}
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
}
You can use mysql_num_rows() to find out how many rows are in the result set passed back from your last query.
...
$res = mysql_query($q) or die(mysql_error());
$num_rows = mysql_num_rows($res);
Then combine that with Scotts answer and you should be set.