when I return my array by I got [{"product":"TEST_1","best_selling_product":"305"},{"product":"IPHONE 4S","best_selling_product":"108"}] , but Highcharts dont let me use string as value then how can I change it to int or float? my backend function is this
function best_selling_product(){
$sql = "SELECT product,SUM(sale_detail.amount) AS best_selling_product FROM sale_detail INNER JOIN product ON sale_detail.idproduct = product.idproduct GROUP BY sale_detail.idproduct ORDER BY SUM(sale_detail.amount) DESC LIMIT 0,5";
$result = $this->conexion->conexion->query($sql);
$array = array();
while($record = $result->fetch_array(MYSQLI_ASSOC)){
$array[] = $record;
}
return $array;
$this->conexion->cerrar();
}
In the json_encode() function, set the JSON_NUMERIC_CHECK flag.
You can either use CAST in the mysql query, or process the data in php using floatval() or intval().
For example in the mysql query:
SELECT CAST(SUM(sale_detail.amount) as UNSIGNED) AS best_selling_product FROM ...
OR with php:
while($record = $result->fetch_array(MYSQLI_ASSOC)){
$record['best_selling_product'] = floatval($record['best_selling_product']);
$array[] = $record;
}
Related
I am creating a time attendance PHP script. I started from storing data in the database MySQL and use different tables for the Punch-in/Punch-out, Breaks, Lunch/Dinner breaks.
Each one of the casualties mentioned before have a table which is structured with an:
ID, start, end, flag
I have already tried to do this with the following code of foreach but unsuccessfully!
foreach ($total as $key => $row) {
$start[$key] = $row['start'];
}
$final = array_multisort($start, SORT_DESC, $total);
echo $final;
Here is the code that I have made with 2 SELECT MySQL queries
$result = mysqli_query($db, "SELECT * FROM time WHERE username =
'$user_check' ORDER BY start DESC");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
} $db->next_result();
$result = mysqli_query($db, "SELECT * FROM break WHERE username =
'$user_check' ORDER BY start DESC");
$data2 = array();
while ($row = mysqli_fetch_assoc($result)) {
$data2[] = $row;
}
$total = array_merge ($data, $data2);
I would like to have 1 array of this 2 queries sorted DESC by start as I will use this array to populate a table in DESC order.
Use UNION ALL in your query, instead of merge arrays. Let the database do the work for you:
SELECT * FROM
(SELECT * FROM time WHERE username = '$user_check'
UNION ALL
SELECT * FROM break WHERE username = '$user_check'
) ORDER BY start DESC
PS: Your code is vulnerable to SQL Injection. You should use prepared statement instead.
How to make the array of id that we call from a table?
What I want is like this :
$array = array(1, 2, 3, 4, 5); // **1 - 5 select from a table**.
Thank you
Code :
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query )){
$a = implode(',',(array)$row['id_add_user']);
echo $a;
}
What I get from echo $a is 12345 not 1,2,3,4,5
Add all the elements to an array, then implode() it into one string with your desired deliminator (here, its ", ") once all results are fetched.
$result = [];
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query)){
$result[] = $row['id_add_user']);
}
echo implode(", ", $result);
Collect necessary values into an array.
$a = [];
while(...){
$a[] = $row['id_add_user'];
}
echo implode(',', $a);
You are trying to implode() the values for each row, you need to build an array of all the values and then output the result imploded. Also if you just want one column - just fetch that column in your SQL
You can further simplify it to...
$query = mysqli_query($conn, "SELECT id_add_user FROM tableA");
$rows = mysqli_fetch_all($query );
echo implode(',',array_column($rows, 'id_add_user' ));
mysqli_fetch_all allows you to fetch all the data in one go. Then use array_column() to extract the data.
$array = array(1,2,3,4,5);
Use below SQL query for selecting the array id data
SELECT column_name(s)
FROM table_name
WHERE column_name IN $array;
I have two MySQL output which I need to encode in a single JSON output.
Output 1:
$sql = "select * from t1 ORDER BY id DESC LIMIT 25";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$output[] = array_map("nl2br", $row);
}
Output 2:
$sql2 = "select * from t2 ORDER BY id DESC LIMIT 25";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$output2[] = array_map("nl2br", $row2);
}
This is what I am doing to get them in single JSON_encode:
echo json_encode($output.$output2);
still not getting both the outputs. I came to know of another solutions i.e. to merge both the queries but I am not able to do that as well. I referred this question also but no luck :(
How about using UNION in your query? Please check it out here: https://dev.mysql.com/doc/refman/5.0/en/union.html
What about
$fullOutput = array_merge($output1, $output2);
echo json_encode($fullOutput);
I'm trying to output data into an xml file, everything is working fine except it's only saving the last record fetched.
The following query is used:
$query = mysql_query("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");
while ($row = mysql_fetch_array($query)){
$result = $row['mileage'];
}
My question is how do I make it so each record is saved in 3 seperate variables so I can output those 3 variables into an xml file. I am also trying to fetch only the last 3 rows sorted by the last date and last time so not sure if the query is correct for doing that.
Thank you.
Firstly: Don't use the mysql_* functions! They are obsolete and you should use PDO instead.
Secondly: The easiest thing to do is to construct an array containing the results.
$result = array();
$query = mysql_query("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");
while ($row = mysql_fetch_array($query)){
$result[] = $row['mileage'];
}
The results of your query are now contained in $result[0], $result[1] and $result[2]. (If you use PDO the code does not look very different.)
$result=array();
$query = mysql_query("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$result[] = $row['mileage'];
}
You can use folowing;
$query = mysql_query("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");
while ($row = mysql_fetch_array($query)){
$result[] = $row['mileage'];
}
You can foreach $result and construct your xml.
try saving the output as an array instead.
$array[]=$value;
will push the $value inside the $array array.
get yourself a function
function dbGetCol($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_row($res)){
$ret[] = $row[0];
}
}
return $ret;
}
and then just call it
$data = dbGetCol("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");
I'm trying to mesh the below mysql query results into a single json object, but not quite sure how to do it properly.
$id = $_POST['id'];
$sql = "SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = '$id'
ORDER BY contracts.end_date";
$sql2 = "SELECT types_id
FROM contracts_types
WHERE contracts_id = '$id'";
//return data
$sql_result = mysql_query($sql,$connection) or die ("Fail.");
$arr = array();
while($obj = mysql_fetch_object($sql_result)) { $arr[] = $obj; }
echo json_encode($arr); //return json
//plus the selected options
$sql_result2 = mysql_query($sql2,$connection) or die ("Fail.");
$arr2 = array();
while($obj2 = mysql_fetch_object($sql_result2)) { $arr2[] = $obj2; }
echo json_encode($arr2); //return json
Here's the current result:
[{"po_number":"test","start_date":"1261116000","end_date":"1262239200","description":"test","taa_required":"0","account_overdue":"1","jobs_id":null,"job_number":null,"companies_id":"4","companies_name":"Primacore Inc."}][{"types_id":"37"},{"types_id":"4"}]
Notice how the last section [{"types_id":"37"},{"types_id":"4"}] is placed into a separate chunk under root. I'm wanting it to be nested inside the first branch under a name like, "types".
I think my question has more to do with Php array manipulation, but I'm not the best with that.
Thank you for any guidance.
Combine the results into another structure before outputting as JSON. Use array_values to convert the type IDs into an array of type IDs. Also, fix that SQL injection vulnerability. Using PDO, and assuming the error mode is set to PDO::ERRMODE_EXCEPTION:
$id = $_POST['id'];
try {
$contractQuery = $db->prepare("SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = ?
ORDER BY contracts.end_date");
$typesQuery = $db->prepare("SELECT types_id
FROM contracts_types
WHERE contracts_id = ?");
$contractQuery->execute(array($id));
$typesQuery->execute(array($id));
$result = array();
$result['contracts'] = $contractQuery->fetchAll(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
echo json_encode($result); //return json
} catch (PDOException $exc) {
...
}
If $contractQuery returns at most one row, change the fetch lines to:
$result = $contractQuery->fetch(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
It would seem like you'd be better served by consolidating the two queries with a JOIN at the SQL level. However, assuming the two arrays have equal length:
for ($x = 0, $c = count($arr); $x < $c; $x++) {
if (isset($arr2[$x])) {
$arr[$x] += $arr2[$x];
}
}
echo json_encode($arr);
Edit: you would need to change from mysql_fetch_object to mysql_fetch_assoc for this to work properly.
Why are you using 2 distinct arrays ? I would simply add the rows of the 2nd query in $arr instead of $arr2. This way, you end up with a single array containing all rows from the 2 queries.