Add 2 row counts together in MySql - php

I am adapting something and I need to add 2 row counts together in mysql. So far I have
<?
$result = mysql_query("SELECT * FROM Table1 WHERE Field1 ='2' ");
$num_rows = mysql_num_rows($result);
$result2 = mysql_query("SELECT * FROM Table2 WHERE Field2 ='6' ");
$num_rows2 = mysql_num_rows($result2);
$num_rows3 = ($num_rows + $num_rows2)
echo "$num_rows3";
?>
I can echo either $num_rows OR $num_rows2 fine but I need to do the calculation then echo $num_rows3.
I am probably doing something stupid here but I do not know mysql at all so I am trying to learn.
Thanks for the help!

You could also have one single query for both counts:
SELECT count(t1.id), count(t2.id)
FROM (SELECT id FROM Table1 WHERE Field1 ='2') t1,
(SELECT id FROM Table2 WHERE Field2 ='6') t2
Also note that you are missing a ; when summing the counts.

This is just a suggestion even though you got your answer.
If you want to add those into ONE MYSQLI query you could use this:
SELECT sum(cnt) from
(SELECT COUNT(*) cnt FROM T1 WHERE Field1=2 union all
SELECT COUNT(*) cnt FROM T2 WHERE Field2=6) a
I just don't see the point in fetching all data in SELECT * FROM Where all you do is mysql_num_rows($result)
Hope this helps, and maybe improves your code.
Good Luck!
Here is just a demo IN SQLFiddle, so you can see this in action:
SQLFiddle Demo

I was missing the ; after the calculation!!

Using only one query and counting before add, a possible code is
<?
$query = "SELECT c1 + c2 FROM ";
$query .= "(SELECT count(Field1) c1 FROM Table1 WHERE Field1 ='2') t1,";
$query .= "(SELECT count(Field2) c2 FROM Table2 WHERE Field2 ='6') t2";
$result = mysql_query($query);
$value = mysql_num_rows($result);
echo "$value";
?>

Related

fetch multiple value from same table using id value

I want to fetch value Rows from single table.I want to fetch sub_id for specific id.
I achieved my require ment in 2 query.I want to do it in single query.I want to display result as Event,order history,Eent Ticket,calander
$sql="select * from table1 where roles like %admin% and sub_id='0'"
$sql1=mysql_query($sql);
while($fet=mysql_fetch_assoc($sql1))
{
$id=$fet['id'];
$query="select page_name from table1 where sub_id= '$id'";
.. ..
}
Use a JOIN
SELECT t1.id, t1.sub_id, t1.page_name, t2.page_name AS parent_page
FROM table1 AS t1
JOIN table1 AS t2 ON t1.sub_id = t2.id
WHERE t2.roles like '%admin%' AND t2.sub_id = '0';
DEMO
use this
$sql="select sub_id from table1 where id='".$id."' ";
After this, use results of this as below
$sql= "select * from table1 where roles like %admin% and sub_id in($ids)";
You dont need another query to get the value of page_name just use $fet['page_name']; you already get the data of page_name in your first query.
$sub_id = $fet['sub_id'];//
echo $sub_id;//
$page_name = $fet['page_name'];//You can get and use the value of page_name here
UPDATED
if you want Event,Order History,Event Ticket and Calander
then change your where to sub_id = '2' ordered by id ascending.
$sql="select * from table1 where roles like %admin% and sub_id='2' order by id asc"
$sql1=mysql_query($sql);
while($fet=mysql_fetch_assoc($sql1))
{
echo $fet['page_name'].'<br/>';//display the page_name
}
You can also use the single query for getting page_name:
SELECT page_name FROM table1
WHERE roles LIKE %admin%
AND sub_id = 2
you can get Event,Order History,Event Ticket,Calendar as:
$sql="SELECT page_name FROM table1
WHERE roles LIKE %admin%
AND sub_id = 2";
$sql1=mysql_query($sql);
$records = array();
while($fet=mysql_fetch_assoc($sql1))
{
$records[] = $fet['page_name'];
}
echo implode(",",$records); // Event,Order History,Event Ticket,Calendar
UPDATE 1:
use sub_id = 2 for getting all page_name related to Event MAnagement
Side note:
I suggest you to use mysqli_* or PDO, instead of mysql_* because mysql_* is deprecated in not available in PHP 7.
$sql="select sub_id from table1 where id='".$id."' ";
if thats what you want.

Joining two tables to get a count

I am attempting to count comments on a particular page with the following problematic sql query:
$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND page_id = '943'"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;
the problem is it is outputting 0 and not 2.
The tables are as follows:
pages:
id:1 page_id:943
id:2 page_id:978
id:3 page_id:977
comments:
id:2 page_id:1 "hello"
id:3 page_id:1 "great"
id:4 page_id:3 "super"
So really the original query should be getting each comment's true page_id from the page_id as set in the pages tables, as joined by comments.page_id = pages.id
What would the final code look like to either make that join, and/or get that count? Thank you.
Try:
SELECT c.* FROM `comments` c
JOIN `pages` p on c.page_id = p.id
WHERE c.is_approved = '1' AND p.page_id = '943'
"SELECT * FROM comments, pages WHERE comments.page_id = pages.id AND is_approved = '1' AND comments.page_id = '943'"
Try using:
SELECT count(*) as cnt
FROM `comments` c join pages p on c.page_id = p.id
WHERE c.is_approved = '1' AND p.page_id = '943'
It seems like a very poor database design to have two columns with the same name in different tables that mean different things. You should probably change the name of pages.page_id to something else.
And, this returns the count directly, so you can read the value from the row. If you just want the count, there is no reason to return all the matching rows.
no join is needed:
$query = "SELECT * FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$query = mysql_query($query);
$total = mysql_num_rows($query);
echo $total;
ofcourse i would suggest a count statement if you do not need/use the data:
$query = "SELECT COUNT(*) as total FROM `comments` WHERE is_approved = '1' AND WHERE page_id IN (SELECT id WHERE page_id = '943')"
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$total = $row['total'];
echo $total;

SQL SELECT query echoing twice even with DISTINCT

I am creating a simple SQL query in PHP - and for some reason, even when DISTINCT is used, it shows twice like this:
BC
BC
OH
OH
TX
TX
Here is my code:
<?php
$sql = "SELECT DISTINCT `title`,`extra_fields_search` FROM `blahblah_items` WHERE catid=336 ORDER BY `blahblah_items`.`extra_fields_search` ASC ";
$partnerlisting= mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($partnerlisting))
foreach($row as $cname => $cvalue){
echo '<li>'.substr($row[extra_fields_search], 0, 2).'</li><br>';
}
;
?>
How can I make it so it prints out only one of each?
SELECT
`title`,
`extra_fields_search`
FROM
`blahblah_items`
WHERE
catid=336
GROUP BY
SUBSTRING(extra_fields_search,1,2) # here. group by first two characters of extra_fields_search
# or just "GROUP BY extra_fields_search", depends what you need
ORDER BY
`blahblah_items`.`extra_fields_search` ASC
SELECT DISTINCT a,b FROM table works in same way as SELECT a,b FROM table GROUP BY a,b
Please follow documentation:
http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
Distinct make sure that you get unique rows. It does not make sure you will get unique column values. In your case if you consider all the fields in the result, you will notice that each row is different from the other by at least one field.
SO you will never get
Col1 Col2
A B
A B
But you can get
Col1 Col2
A B
A C
Try:
SELECT `title`, group_concat(distinct `extra_fields_search`)
FROM `blahblah_items`
WHERE catid=336
Group BY `title`
ORDER BY 2
try this
SELECT `title`,`extra_fields_search`
FROM `blahblah_items` WHERE catid=336
Group BY extra_fields_search
ORDER BY `blahblah_items`.`extra_fields_search` ASC
edit :
try this in your code
while($row = mysql_fetch_assoc($partnerlisting))
$rows[] = $row;
foreach($rows as $row){
echo '<li>'.substr($row[extra_fields_search], 0, 2).'</li><br>';
}
;

How to send SQL count data & array data together?

I have a script designed to print out values of students who have accrued more than 3 tardies. I want this script to print out both the student name, and the amount of times they've been tardy, but so far I've been only able to print out their names with the following script:
$sql = "select DISTINCT StudentID,classid,date from attendance_main where status = 'Tardy' AND classid like '%ADV%'";
$result = mysql_query($sql) or die (mysql_error());
while($row=mysql_fetch_array($result)) {
$studentid = $row['StudentID'];
$sql2 = "select distinct StudentID,classid,date from attendance_main where StudentID = '$studentid' AND status = 'Tardy' AND classid like '%ADV%'";
$result2 = mysql_query($sql2) or die (mysql_error());
while($row2=mysql_fetch_array($result2)) {
$tardycount = mysql_num_rows($result2);
$studentid = $row2['StudentID'];
if($tardycount >= 3) {
$sql3 = "select * from students where rfid = '$studentid'";
$result3 = mysql_query($sql3) or die (mysql_error());
while($row3=mysql_fetch_array($result3)) {
$fname[] = $row3['fname'];
}
}
}
}
$newdata = array_unique($fname);
foreach ($newdata as $value) {
echo $value;
}
I can't think of how to intuitively do this. Keeping it all in the while loop didn't work (I had multiple results coming up for the same students despite requesting unique entries) so using array_unique was the only method I could think of.
Thanks for any help!
Something like this:
SELECT
attendance_main.StudentID,
students.fname,
COUNT(attendance_main.*) AS `times_tardy`
FROM
attendance_main
INNER JOIN
students
ON
attendance_main.StudentID = students.rfid
WHERE
attendance_main.status = 'Tardy'
AND
attendance_main.classid like '%ADV%'
GROUP BY
attendance_main.StudentID
HAVING
`times_tardy` > 3
Joining the two tables gets you the tardy count and student's name in one query, and the GROUP BY and HAVING clause that get you only the students with more than 3 tardy entries.
You can (and should) do almost everything in SQL. It should look something like this.
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"
left join student on student.rfid = attendance_main.StudentId
group by StudentId
having count(*) > 3;
Here's how it works.
select the results you want to work with:
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"
Join the students to your result set on the common id
left join student on student.rfid = attendance_main.StudentId
group everything by student. We use count(*) to get the number of items. We know we're only dealing with tardies because of the where clause in the select.
group by StudentId
limit the results to only tardies above 3 with the having claues (this is like a where clause for the group by)
having count(*) > 3;

MySQL return unique columname with 2 joins of equal table

I have the following query:
SELECT *
FROM scool
LEFT JOIN people as t1 ON t1.scool_fk=scool.id AND t1.lang_gk='en'
LEFT JOIN people as t2 ON t2.scool_fk=scool.id AND t2.lang_gk='fr'
...
(this is nonsense query, only for example)
With SELECT * it query returns french values
With SELECT t1.* it query returns english values
The only possible solution i know is
SELECT t1.name as name_en, t2.name as name_fr
This don't like me because i can't automatize the selects in my program
Is possible to be return all values from SELECT with tablename.columnname or other similar solution, for get values in php?
Use mysql_fetch_field and properties table and name:
<?php
mysql_connect("", "", "");
mysql_select_db("test");
$res = mysql_query("SELECT * FROM t_ai a1 CROSS JOIN t_ai a2 LIMIT 1") or die(mysql_error());
$names = array();
for ($i = 0; $i < mysql_num_fields($res); $i++) {
$meta = mysql_fetch_field($res, $i);
array_push($names, "$meta->table.$meta->name");
}
print implode($names, "\t") . "\n";
?>
$ php phptest.php
a1.id a2.id

Categories