Joining two tables to get a count - php

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;

Related

Add 2 row counts together in MySql

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";
?>

How to run a query and fetch items in 3-dimensional array format

I've been trying to get towns from local councils and local councils from states. I was able to get local councils from state, but getting towns from local councils is a problem. It keeps telling me illegal offset. this is my code:
$querys = "select id,title from link where (parent is null or parent=0) and title is not null and category='state' and type='1' order by title";
$results = mysql_query($querys,$link) or die(mysql_error());
$counts = 0;
while($rows= mysql_fetch_array($results,MYSQL_ASSOC))
{
$state_id[] = $rows["id"];//echo $state_id[$counts]."<br>";
$state[] = $rows["title"];
$querylg = "select id,title from link where title is not null and category='lga' and type='1' and parent={$rows['id']} and parent is not null order by title";
$resultlg = mysql_query($querylg,$link) or die(mysql_error());
$countlg[$counts] = 0;
while($rowk=mysql_fetch_array($resultlg,MYSQL_ASSOC))
{
$lg_id[$counts][] = $rowk["id"];//echo $lg_id[$counts][$countlg]."<br>";
$lg_name[$counts][] = $rowk["title"];
$queryt = "select id,title from link where title is not null and category='town' and type='1' and parent={$rowk['id']} and parent is not null order by title";
$resultt=mysql_query($queryt,$link) or die(mysql_error());
$counttw[$countlg][$counts] = 0;
while($row=mysql_fetch_array($resultt,MYSQL_ASSOC))
{
$tw_id[$counts][$countlg][] = $row["id"];
$tw_name[$counts][$countlg][] = $row["title"];
$counttw[$countlg][$counts]++;
}
$countlg[$counts]++;
}
$counts++;
}
I am not quite sure exactly what you want from your code (ie, how many of the counts, etc, are just there to get your array, and how many are actually required). Could you put the actual output you want?
I would be tempted to rewrite it based on a single joined query:-
SELECT a.id AS state_id, a.title AS state_title, b.id AS lg_id, b.title AS lg_title, c.id AS town_id, c.title AS town_title
FROM link a
LEFT OUTER JOIN link b ON a.id = b.parent AND b.title IS NOT NULL AND b.category='lga' AND b.type='1'
LEFT OUTER JOIN link c ON b.id = c.parent AND b.title IS NOT NULL AND b.category='town' AND b.type='1'
WHERE (a.parent IS NULL OR a.parent=0) AND a.title IS NOT NULL AND a.category='state' AND a.type='1'
ORDER BY a.title, b.title, c.title

Inner/Left join with two different where clauses

i'm in the process of joining two tables together under two different conditions. For primary example, lets say I have the following nested query:
$Query = $DB->prepare("SELECT ID, Name FROM modifications
WHERE TYPE =1 & WFAbility = '0'");
$Query->execute();
$Query->bind_result($Mod_ID,$Mod_Name);
and this query:
$Query= $DB->prepare("SELECT `ModID` from `wfabilities` WHERE `WFID`=?");
$Query->bind_param();
$Query->execute();
$Query->bind_result();
while ($Query->fetch()){ }
Basically, I want to select all the elements where type is equal to one and Ability is equal to 0, this is to be selected from the modifications table.
I further need to select all the IDs from wfabilities, but transform them into the names located in modifications where WFID is equal to the results from another query.
Here is my current semi-working code.
$Get_ID = $DB->prepare("SELECT ID FROM warframes WHERE Name=?");
$Get_ID->bind_param('s',$_GET['Frame']);
$Get_ID->execute();
$Get_ID->bind_result($FrameID);
$Get_ID->fetch();
$Get_ID->close();
echo $FrameID;
$WF_Abilties = $DB->prepare("SELECT ModID FROM `wfabilities` WHERE WFID=?");
$WF_Abilties->bind_param('i',$FrameID);
$WF_Abilties->execute();
$WF_Abilties->bind_result($ModID);
$Mod_IDArr = array();
while ($WF_Abilties->fetch()){
$Mod_IDArr[] = $ModID;
}
print_r($Mod_IDArr);
$Ability_Name = array();
foreach ($Mod_IDArr AS $AbilityMods){
$WF_AbName = $DB->prepare("SELECT `Name` FROM `modifications` WHERE ID=?");
$WF_AbName->bind_param('i',$AbilityMods);
$WF_AbName->execute();
$WF_AbName->bind_result($Mod_Name);
$WF_AbName->fetch();
$Ability_Name[] = $Mod_Name;
}
print_r($Ability_Name);
See below:
SELECT ModID,
ID,
Name
FROM modifications M
LEFT JOIN wfabilities WF
ON WF.ModID = M.ID
WHERE TYPE =1 & WFAbility = '0'
To do this, you need to join your tables, I'm not quite sure what you are trying to do so you might have to give me more info, but here is my guess.
SELECT ID, Name, ModID
FROM modifications
JOIN wfabilities
ON WFID = ID
WHERE TYPE = '1'
AND WFAbility = '0'
In this version I am connecting the tables when WFID is equal if ID. You will have to tell me exactly what is supposed to be hooking to what in your requirements.
To learn more about joins and what they do, check this page out: MySQL Join
Edit:
After looking at your larger structure, I can see that you can do this:
SELECT modifications.Name FROM modifications
JOIN wfabilities on wfabilities.ModID = modifications.ID
JOIN warframes on warframes.ID = wfabilities.WFID
WHERE warframes.Name = 'the name you want'
This query will get you an array of the ability_names from the warframes name.
This is the query:
"SELECT A.ID, A.Name,B.ModID,C.Name
FROM modifications as A
LEFT JOIN wfabilities as B ON A.ID = B.WFID
LEFT JOIN warframes as C ON C.ID = B.WFID
WHERE A.TYPE =1 AND A.WFAbility = '0' AND C.Name = ?"

How to get information from 2 tables at once in PHP and MySQL?

<?php
include('includes/config.php');
$topi = $_GET['id']; //id of url
mysql_select_db("ban", $con);
$query = "SELECT * FROM `basic` WHERE id = '$topi' LIMIT 0, 30";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$aa = $row['item'];
$cc = $row['moreinfo'];
$dd = $row['contactinfo'];
$ff = $row['id'];
In this script, I get information from the table basic, but I want to retrieve data from another table named users. How can I retrieve data from two tables at once?
users table consists of following columns:
email
username
ID
You need to JOIN the two tables on a common value, called a foreign key. Once you've posted the structure of the users table as requested in the comments, I can provide a more complete example.
EDIT: See example. This calls explicit column names instead of SELECT *.
$query = "SELECT
basic.id,
basic.item,
basic.moreinfo,
basic.contactinfo,
users.email,
users.username
FROM basic JOIN users ON basic.id = users.id
WHERE id = '$topi'
LIMIT 0 , 30";
You would use a JOIN onto the other table.
$query = "SELECT *
FROM basic b
JOIN users u ON b.user_id = u.user_id
WHERE id = '$topi'
LIMIT 0, 30";
Something like that, but based on your fields.
Please Note: the ON clause specifies what you will be looking for a match on.

One query instead of two?

Here I'm making two queries with PHP. Is there something more simple? One query instead of two?
$id = mysql_real_escape_string($_GET["id"]);
$result = mysql_query("SELECT * FROM questionstable WHERE id=$id");
$row = mysql_fetch_assoc($result);
$category = $row['category'];
$main = mysql_query("SELECT name FROM categorytable WHERE id=$category");
SELECT questionstable.*, categorytable.name
FROM questionstable
INNER JOIN categorytable
ON categorytable.id = questionstable.category
WHERE questionstable.id=$id
As an aside, assuming your questionstable.id is numeric, you could use $id = (int)$_GET["id"] and save some writing. (It's also probably a safer bet. Just because it's escaped doesn't mean it's completely safe--especially when it's not within quotes [gives you a LOT of options for SQL injection]. ;-))
Please try:
SELECT name
FROM categorytable
WHERE id = (
SELECT category
FROM questionstable
WHERE id = $id
)
$id = mysql_real_escape_string($_GET["id"]);
$main = mysql_query("SELECT c.name FROM categorytable c inner join questionstable q on c.category = q.category WHERE q.id = $id");
Do not use inner join use left join instead, it won't return any result if the category is not found
SELECT questionstable.*, categorytable.name
FROM questionstable
LEFT JOIN categorytable
ON categorytable.id = questionstable.category
WHERE id=$id

Categories