Group items on SQL - php

Can someone help me with this:
I have a mySQL database and I would like to do a simple search amoung the items, here is an example of my database named "orders"
id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
How can I group by duplicated data and display it like this:
<select name="costumer">
<option>Hansen</option>
<option>Nilsen</option>
<option>Jensen</option>
</select>
I know it is the GROUP BY command, but dont know how to display it on a PHP script file

Try this:
$dbconn = new mysqli();
$dbconn->connect("localhost","root","","test");
if($dbconn->connect_errno ){
echo "Connection Failed";
}
$query = "SELECT DISTINCT Customer FROM `Orders`";
$result = $dbconn->query($query);
echo "<select name=\"costumer\">";
while($row = $result->fetch_array())
{
echo "<option>".$row["Customer"]."</option>";
}
echo "</select>";

you can use DISTINCT on this since you only need to have 1 column,
SELECT DISTINCT Customer FROM `Orders`

Related

php mysqli query select

I have 3 different tables
table 1 keep general scores over the year
table 2 and 3 is event specific
only common field in all 3 is a member ID
I need to select 5 top score results for each member from table1 combine them with 1 specific result from table 2 and 3
I managed to get everything together in a temp table, but cnt get the output the way I need it
example what i have and need.
Original code
$prevQuery = "SELECT distinct member_id FROM scores";
$prevResult = $conn->query($prevQuery);
while($row = $prevResult->fetch_assoc()) {
$scores=("SELECT member_id,event_id,event_date,event_score FROM scores where member_id = ".$id." ORDER BY event_score DESC LIMIT 5");
Query:
select * from temp_table order by mem_id asc
PHP:
you can simple do your expected result in your application like this
<?php
$result = array(array('mem_id'=>1,'location'=>'A','date'=>'20/05/2017','score'=>100),array('mem_id'=>1,'location'=>'B','date'=>'21/05/2017','score'=>103),array('mem_id'=>1,'location'=>'C','date'=>'22/05/2017','score'=>106),array('mem_id'=>1,'location'=>'C','date'=>'23/05/2017','score'=>108),
array('mem_id'=>2,'location'=>'A','date'=>'20/05/2017','score'=>105),array('mem_id'=>2,'location'=>'B','date'=>'21/05/2017','score'=>109),array('mem_id'=>2,'location'=>'C','date'=>'22/05/2017','score'=>111),array('mem_id'=>2,'location'=>'C','date'=>'23/05/2017','score'=>110));
$new_result=array();
foreach($result as $key=>$row)
{
$new_result[$row['mem_id']][]=$row;
}
echo "<table border='1px'>";
echo "<thead><tr><th>S.No</th><th>date</th><th>score1</th><th>date</th><th>score2</th><th>date</th><th>score3</th><th>date</th><th>score4</th></tr>";
echo "<tbody>";
foreach($new_result as $key=>$row)
{
echo "<tr><td>".$key."</td>";
foreach($row as $key1=>$row1)
{
echo "<td>".$row1['date']."</td>";
echo "<td>".$row1['score']."</td>";
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
OUTPUT :
S.No date score1 date score2 date score3 date score4
1 20/05/2017 100 21/05/2017 103 22/05/2017 106 23/05/2017 108
2 20/05/2017 105 21/05/2017 109 22/05/2017 111 23/05/2017 110

SUM of columns while grouping by other column

So this is the structure of my MySQL table that I wanna work this out with:
ID type category_id amount
12 Expense 3 963.39
13 Expense 5 1200.50
14 Expense 3 444.12
15 Expense 5 1137.56
..............................
Desired output:
1407,41 (for category_id = 3)
2338,06 (for category_id = 5)
....... (and for other category_id)
What I get now:
1407,41 (only for category_id = 3)
My query does not add or display the sum of other category_id.
This is the query I am trying:
$query = "SELECT SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
$expense_count = mysqli_fetch_array($expense_query);
echo $expense_count[0];
Been stuck with this for the last couple of days. Any help is very much appreciated. Thank you!
You're only calling mysqli_fetch_array() once. You need to call it in a loop to get all the totals. You should also include the category ID in the SELECT list.
$query = "SELECT category_id, SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($expense_query)) {
echo "{$row['TotalAmount']} (for category_id = {$row['category_id']}<br>\n";
}
The query here works. It's just that you only select the first result from the $expense_count variable. $expense_count[1] will return the second category listed, $expense_count[2 will return the third one, ect...
Try echo implode(" <br>", $expense_count);
Have a nice day.

How can I show all data under specific category using sql query?

well, I have 2 Mysql table which structure is bellow :
Table Jobs
job_id---job_cat_id---job_title---job_description---job_data----is_active
=========================================================================
1 1 title 1 description 1 2016-05-06 1
2 2 title 2 description 2 2016-05-06 0
3 2 title 3 description 3 2016-05-06 1
Table job_details
job_cat_id---job_cat_name
=========================
1 cat name 1
2 cat name 2
3 cat name 3
Now I want to show all jobs under each category from jobs table. E.g
What I need to show :
Job Category 1
1. job 1 from category 1
2. Job 2 from category 1
Job Category 2
1. Job 3 from category 2
So to do this I am using following sql query but can't get the correct result :
$get_job = mysqli_query($conn, "SELECT jobs.job_id, jobs.job_title, job_category.job_cat_name FROM jobs LEFT JOIN job_category ON job_category.job_cat_id = jobs.job_cat_id WHERE jobs.is_active = '1' ");
while($result = mysqli_fetch_array($get_job) ) {
$job_id = (int) $result['job_id'];
$job_title = htmlspecialchars($result['job_title']);
$job_category = htmlspecialchars($result['job_cat_name']);
echo "<h4>$job_category</h4>";
echo "<p>$job_title</p>";
}
Now, It's showing me all category with all jobs but I want to show all jobs under each category.
What is showing now :
Job Category 1
1. job 1 from category 1
Job Category 1
1. Job 2 from category 1
Job Category 2
1. Job 3 from category 2
First we have to remember that the result from a SELECT query is a newly generated table. It is not a multi dimensional array. If it were a multidimensional array, then you could get away with printing the job category at the beginning of each new array which could be grouping up all the jobs in a single category, however since this is not the type of result obtained by the SQL SELECT QUERY, you are printing the job category after each line:
echo "<h4>$job_category</h4>";
echo "<p>$job_title</p>";
Solution:
A solution to your problem would be to first use the ORBER BY ASC in your sql query:
$get_job = mysqli_query($conn, "SELECT jobs.job_id, jobs.job_title, job_category.job_cat_name FROM jobs LEFT JOIN job_category ON job_category.job_cat_id = jobs.job_cat_id WHERE jobs.is_active = '1' ORDER BY job_cat_id ASC");
From there, you know that the jobs in each category should at least be grouped up next to each other (from lowest to highest like 1,1,1,1,2,2,3,3,3). What you can now do is have a conditional print the $job_category if AND ONLY IF it hasn't been printed already previously.
Change this line:
echo "<h4>$job_category</h4>";
into this line:
if ($previous_print != $job_category)
{
echo "<h4>$job_category</h4>";
$previous_print = $job_category;
}
Let me know if it works now.
Another solution may be if you just run one query using group by job_cat_id and then inside loop write another query to get desired result with where clause job_cat_id .
You need to do 2 queries here. Here's an exmaple code, might need some tweaks acording to your table column names:
<?php
$query = "SELECT `job_cat_id`, `job_cat_name`, COUNT(`jobs`.`id`) as `jobs`
FROM `job_category`
GROUP BY `job_cat_id`";
$get_cat = mysqli_query($conn, $query);
$cats = [];
while($result = mysqli_fetch_array($get_cat) ) {
$result['jobs'] = [];
$cats[$result['job_cat_id']] = $result;
}
$get_job = mysqli_query($conn, "SELECT jobs.job_id, jobs.job_title, jobs.job_cat_id FROM jobs WHERE jobs.is_active = '1' AND `job_cat_id` IN (" . implode(',', array_keys($cats)) . ")");
while($result = mysqli_fetch_array($get_job) ) {
$cats[$result['job_cat_id']][] = $result;
}
foreach ($cats as $cat) {
$job_category = htmlspecialchars($cat['job_cat_name']);
echo "<h4>$job_category</h4>";
foreach ($cat['jobs'] as $job) {
$job_title = htmlspecialchars($job['job_title']);
echo "<p>$job_title</p>";
}
}

Select Query array and array from POST not lining up

when the user inputs the form, I have know way of knowing what the user can input because there are hundreds of options in the database.
I am using a foreach loop to get the categories and the cost from the posted field that they chose example:
<td><?php foreach($pcategories as $value){echo "$value <br>";}?></td>
$qty $pcategories $cost $Rate
1 Bicycles 100 45
7 Auto Parts 200 60
5 Alarm Sys 300 35
The rate is then being selected from the query below
<?php $connection = mysqli_connect("localhost","root","","customs") or die("Error " . mysqli_error($connection));
$sql = "SELECT `categories`, `rate`, `elevy` FROM `lt_products` WHERE `categories` IN ('".implode("','",$pcategories)."')";
$result = mysqli_query($connection, $sql)or die(mysql_error());
while($row = mysqli_fetch_assoc($result)) {?>
<?php echo $row["rate"]; ?> <br>
<?php } ?>
Here's the problem the query is pulling the correct rates base on the categories the user in putted
but the rates are not coming out to match the order of the categories the user input.
Above rates should actually look like this below but instead that is what im getting above
$qty $pcategories $cost $Rate
1 Bicycles 100 35
7 Auto Parts 200 60
5 Alarm Sys 300 45
The select query seems to be coming out in alphabetical order based on the pcategories field in the table.
I dont know whats the best way to fix this so that the actual rate matches the categories the user chose.
Any help would be great thank you
Use the FIELD function to order the results based on their position in $pcategories
$sql = "SELECT `categories`, `rate`, `elevy`
FROM `lt_products`
WHERE `categories` IN ('".implode("','",$pcategories)."')
ORDER BY FIELD(categories, '".implode("','",$pcategories)."')";

MySQL Count number of Items with Group By

We have these two fields in our MySQL database:
in_model , in_color
And we are trying to count the total of model (in_model field), which has the same color (in_color field) in PHP with MySQL as backend database. We tried using the count() function, together with the group by. But it would seem we don't have achieve a desired result
This is our MySQL database:
$query = "SELECT in_model, COUNT(in_color) FROM in_newunit GROUP BY in_color,in_model";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)) {
echo "There are ". $row['COUNT(in_color)'] ."
". $row['in_model'] ." items.";
echo "<br />";
}
This is the output we are receiving
There are 1 C2I items.
There are 2 try items.
There are 2 try items.
There are 4 C2I items.
This is what we are trying to achieve
We are trying to have the color appear in the echo
There are 1 C2I Black items.
There are 2 try White items.
There are 2 try Black items.
There are 4 C2I White items.
I think this is straight enough. Try this.
$query = "SELECT in_model, in_color, count(*) AS counter FROM in_newunit GROUP BY in_model, in_color";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)) {
echo "There are ". $row['counter'] ." ". $row['in_model'] ." ".$row['in_color']." items.";
echo "<br />";
}
The query is actually the other way around:
SELECT in_color, count(*) FROM in_newunit
GROUP BY in_color
And you have actually said it yourself:
we are trying to count the total of model (in_model field), which has the same color (in_color field)
"count the total of model" > count(*)
"which has the same color" > for every color the previous count, which is a group by in_color
Also note that if you do count(in_model) you won't be counting values with in_model as null. If you do count(*) you will be counting the null values too. Up to you.
Update
So you want the amount of elements there are by (model, color) pair. Then this is the query:
SELECT in_model, in_color, count(*) FROM in_newunit
GROUP BY in_model, in_color
Eg:
model1 | black | 2
model1 | white | 1
model2 | black | 5
model3 | white | 4

Categories