PHP Output Multiple SQL Query Number of Results - php

I have five different SQL queries that I would like to return back the number of rows returned in a list. Basically I have a MySQL database and would like to show some statistics on how many records we have and how many of them have had information added. Examples of the queries are...
SELECT * FROM `ibf_ccs_custom_database_1`
SELECT * FROM `ibf_ccs_custom_database_2`
SELECT * FROM `ibf_ccs_custom_database_3`
SELECT * FROM `ibf_ccs_custom_database_1` WHERE `field_30` <> ''
SELECT * FROM `ibf_ccs_custom_database_2` WHERE `field_60` <> ''
Which should return back the following output
Total Records Database 1: 12,548
Total Records Database 2: 9,835
Total Records Database 3: 5,916
Filled Out Records in Database 1: 567
Filled Out Records in Database 2: 681
Any help is much appreciated!

It would be much more efficient to have the database prepare a result containing just the count of rows, rather than preparing a complete set of ten thousand plus rows.
For example, to have the database return the results as shown in the question:
SELECT CONCAT('Total Records Database 1: ',FORMAT(COUNT(1),0) AS txt
FROM `ibf_ccs_custom_database_1`
UNION ALL
SELECT CONCAT('Total Records Database 2: ',FORMAT(COUNT(1),0)
FROM `ibf_ccs_custom_database_2`
UNION ALL
SELECT CONCAT('Total Records Database 3: ',FORMAT(COUNT(1),0)
FROM `ibf_ccs_custom_database_3`
UNION ALL
SELECT CONCAT('Filled Out Records in Database 1: ',FORMAT(COUNT(1),0)
FROM `ibf_ccs_custom_database_1` WHERE `field_30` <> ''
UNION ALL
SELECT CONCAT('Filled Out Records in Database 1: ',FORMAT(COUNT(1),0)
FROM `ibf_ccs_custom_database_2` WHERE `field_60` <> ''
If you want to handle the labeling and formatting in the application layer, you could just return the counts in a single row:
SELECT t1.cnt AS t1_cnt
, t2.cnt AS t2_cnt
, t3.cnt AS t3_cnt
, f1.cnt AS f1_cnt
, f2.cnt AS f2_cnt
FROM ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_1` ) t1
JOIN ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_2` ) t2
JOIN ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_3` ) t3
JOIN ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_1` WHERE `field_30` <> '' ) f1
JOIN ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_1` WHERE `field_60` <> '' ) f2

I'd just build an array with key => value pairs for your row counts. Something like this:
$db_queries = array();
$query = "SELECT * FROM ibf_ccs_custom_database_1";
$res = $mysqli->query($query);
$db_queries['q1'] = $res->num_rows;
$query = "SELECT * FROM ibf_ccs_custom_database_2";
$res = $mysqli->query($query);
$db_queries['q2'] = $res->num_rows;
$query = "SELECT * FROM ibf_ccs_custom_database_3";
$res = $mysqli->query($query);
$db_queries['q3'] = $res->num_rows;
$query = "SELECT * FROM ibf_ccs_custom_database_1 WHERE field_30 <> ''";
$res = $mysqli->query($query);
$db_queries['q4'] = $res->num_rows;
$query = "SELECT * FROM ibf_ccs_custom_database_2 WHERE field_60 <> ''";
$res = $mysqli->query($query);
$db_queries['q5'] = $res->num_rows;
foreach($db_queries as $k => $v){
echo $k, " contains ", $v, " rows.";
}

Related

using count to select total of rows from two table

I have two MySQL tables,
student = 150 (total no of rows which represent total no of student)
employer= 230 (total no of rows which represent total no of employer)
FULL CODE
<?php echo mysqli_num_rows($studempl); ?>
$conn = new mysqli ('localhost', 'root', '', 'dashboard');
$studempl = $conn ->query ("SELECT (SELECT COUNT(*) FROM student) + (SELECT COUNT(*) FROM employer) FROM dual");
$tot_studempl = mysqli_num_rows($studempl);
Result: 1
How can i fix this?
I tried to use
SELECT 'student' AS stdID, COUNT(*) FROM student
UNION
SELECT 'employer' AS emplID, COUNT(*) FROM employer*
It displays the result = 2,
I also tried to use:
SELECT (SELECT COUNT(*) FROM student) AS count1,(SELECT COUNT(*) FROM employer) AS count2 FROM dual*
It displays the result = 1,
I think I might have wrong in my code,
how can I get total from student and from employer so i can view the data and display in piechart?
150, 230
I did the sum of the two tables in MySQL with a query like this
SELECT ( (SELECT COUNT(*) FROM scheme.student) +
(SELECT COUNT(*) FROM scheme.employer)
) AS 'Column' ;
In my case, i used the same table 2 times and that table has 280 rows (280 x 2 = 560).
Hope this help you
You're second query should work.
SELECT (SELECT COUNT(*) FROM student) AS count1,(SELECT COUNT(*)
FROM employer) AS count2 FROM dual* <-- make sure you remove (*)
// so it should be like this
SELECT (SELECT COUNT(*) FROM student) AS count1,(SELECT COUNT(*)
FROM employer) AS count2 FROM dual
Then you just have to fetch the array to display the results
$sql = "SELECT (SELECT COUNT(*) FROM playlists) AS count1,(SELECT COUNT(*) FROM artists) AS count2 FROM dual";
if ($result=mysqli_query($con,$sql))
{
$row = mysqli_fetch_array($result);
var_dump($row); // just checking the raw array...
echo "<br />";
echo $row[0]. ", ". $row[1]; // got your results -> 150, 230
}
mysqli_close($con);
Also, you're first query works if you replace the + to , like this
$sql = "SELECT (SELECT COUNT(*) FROM students), (SELECT COUNT(*) FROM employer) FROM dual";

Find duplicate value accross multiple column within same row in Mysql

Please help find duplicate entries in multiple columns of same row in MySQL:
If you want to find the records that have duplicates in columns you can use this query:
SELECT T1.* FROM tbl T1
JOIN
(SELECT id
FROM (
SELECT id, sample1 AS n from tbl
UNION ALL
SELECT id, sample2 AS n from tbl
UNION ALL
SELECT id, sample3 AS n from tbl
) AS X
GROUP BY id, n
HAVING COUNT(*) > 1
) T2
ON T1.id = T2.id;
You can also test it Here
I am not sure with MySql,
But in PHP below example will use.
Example
$query = "select * from table_name";
$result = mysqli_query($query);
while ($row = mysqli_fetch_array($result)) {
if ($row['sample1'] == $row['sample2']) {
// This row duplicate
}
else {
// This row not duplicate
}
}
SELECT Sample1, COUNT(*) C FROM tablename GROUP BY Sample1 HAVING C > 1;
Finding duplicate values in MySQL
MySQL select records for duplicates using multiple columns

SQL in php force WHERE IN to find more than one time the same id

I am trying to to do a cart where the products have customizations... To avoid lot of queries in the data base I have tried to save the results in an array after the query. The query looks like this:
$sql = 'SELECT *
FROM cc_restaurants_menu
WHERE menu_id
IN ("7","50","50")
ORDER BY FIELD (menu_id,"7","50","50")';
$result = $conn->query($sql);
if($result->rowCount() > 0) {
while($row = $result->fetch()) {
$names[] = $row['menu_product'] .'<br>';
}
}
But the problem with this is that the query avoid the repeated ids. (I need repeated ids because the people can add the product more than one time).
Is there anyway to get the repeated ids more than one time?
The only idea I have is do something like (if the ids are in an array) :
foreach($ids as $d) {
//query here the database based in each id
}
thanks in advance
Think you might need one query for each menu_id, and use UNION ALL to join the results together.
Something like this:-
SELECT *
FROM cc_restaurants_menu
WHERE menu_id = "7"
UNION ALL
SELECT *
FROM cc_restaurants_menu
WHERE menu_id = "50"
UNION ALL
SELECT *
FROM cc_restaurants_menu
WHERE menu_id = "50"
ORDER BY FIELD (menu_id,"7","50","50")
Or build up the required menu ids in a sub query which you then join against the main table.
SELECT cc_restaurants_menu.*
FROM cc_restaurants_menu
INNER JOIN
(
SELECT 7 AS a_menu_id UNION ALL SELECT 50 UNION ALL SELECT 50
) sub0
ON cc_restaurants_menu.menu_id = sub0.a_menu_id
ORDER BY FIELD (cc_restaurants_menu.menu_id,"7","50","50")
Generating the first query with implode would be done something like this:-
$sql = "SELECT * FROM cc_restaurants_menu WHERE menu_id = '".implode("' UNION ALL SELECT * FROM cc_restaurants_menu WHERE menu_id = '", id_array)."' ORDER BY FIELD (menu_id,'".implode("','", id_array)."')";
and generating the 2nd query with implode would be done something like this:-
$sql = "SELECT cc_restaurants_menu.* FROM cc_restaurants_menu INNER JOIN (SELECT ".implode(" AS a_menu_id UNION ALL SELECT ", id_array) AS a_menu_id ) sub0 ON cc_restaurants_menu.menu_id = sub0.a_menu_id ORDER BY FIELD (cc_restaurants_menu.menu_id,".implode(",", id_array).")";

Speeding up SQL loop

I have a nested loop in my PHP code that is taking a long time and wondered of there was a way to speed this up:
$sql = "SELECT * FROM table_1";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result)){
$sql2 = "
SELECT count(*)
FROM user_modules
WHERE
begin_ymdhi >= ".$date_from." AND
begin_ymdhi <= ".$date_to." AND
(
completed_ymdhi IS NULL OR
completed_ymdhi = ''
) AND
user_id = ".$row['user_id']." AND
task_id = ".$row['task_id']." AND
module_discon = 'N'
";
}
The outer query gets 1000 rows, the inner has to count across 10,000 rows - the run-time is around 115 seconds ! Is there any way to improve this method, either using a different technique or combined SQL query?
Don't use nested queries, combine them into a single query with a join:
SELECT t1.*, COUNT(u.user_id) ct
FROM table_1 t1
LEFT JOIN user_modules AS u ON u.user_id = t1.user_id AND u.task_id = t1.task_id
AND u.begin_ymdhi BETWEEN '$date_from' AND '$date_to'
AND u.module_discon = 'N'
GROUP BY t1.user_id, t1.task_id
Are the task_id's unique? if so, the most straight forward would be something like:
$sql2 = "
SELECT count(task_id) AS TaskCount
FROM user_modules
WHERE
begin_ymdhi >= ".$date_from." AND
begin_ymdhi <= ".$date_to." AND
(
completed_ymdhi IS NULL OR
completed_ymdhi = ''
) AND module_discon = 'N'
group by user_id
";
$result = mysqli_query($sql2);
SELECT user_modules.user_id, user_modules.task_id, count(*)
FROM user_modules LEFT JOIN table_1 USING (user_id, task_id)
WHERE
begin_ymdhi >= ".$date_from." AND
begin_ymdhi <= ".$date_to." AND
module_discon = 'N' AND
(
completed_ymdhi IS NULL OR
completed_ymdhi = ''
)
GROUP BY user_modules.user_id, user_modules.task_id
Append EXPLAIN before that entire SELECT statement (i.e EXPLAIN SELECT count(*)...) and MySQL will give you a run-down on what the select is doing.
Make sure the begin_ymdhi field is indexed properly. SHOW INDEX FROM table_2 to see.

How we get unmatched values from tables in mysql databases

I have a problem in fetching data from mysql database tables.
I have two tables like table-1 and table-2 in below figure. How to get data from table-2 when pilotid is not equal to 1 in table-1.
I'm not sure, if I understand correctly, but this returns all rows of table-1, that do not have a matching entry in table-2. You can find the respective documentation of NOT EXISTS here.
SELECT *
FROM table-1 t1
WHERE NOT EXISTS( SELECT * FROM table-2 t2 WHERE t1.`Venueid` = t2.`Venueid` )
select a.venueid, a.name
from table2 a, table-1 b
where b.pilotid <> 1 and b.venueid = a.venueid;
SELECT Table_2.*
FROM Table_2
LEFT JOIN Table_1
ON Table_2.Venueid = Table_1.Venueid
WHERE Table_1.Venueid != 1
OR Table_1.Venueid NOT IN(1, 13, 15);
$sql = "select Venueid from Table1 where pilotid <> 1";
$data = mysql_query($sql);
while($row = mysql_fetch_assoc($data))
{
$ids[] = $row['Venueid'];
}
$sql2 = "select * from Table2 where venueid IN(".implode(',', $ids).")";
$data2 = mysql_query(sql2);
//$data2 contains the result-set resource;

Categories