Retrieve total amounts of rows containing strings - php

I have a table in MySQL, with 5(sort of) possible values in the column 'type'... I say sort of because the data type is 'set' and 1 type has a subcategory... It's for a type of property, so the possible types are retail, office, hospitality, industrial, residential(multi family), residential(single family).
I'm attempting to paginate the results and I need to know how many pages each should have. So I need a query that tells me how many of each type are in the table, the user can select residential as a category, or single, multi as subcategories.
I can't figure out how to do a query that tells me how many of each there are, or how to retrieve those numbers as variables I can use to divide be items per page.
id | type
-----------------------
1 | office
2 | residential,single
3 | industrial
4 | residential,multi
5 | retail
6 | office
7 | hospitality
8 | residential,single
etc....
so if this was the data, I would need to get:
$office = 2
$residential = 3
$industrial = 1
$single = 2
etc...

Use array_count_values() function
Check the link http://php.net/manual/en/function.array-count-values.php
From their website http://php.net/manual/en/function.array-count-values.php;
and Try this code
<?php
$query= // Run your select query.
$result= mysqli_query($link, $query);
//Run the while loop
while($row= mysqli_fetch_array($result))
{
$array[]=$row['Column_Name'];//Store the result in array
}
$count = array_count_values($array);//Use array count
print_r($count);//See the result
Or if you see The out put the way you want
Run Foreach loop on the $count array
foreach($count as $key => $value) {
//Get the out put From new array
echo $value .' '. $key.'<br/>' ;
}

A count and group by should do the trick;
SELECT id, type, COUNT(*) as count
FROM mytable
GROUP By id

Related

DB query foreach rows that are equal calculate the values from other column

I have a db table with in one column the province name of a country. And in another column of the same table the amount of people living in this province.
There are many more columns in the table and also postal codes. As the postal codes are unique you can see in this table that the province column has a lot of equals.
Sample data:
id | postal code | province | amount
1 | 1001 | Amsterdam | 500
2 | 1002 | Amsterdam | 1500
3 | 1003 | Amsterdam | 250
In a form that I am creating I need to create checkboxes for each province and the value of the checkbox needs to be the amount value.
For this I use the below code. (This code is inserted into a Form Builder called RS Form so it might look a bit strange but please believe me it is working.
The form builder creates the checkboxes it only needs the 'grab from db' part not the echo checkboxes part).
<?php
//<code>
$db =& JFactory::getDBO();
$db->setQuery("SELECT province, amount FROM `#_the_correct_table`");
$results = $db->loadObjectList();
foreach ($results as $result) {
$value = $result->amount;
$label = $result->province;
$items[] = $value.'|'.$label;
}
// Multiple values are separated by new lines, so we need to do this now
$items = implode("\n", $items);
// Now we need to return the value to the field
return $items;
//</code>
?>
The above code is currently generating about 4000+ checkboxes with lots of duplicates, so I have been looking into outputting each province only once and making it calculate the amounts. So with the above example I would get 1 checkbox Amsterdam = 2250.
I am struggling with getting this code which should do this combining to work with the code I already have.
$sum = 0;
foreach($quantity as $value) $sum = $sum + $value;
echo $sum;
Can someone please show me how to combine it?
No need to do it using PHP. This is a standard SQL task.
You need to perform 2 operations:
group your records by province name (Amsterdam for example)
sum amount values for grouped rows
Just change your SQL query to something like:
SELECT SUM(amount) as province_sum
FROM tbl
GROUP BY province
Here is the SQL fiddle: http://sqlfiddle.com/#!9/9cbf9d/1

How to add not existing record and return it with zero value in Mysqli

QUERY:
SELECT month(date_created), count(a.ticket_num)
FROM ticket as a
LEFT JOIN user_management as b on b.engineer_id = a.ticket_engineer
WHERE b.tl_id = 'sample_id'
AND year(date_created) = '2019'
GROUP BY extract(year from date_created), extract(month from date_created)
SAMPLE OUTPUT:
month | ticket_num
----------------------
2 | 12
4 | 24
6 | 78
EXPECTED SAMPLE OUTPUT:
month | ticket_num
----------------------
1 | 0
2 | 12
3 | 0
4 | 24
5 | 0
6 | 78
As you can see the above expected output, i'm trying to place all existing month in the first column and set all the count to zero if not existed in the second column. As of now, i only have the query for sorting the ticket count by month that is existed when the ticket is created.
There are different approaches to this problem. One is pure SQL for example.
But I would say a PHP based solution is simpler. Basically you need to get your data into array, then create a loop that outputs the desired months order, and have a condition that sees whether we have a corresponding row in our array and outputs ether the actual data or a zero accordingly.
The only tricky part is to have such an array that would let us check the data availability. For this we have to index it with month numbers. Not a big deal actually
$sql = "SELECT month(date_created), count(a.ticket_num) ...";
$res = $mysqli($sql);
$data = [];
while($row = mysqli_fetch_row($res)) {
$data[$row[0]] = $row[1];
}
Now $data is an array indexed by the month number. The rest is a primitive loop
foreach (range(1,12) as $month) {
echo $data[$month] ?: 0;
}
On a side note I would like to advertise using PDO as opposed to mysqli for your database interactions as this case clearly displays the superiority of the former. Using PDO we can get the indexed array right away, without an explicit loop, thanks to a special fetch mode:
$sql = "SELECT month(date_created), count(a.ticket_num) ...";
$data = $data = $pdo->query($sql)->fetchAll(PDO::FETCH_KEY_PAIR);
That's all!

Select Random yet distinct rows from table - MySQL

I have a table with various categories, and multiple entries for each category.
Word | Category
------------------
Apple | Food
Orange | Food
Grapes | Food
Mango | Food
I wish to retrieve 3 random rows for the category 'food', for which I run the following query,
$query = "SELECT * FROM table WHERE category='food' ORDER BY RAND() LIMIT 3"
$fetch_row = mysqli_query($db_connect, $query);
while ($row = mysqli_fetch_array($fetch_row)) {
array_push($words, $row['word']);
}
However, when I print the contents of the array $words, they tend to repeat sometimes (not on all runs), for example;
Apple, Orange, Apple
i.e. Its not always unique. I want to select random, yet unique words for a given category. What am I doing wrong? I've tried going through other related answers, but I keep messing something up. I've also tried the following query;
SELECT * FROM table WHERE category='food' GROUP BY category ORDER BY RAND() LIMIT 3
But this still gives repetitions occasionally.
Since word column have same values, do GROUP BY word like below:-
SELECT * FROM table WHERE category='food' GROUP BY word LIMIT 3

A better way to display this data from MySql using php

I currently have data like this in a table:
id | type
------------
1 | 1
2 | 1
3 | 2
4 | 2
5 | 3
6 | 3
6 | 3
I need to display data like this:
Type 1
--All type ones go here
Type 2
-- All type twos go here
Type 3
All type threes go here
The way I do it right now is by using two separate sql statements and loops.
select distinct type as type from table
while()
{
select type from table where type = type;
while()
{
}
}
Is there a better way to do this and get the results I want, or is using two loops the only way?
Change your query so that you are using ORDER BY type ASC.
Loop through the results, build an associative array where the key is the type, and the values are the ids.
Now you only have one loop, and ids can be accessed by their type from the associative array. It should be trivial to loop through the array by the key, and then show all the ids for that key.
Just select everything, and check whenever you hit a new type. This allows you to list everything out in O(n) time using only one query.
$result = mysql_query('SELECT id, type FROM table ORDER BY type ASC');
$type = 0;
while ($row = mysql_fetch_assoc($result) {
if ($type != $row['type']) {
// New type found
$type = $row['type'];
echo "Type " + $row['type'] + "\n";
}
echo "-- " + $row['id'] + "\n";
}
This would give you an output like this
Type 1
-- 1
-- 2
Type 2
-- 3
-- 4
Type 3
-- 5
-- 6
-- 7
Use GROUP_CONCAT() with GROUP BY:
SELECT
`type`,
GROUP_CONCAT(`id` SEPARATOR ',') as `ids`
FROM
`table`
GROUP BY
`type`
ORDER BY
`type`;
In each cycle iteration, $row['ids'] might be explode()d, like:
<?php
while($row = $result->fetch_assoc()){
$ids = explode(',', $row['ids']);
echo 'Type ', $row['type'], PHP_EOL;
if(empty($ids))continue;
foreach($ids as $id){
echo $id, ' ';
}
echo PHP_EOL;
}
?>

Collect values from DB, group matching values, count it and use in other code

This is what my customers_basket table looks like:
customers_id | products_id | basket_quantity
3 | 56:3121fefbe6043d6fc12e3b3de2c8fc38 | 3
3 | 56:fb4c9278fcfe6225b58c06711a7e62ef | 1
3 | 56:8e334fce09556108f5416e27154b6c27 | 1
3 | 52:f3b9f38e4ddd18035bc04cd264b0f052 | 1
This is the query I'm using:
$products_in_cart_query = "SELECT products_id FROM customers_basket WHERE customers_id = " . $_SESSION['customer_id'] ."";
$products_in_cart = $db->Execute($products_in_cart_query);
$products_in_cart_model = $products_in_cart->fields['products_id'];
$products_in_cart_model = substr($products_in_cart_model, 0, strpos($products_in_cart_model, ":"));
The end result I get is 56,56,56,52
First of all, how do I use the first line's quantity field? I'd need to list that products_id 3 times since quantity is 3. Therefore, the end result needs to be: 56,56,56,56,56,52
or, for easier understanding (56,56,56),56,56,52
And second, how do I count how many same values I have? In this case, I have 5x56 and 1x52. I need to use those counts in my further calculation.
EDIT: further calculations explained
I need to know how many of each product_id I have and then run something like this:
foreach(product_id) {
$shipping_cost += FIXED_VALUE * basket_qty;
}
To get the basket quantity, you have to select it. It would be best if the first portion of the product ID was stored in a separate column, rather than having to do messy operations like substringing.
Query 1: 2-character codes and corresponding quantities
SELECT SUBSTR(products_id, 1, 2) AS product_code, basket_quantity
FROM Customers_Basket
WHERE customers_id = 3;
Query 2: 2-character codes and summed quantities
SELECT product_code, SUM(basket_quantity) AS total_quantity
FROM (SELECT SUBSTR(products_id, 1, 2) AS product_code, basket_quantity
FROM Customers_Basket
WHERE customers_id = 3
)
GROUP BY product_code;
If you really, really, really desperately want 3 rows of data for the product ID 56:3121fefbe6043d6fc12e3b3de2c8fc38, then you have to know ways to generate rows. They're truly painful in the absence of convenient SQL support (so much so, that you'd do better to select a row in PHP with the quantity and then generate the appropriate number of rows in your array in the client-side (PHP) code). I'm going to assume that some variation on these queries will get you the information you want.

Categories