How to count mutiple columns occurrencies in whole table - php

I have 5 columns that has data which are ids from other table
how do I count how many times each number appears in whole table, in all records.
I want to count paslauga1, paslauga2, paslauga3, paslauga4, paslauga5 data occurrencies.
For example there is 2 records that has 4 times 1 id 2 times 2 id 1 time id 3
So I want it to output
1 has appeared 4 times
2 has appeared 1 times
3 has appeared 2 times
and if more ids would be there 4,5,6 etc it would display them too.
I need to count this so I can use it on php code, maybe theres easier way to do so in php?

Use a simple loop in PHP that counts the numbers in an array.
$counts = array();
$result = $pdo->query("SELECT paslauga1, paslauga2, paslauga3, paslauga4, paslauga5 FROM yourTable");
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
foreach ($row as $col) {
if ($col !=== null) {
if (isset($counts[$col])) {
$counts[$col]++;
} else {
$counts[$col] = 1;
}
}
}
}
ksort($counts);
foreach ($counts as $id => $c) {
echo "$id has appeared $c times<br>";
}

SELECT paslauga, count(paslauga)
FROM (
SELECT paslauga1 as paslauga FROM yourTable
UNION ALL
SELECT paslauga2 as paslauga FROM yourTable
UNION ALL
SELECT paslauga3 as paslauga FROM yourTable
UNION ALL
SELECT paslauga4 as paslauga FROM yourTable
UNION ALL
SELECT paslauga5 as paslauga FROM yourTable
) T
GROUP BY paslauga

Related

basic - multiple categories from each item at foreach loop in PHP/mySQL

I've got table of categories. One item may have more than one category in table3. Three tables as below:
table1:
ID Item_id
1 1
2 2
3 3
4 4
5 5
table2:
ID Item_id Category
1 1 catId_1
2 2 catId_1
3 2 catId_2
4 3 catId_2
5 3 catId_3
6 3 catId_4
7 4 catId_2
8 5 catId_1
etc.
third table has only information of the name of category:
table3:
Category_id category_name
catId_1 cats
catId_2 dogs
catId_3 IT_managers
catId_4 Trump_lovers
I made a query to get PDO object of all items and be able to get categories from each one in php.
First query:
public function getCategories(){
$this->db->query('SELECT table1.*, table2.*, table3.*
FROM table1
INNER JOIN table2
ON table1.item_id = table2.item_id
INNER JOIN table3
ON table2.category=table3.category_id');
$results = $this->db->resultset();
return $results;}
$items = $offer_class -> getCategories();
How can I take all category name of each item in foreach loop?
I've tried this foreach loop, but it gives me only first category for each item:
<?php foreach($items as $item){
echo $item->category_name;
}
?>
You could split it up in 2 queries. - One query to find the needed in Table1,Table2 and an other query to find the category_name which matches the items.
In your foreach loop you'll then make a new foreach loop where you list the category_name data.
Regarding to your comment, you could do it like this:
<?php
$items = array("test", "test2",array("CAT1","CAT2","CAT3","CAT4"));
foreach($items as $t)
{
if(!is_array($t))
{
echo $t;
}
else
{
foreach($t as $ar)
{
echo $ar . " ";
}
}
}

id is not auto_increment and trying to get difference between rows mysql php

I am tring to get difference between frequency, so first row minus next rows,second row minus third row,etc. However, my id in the table like below. So I cannot use minus 1 to get the previous row, and I trying to use <, but not working,help, appreciate.
id game number frequency
1 a 3 4
5 c 3 5
6 a 3 7
9 a 2 9
13 a 2 19
My query is:
SELECT t1.frequency-t2.frequency as diff
FROM $table as t1
JOIN $table as t2 ON t2.id < t1.id
WHERE t1.game=a AND t1.num=2
A php solution for your requirement could be this:
$result = mysqli_query($connection, "SELECT * FROM $tableName");
$rows = mysqli_fetch_all ($result, MYSQLI_ASSOC);
for($i=0; i<count($rows)-1; i++){
echo ( abs($rows[$i]-$rows[$i+1) );
}

count total numbers of same item exist in database

assume I have a table that contain a column named post_id and it has the result like
1
1
1
2
2
3
1
1
I want to loop through all the records and count how many times they exist. What I could thought of is
by while loop
if(result[] = 1){$1++}, but the problem is the value of record is not fixed, it can be 9999..
I'd tried
while ($something= $item->fetch_array()) {
while($test[] = $something['post_id'] > 0){
//logic here
}
}
select post_id, count(*)
from table
group by post_id
This is something you can do in SQL. I believe it would be the following:
SELECT post_id, COUNT(*) FROM tablename GROUP BY post_id;
This will return, for each post_id in the table, that post_id and the count of rows with that post_id.
Have you try this.
Assume:
Table one
**Table one**
Column1
1
1
1
2
2
3
1
1
You can use this query to count it.
SELECT one.column1, COUNT(two.column1) FROM one as one, one as two;

MySQL greatest value in row?

I'm using MySQL with PHP. This is like my table: (I'm using 3 values, but there are more)
id | 1 | 2 | 3
---+---+---+----
1 | 3 |12 |-29
2 | 5 |8 |8
3 | 99|7 |NULL
I need to get the greatest value's column name in a certain row. It should get:
id | maxcol
---+-------
1 | 2
2 | 2
3 | 1
Are there any queries that will do this? I've been trying, but I can't get it to work right.
Are you looking for something like the GREATEST function? For example:
SELECT id, GREATEST(col1, col2, col3)
FROM tbl
WHERE ...
Combine it with a CASE statement to get column names:
SELECT id, CASE GREATEST(COALESCE(`1`, -2147483646), COALESCE(`2`, -2147483646), COALESCE(`3`, -2147483646))
WHEN `1` THEN 1
WHEN `2` THEN 2
WHEN `3` THEN 3
ELSE 0
END AS maxcol
FROM tbl
WHERE ...
It's not pretty. You'd do better to follow Bill Karwin's suggestion and normalize, or simply take care of this in PHP.
function findcol($cmp, $arr, $cols=Null) {
if (is_null($cols)) {
$cols = array_keys($arr);
}
$name = array_shift($cols);
foreach ($cols as $col) {
if (call_user_func($cmp, $arr[$name], $arr[$col])) {
$name = $col;
}
}
return $name;
}
function maxcol($arr, $cols=Null) {
return findcol(create_function('$a, $b', 'return $a < $b;'), $arr, $cols);
}
This is a great example of the way normalization helps make query design easier. In First Normal Form, you would create another table so all the values would be in one column, on separate rows.
Since you have used repeating groups to store your values across three columns, you can find the column with the greatest value this way:
SELECT id, IF(col1>col2 AND col1>col3, 'col1', IF(col2>col3, 'col2', 'col3'))
AS column_with_greatest_value
FROM mytable;
The short answer is that there is no simple means to do this via a query. You would need to transpose your data and then determine the largest value that way. So something like:
Select Id, ColumnName, Value
From (
Select '1' As ColumnName, Id, [1] As Value
From Table
Union All
Select '2', Id, [2]
From Table
Union All
Select '3', Id, [3]
From Table
) As Z
Where Exists(
Select 1
From (
Select '1' As ColumnName, Id, [1] As Value
From Table
Union All
Select '2', Id, [2]
From Table
Union All
Select '3', Id, [3]
From Table
) As Z2
Where Z2.Id = Z.Id
Group By Z2.Id
Having Max(Z2.Value) = Z.Value
)
Order By Id
This solution depends on a fixed set of columns where you basically name the columns in the UNION ALL queries. In addition, if you have two columns with identical values for the same Id, you will get duplicate rows.
This query will return the max value regardless of NULLs
SELECT MAX(value)
FROM
(SELECT 1 column_no, col1 value
FROM anotherunamedtable
UNION ALL
SELECT 2, col2
FROM anotherunamedtable
UNION ALL
SELECT 3, col3
FROM anotherunamedtable) t
If you really need the column number then
SELECT id,
(SELECT column_no
FROM
(SELECT 1 column_no, col1 value
FROM anotherunamedtable
WHERE id = t.id
UNION ALL
SELECT 2, col2
FROM anotherunamedtable
WHERE id = t.id
UNION ALL
SELECT 3, col3
FROM anotherunamedtable
WHERE id = t.id) s
ORDER BY max_value DESC
LIMIT 1)) as column_no
FROM anotherunamedtable t
But I think that the last query might perform exceptionally horrible.
(Queries are untested)
In the php side, you could do something like this:
foreach ($rows as $key => $row) {
$bestCol = $best = -99999;
foreach ($row as $col => $value) {
if ($col == 'id') continue; // skip ID column
if ($value > $best) {
$bestcol = $col;
$best = $value;
}
}
$rows[$key]['best'] = $bestCol;
}
Or something similar...
Forests and trees, here's a trivial and fastest solution (providing I didn't fumble); the expression simply looks for the largest column in the row
SELECT id,
CASE COALESCE(col1, -2147483648) >= COALESCE(col2, -2147483648)
WHEN
CASE COALESCE(col2, -2147483648) >= COALESCE(col3, -2147483648)
WHEN true THEN 1
ELSE
CASE COALESCE(col1, -2147483648) >= COALESCE(col3, -2147483648)
WHEN true THEN 1
ELSE 3
END
END
ELSE
CASE COALESCE(col2, -2147483648) >= COALESCE(col3, -2147483648)
WHEN true 2
ELSE 3
END
END
FROM table t
a version with IF() would maybe be more readable, but the above should perform a bit better
To deal with NULLS an INT value with minimum of -2147483648 was assumed, the expression could be rewritten to deal explicitly with nulls but would have to branch into 8 different cases and is left as an exercise for the OP.

PHP trim row results?

Hello I'm getting results in format
location1 2 4
location2 3 2
location3 0 0
location1 1 0
How can I trim results so that row returning 0 and 0 is not displayed ? thank you
.................
Here is Mysql query, I don't know how to trim it from MySQL so I thought using PHP ..
SELECT hotelas.name, hotelas.address, hotelas.city, hotelas.country, hotelas.hotel_id
AS hotelid,
COUNT( DISTINCT apart.apartman_id ) AS number_of_free_ap,
COUNT( DISTINCT room.apartman_id ) AS num_of_free_rooms
FROM hotel AS hotelas
LEFT JOIN apartman AS apart ON ( apart.apartman_hotel = hotelas.hotel_id
AND apart.occupied =0
AND apart.what =1 )
LEFT JOIN apartman AS room ON ( room.apartman_hotel = hotelas.hotel_id
AND room.occupied =0
AND room.what =0 )
GROUP BY hotelas.hotel_id
TABLE field what, 0 - for room, 1 - apartment
So I get a few columns among which the most important ones are count columns , free rooms and free apartments. So I have a test hotel which is full 0 rooms and 0 apartments and I want is removed from this list where all other hotels have at least one room or one apartment available.
if you are querying you database to get this information and you can change the query, that would be the best place for it.
SELECT *
FROM myTable
WHERE
firstColumn != 0
OR
secondColumn != 0
If you are getting this in PHP from some other source (CSV or something), or you don't have control over the query, use array_filter():
// i'm assuming each line in your example is an array of values
$myArray = array_filter($myArray, 'noDoubleZeroes');
function noDoubleZeroes($line) {
return $line[1] != 0 || $line[2] != 0;
}
select * from table
where column1 !=0
or column2 !=0
That's how you can trim it in MySQL.
OTOH, if you have an array such as this ( you will usually get this after you query from a db)
array(array('location1', 2, 4), array('location2', 3, 2))
Then you need to loop over the array and do the manual filtering:
$newarrs=array();
foreach($arrs as $values)
{
if($values[1]!=0 || $values[2]!=0)
$newarrs[]=$values;
}
return $newarrs;
If i understood you correctly this should help
$columns = explode($resultLine, " ");
$whatYouWant = $columns[0];

Categories