How can I create an array from the results of 2 queries? - php

I'm trying to create an array from the results of 2 queries, and send it all together to front-end, but I'm stuck to the point where I need to push the results of the second query to the array, I tried to do it using array_push but doesn't work.
Let's say we have this example, and I need to include the results of $query2 to $return_arr
Any ideas?
<?php
header('Access-Control-Allow-Origin: *');
include "config.php";
$return_arr = array();
$query1 = "SELECT * FROM balance WHERE class='income' ORDER BY id DESC";
$query2 = "SELECT * FROM balance WHERE class='expense' ORDER BY id DESC";
$result1 = mysqli_query($conn,$query1);
while($row = mysqli_fetch_array($result1)){
$id = $row['id'];
$description = $row['description'];
$date = $row['date'];
$euro = $row['euro'];
$who = $row['who'];
$class = $row['class'];
$return_arr[] = array("id_income" => $id,
"description_income" => $description,
"date_income" => $date,
"euro_income" => $euro,
"who_income" => $who,
"class_income" => $class
);
}
// Encoding array in JSON format
echo json_encode($return_arr);

Here's a different query:
SELECT *
FROM balance
WHERE class IN('income','expense')
ORDER
BY class
, id DESC

Like JS Bach answer. But maybe you could speed up performance by mention the column's name.
SELECT column1, column2, column3 FROM balance WHERE class IN ('income','expense') ORDER BY class, id DESC;

You can also make use of OR operator
$query = SELECT * FROM balance WHERE class = "income" OR class = "expense" ORDER BY class, id DESC;
$result = mysqli_query($conn,$query);
$array = mysqli_fetch_array($result,MYSQLI_ASSOC);
Your fetched records will already be in an array format in $array
This can be more effective when dealing with tables having records in 1000s of rows

Related

How to combine multiple query's into one?

I am running a line graph on RGraph framework, and I am using a SELECT COUNT statement for rejected, accepted, approved etc.....counting how many items was rejected or accepted etc and then dumping the query data into an array, However I am looking for an easier way to implement this query, instead of running a query on each unique row value, also thinking in the way if I have to encounter other column data besides rejected, accepted or etc....I wouldnt, my code doesnt seem very scalable then. Please help
So far, I am running a query for each keyword, hope my code explains this.
The final variable is what i am feeding to RGRAPH, This works fine as it is, however it isn't the right way, and not very scalable, should my row data change.
<?php
$cxn = mysqli_connect("localhost","root","", "csvimport");
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = 'rejected'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$rejected = $display[0];
//echo $rejected;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion =
'accepted'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$accepted = $display[0];
//echo $accepted;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = '-'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$dash = $display[0];
//echo $dash;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion =
'approved'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$approved = $display[0];
//echo $approved;
$datarray = [$rejected, $accepted, $dash, $approved];
print_r($datarray);
$data_string = "[" . join(", ", $datarray) . "]";
echo "<br>";
print_r($data_string);
?>
You can just use GROUP BY and add the conclusion column to the result set, so
SELECT conclusion, COUNT(*) as total
FROM table_1
WHERE conclusion in ('rejected', 'accepted', '-', 'approved')
GROUP BY conclusion
Then retrieve each row of the result set
$totals = [];
while($row = mysqli_fetch_array($result)) {
$totals [$row[0]] = [$row[1]];
}
and $totals will be an array something like
array( 'accepted' => 12,
'approved' => 20...)
If you want all of the conclusions, then just remove the WHERE conclusion in line and it will return all of the possibilities along with the count.

i want to select a randomly data using php

I need help in selecting a random data from the table
Let's suppose There are 10 columns in my table but i want that if I hit the query sometime it will bring all data and sometime it will bring data only from 1 column and some time from the no 1 and no 2 column
How can I achieve this?
Thanks in advance
function selectAllInventoriesINGroup($conn,$groupname,$import_id)
{
$cgstSgst = explode('-', $groupname);
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
$result = $conn->query($sql);
$jsonxx = mysqli_fetch_all ($result, MYSQLI_ASSOC);
return $jsonxx ;
}
I have tested this but it fetch the all the data from the database
<?php
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
?>

Is there a way to sort PHP array_merge based on raw[2]?

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.

Displaying Row Count for Data in PHP

Been at this awhile...this is actually another simplified question to a problem I posted earlier. I'm trying to display the country and count for the following query:
$query = mysqli_query($con, "SELECT COUNT(id), country FROM users GROUP BY country ORDER BY COUNT(id) DESC");
while ($row = mysqli_fetch_array($query)) {
$countries = $row['country'];
echo $countries;}
What I'm getting in output is the countries listed from highest to lowest, but it does not have the count displayed next to it. I know these have been summed in the query, how do I target the number & assign it to a php variable for display?
Any help would be appreciated.
You can use an alias for your COUNT column and then reference that in the array returned by mysqli_fetch_array for each row.
$query = mysqli_query($con, "SELECT COUNT(id) AS countryCount, country FROM users GROUP BY countryCount ORDER BY countryCount DESC");
while ($row = mysqli_fetch_array($query)) {
$count = $row['countryCount'];
$countries = $row['country'];
echo $count;
echo $countries;}
You need to add alias in query for COUNT(id) like below:-
$query = mysqli_query($con, "SELECT COUNT(id) as count, country FROM users GROUP BY country ORDER BY count DESC");
Now change while() loop code a bit:-
while ($row = mysqli_fetch_assoc($query)) { // _assoc for lighter array iteration
$countries = $row['country'];
$countries_count = $row['count'];// get count of each country
echo $countries.'--'.$countries_count ;// show country and it's count both
}
Is this what you are trying to do:-
$query = mysqli_query($con, "SELECT COUNT(id) AS total_country, country FROM users GROUP BY country ORDER BY id DESC");
while ( $row = mysqli_fetch_array( $query ) )
{
$countries = $row['country'];
$total_countries = $row['total_country'];
echo "<p>{$countries}</p>;
echo "<p>Total count: {$total_countries}</p>";
}
You're not assigning the variable.
Do this: $count = $row['COUNT']; and echo it. It should work

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories