print json_encode of a MySQL SUM() function - javascript

I am trying to print with JSON a SUM() of a price.
Currently I am trying:
$query="SELECT SUM(cost) FROM `Service`";
$result = mysql_query($query);
$json = array();
while($row = mysql_fetch_array($result))
{
$json['cost'] = $row['cost'];
}
print json_encode($json);
mysql_close();
This returns null.
If I try SELECT cost FROM Service instead, it returns the last cost from the database.
What Im I doing wrong?

supply an ALIAS on the column passed on the aggregate function
SELECT SUM(cost) totalCOST FROM `Service`
so you can fetch the columnName
$json['cost'] = $row['totalCOST'];

Related

How to get products from table with exact ids from array?

I have a sql table with products and i don't get how to retrieve several products using array with their ids
i know how retrieve all of these products and only one using id
JSON with all products from sql
function loadGoods(){
$conn = connect();
$sql = "SELECT * FROM PRODUCTS";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$out = array();
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$out[$row["id"]] = $row;
}
echo json_encode($out);
} else {
echo 0;
}
mysqli_close($conn);
}
JSON with one product using its id received in js file from hash
function loadSingleGoods(){
$id = $_POST['id'];
$conn = connect();
$sql = "SELECT * FROM PRODUCTS WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
echo json_encode($row);
} else {
echo 0;
}
}
Both of these snippets are working and now i have array with id's but i don't get how retrieve only their properties from sql in JSON file.
I have array with ids like this ["6", "7", "27"] and i need to retrieve from sql PRODUCTS only items with these ids. As i understand i have to do something with this line
$sql = "SELECT * FROM PRODUCTS WHERE id='$id'";
i tried such code
$sql = "SELECT * FROM PRODUCTS WHERE in_array("id", $ids, TRUE);
but it didn't work
It would be helpful if you showed us your JavaScript also, but assuming you're feeding the output of the json_encode() into a single variable, you can access each product like so:
console.log(json_variable[0]);
That should give you the first "row". To access a particular cell, try this:
console.log(json_variable[0]['column_name']);
To go thru all of them, try jQuery's each():
$.each( json_variable, function( id, column_name) {
console.log( id + ": " + column_name);
});
You can parse json object using JSON.parse() and access all the value of the object.
var text = '{ "name":"John", "age":"39", "city":"New York"}';
JSON.parse(text, function (key, value) {
console.log(value);
});
Here you can replace text with your json variable.
If you want to read more about json parse & how to access json variable in js click here.
You can build your query before executing it:
$sql_array=array("6", "7", "27");
$first_item=array_values($sql_array)[0];
$sql="SELECT * FROM `PRODUCTS` WHERE `id`='$first_item'";
$built_query="";
foreach ($sql_array as $k => $id) {
if ($k < 1) continue;
$built_query=$built_query." OR `id` = '$id'";
}
$built_query=$sql.$built_query;
echo "$built_query";

Save results from pdo query to a javascript variable

I am new to javascript so please be patient with me.
I have a function in php which goes like this:
public function getSubjects() {
$stmt = $this->_db->prepare('SELECT id, subject from subjects');
$stmt->execute();
return $stmt->fetchall();
}
Then I have a variable subs in javascript which is hardocded like this:
var subs = {"Maths":1,"Geography":2,"Chmesitry":3,"Literature":4};
How do I populate the subs variable with the format above from the getSubjects method?
I like to use json_encode to convert the array to json so it can be used as an array of objects in JS.
PHP:
public function getSubjects() {
$stmt = $this->_db->prepare('SELECT id, subject from subjects');
$stmt->execute();
return json_encode($stmt->fetchall());
}
In javascript:
var subs = <?php echo getSubjects(); ?>;
console.log(subs);

Create a JSON string with each row in MySQL database as new array element

I have a MySQL database ($database) set up, with a table ("gigdata") and column names as follows:
id
clientname
day
month
year
postcode
status
entered
Each column name has a few rows of test data under it. I have successfully connected to the database using PHP's mysqli class, as below.
So far, I have written this PHP:
//Connect to database
$conn = new mysqli(localhost, $username, $password, $database);
//Check connection
if ($conn->connect_error) {
die("Failed to connect to MySQL: " . $conn->connect_error);
}
echo "<p>Connected to database</p>";
//Select data from database
$sql = "SELECT id, clientname, day, month, year, postcode, status, entered FROM gigdata";
$result = mysqli_query($conn, $sql);
//Create an empty array
$gigarray = array();
//Check data exists, if YES store in array
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
foreach ($row as $r) {
array_push($gigarray, $r);
}
}
} else {
echo "0 results";
}
I'm then echoing the JSON string into Javascript, which works fine:
var gigdata = <?php echo json_encode($gigarray) ?>;
QUESTION
My aim is to adapt the original PHP so that the JSON ends up formatted such that:
each database row is a new array element
each database column name is the name in each JSON name/value pair
each database field is the value in each JSON name/value pair
Hope this makes sense, and thanks a lot in advance.
There's actually a very helpful mysqli function for getting all data from a result, exactly how you want it - mysqli_fetch_all
Try:
json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));

Return multiple results with AJAX from sql query in php

Hello I am realizing simple AJAX request and would like to be able to store the results from the SQL SELECT query into 3 different ajax variables.
Where 2 of them will store one variable and the other one have to store foreach results.
Let's say my AJAX request is the following:
$.post('includes/check_number.php', {'date':date, 'userid':userid}, function(data) {
$("#time-result").html(data.result01);
$("#time-sum-result").html(data.result02);
Where I will have 2 results result01 and result02
In the current state of my script inside the mysql select request what is returning like data is the following:
$stmt = $con->prepare( $sql );
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
foreach($stmt as $row) {
echo "<tr>
<td>".$row['clientname']."</td>
<td>".$row['taskname']."</td>
<td>".$row['department']."</td>
<td>".$row['note']."</td>
<td>".$row['caseid']."</td>
<td>".$row['time']."</td>
</tr>";
}
I would like to put the result of the forreach as it is inside the echo, where it will contains various iterations and then for result02 for example would like to put only one row of the same query for example like: $row['date']
In this case
data.result01 - will have all the code of the <tr></tr>
data.result02 - will have only one variable which is date.
Question is how to dump the foreach into result01 and in the same time to put in result02 only one row from the same query. $stmt
Export all your data first then use it with jquery ?
Something like :
PHP :
foreach($stmt as $row) {
$arr_out[] = $row;
}
echo json_encode($arr_out);
exit();
JQUERY :
var result1 = "";
$.post('includes/check_number.php', {'date':date, 'userid':userid}, function(data) {
$.each(data, function(key, item) {
result1 += "<tr><td>"+item.clientname+"</td>[...]<td>"+item.time+"</td></tr>";
result2 = item.date;
});
$("#time-result").html(result1);
}
I didn't test this code, hope it will help you.

Storing data from MySQL to PHP Array to return with JSON

I have a MySQL table with cols | btn_id | btn_title | btn_bg | btn_text |.
I am trying to get the data in the table to a php array and then return via JSON so the array can be used in the JS document requesting the PHP/MySQL Data. Respective of row and columns/index.
So far i have:
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
Q. Now i wish to return a JSON Array made from the array of data. How do i proceed here?
Note: I am horrible with arrays and not entirely sure i have the correct method above for my requirements, but i think it is correct.
Call json_encode after the loop:
header("Content-type: application/json");
echo json_encode($array);

Categories

Resources