I have a 2 tables called forums and forum_categories in database
forum_categories
cat_id
forums
cat_id
I am trying to count the total for each category for some reason it displays total record for all records.
I have 2 categories so far in the database
first category has value of 1
second category has value of 2
In category one, I have two forums that has a cat_id of 1
In category two, I have one forum that has a cat_id of 2
it displays
category 1 -------------------- 3 ---------------
category 2 -------------------- 3 ---------------
when it should display
category 1 -------------------- 2 ---------------
category 2 -------------------- 1 ---------------
$topics_count always displays 3.
$sql = "SELECT * FROM forum_categories, forums WHERE forum_categories.cat_id = forums.cat_id GROUP BY forum_categories.cat_id";
$result = query($sql);
$sql2 = "SELECT fc.cat_title COUNT(f.forum_id) FROM forums as f LEFT JOIN forum_categories fc ON (f.cat_id = fc.cat_id) GROUP BY f.cat_id";
$result2 = query($sql2);
$topics_count = count($result2);
while (($row = mysqli_fetch_assoc($result)) != false) {
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
$forum_name = $row['forum_name'];
echo "<tr>";
echo "<td>$cat_id</td>";
echo "<td><a href='viewforum.php?f={$cat_id}'>$cat_title</a><br>$forum_name admin</td>";
echo "<td>$topics_count</td>";
echo "<td>0</td>";
echo "</tr>";
}
This bit of code below gives you all results:
$sql2 = "SELECT * FROM forums WHERE cat_id = cat_id";
$result2 = query($sql2);
$topics_count = row_count($result2); // here this would be 3*
*in case of 2 for cat1 + 1 for cat2 and you echo this in each table row as:
echo "<td>$topics_count</td>";
therefore you see the total number (3) on both rows.
What you are actually trying is to join forums and forum_categories table, get the forum_categories.cat_title and COUNT(forums.cat_id) while grouping the results by forums.cat_id
SELECT
fc.cat_title,
COUNT(f.forum_id)
FROM forums as f
LEFT JOIN forum_categories fc ON (f.cat_id = fc.cat_id)
GROUP BY f.cat_id
Here is the same demo fiddle I've sent you yesterday.
Your query would then return you something like:
Demo Forum 1 | 2
Demo Forum 2 | 1
UPDATE:
$sql2 = "SELECT
fc.cat_id,
fc.cat_title,
f.forum_name,
COUNT(f.forum_id) as count
FROM forums as f
LEFT JOIN forum_categories fc ON (f.cat_id = fc.cat_id)
GROUP BY f.cat_id";
$result2 = query($sql2);
while (($row = mysqli_fetch_assoc($result)) != false) {
$cat_id = $row['cat_id']; // category id
$cat_title = $row['cat_title']; // category title
$forum_name = $row['forum_name']; // forum name
$count = $row['count']; // count of forum_id (grouped by cat_id)
echo "<tr>";
echo "<td>$cat_id</td>";
echo "<td><a href='viewforum.php?f={$cat_id}'>$cat_title</a><br>$forum_name admin</td>";
echo "<td>$count</td>";
echo "<td>0</td>";
echo "</tr>";
}
Here, I'm pretty sure the count would be okay, but not sure about "Forum Name".
try this
replace this
while (($row = mysqli_fetch_assoc($result)) != false) {
with this
while ($row = mysqli_fetch_assoc($result)) {
Related
I want to get data from another table by just calling if the ID and data from another table is the same.
Table_1
Id | name | lastname
1 | Fred | Moore
Table 2
Id | table1_id
1 | 1
I can already get and store the table 1 id to my table 2, but i want to echo the name and lastname from the table 1.
e.g. if table 2 table1_id is equal to Table_1 Id it will print the name and lastname .
Try this query
select table_1.name, table_1.lastname
from table_1
left join on table_2 on table_1.id = table_2.table1_id
<?php
$a = "Table_1";
$b = "Table_2 ";
$allItem = $cxn->query("SELECT *
FROM $a
INNER JOIN $b
ON $a.id = $b.id
WHERE $a.id = 1);
$allItem = $allItem->fetchAll();
$lastName = $allItem["lastname"];
$name = $allItem["name"];
?>
Maybe it could work!
<?php
$conn = mysqli_connect("localhost","username","password","database_name");
if(!$conn){
echo "Database Connection Failed!";
}
$query1 = mysqli_query($conn,"SELECT table1_id,first_name,last_name FROM table_1")or trigger_error(mysqli_error($conn));
if(mysqli_num_rows($query1)){
while($row1 = mysqli_fetch_array($query1)){
$table1_id = $row1['table1_id'];
$table1_first_name = $row1['first_name'];
$table1_last_name = $row1['last_name'];
$query2 = mysqli_query($conn,"SELECT table2_id,table1_id,first_name,last_name FROM table_2 WHERE table1_id='$table1_id' ORDER BY first_name,last_name ASC")or trigger_error(mysqli_error($conn)); //check table1_id from table2 AND table1_id from table1 if matched
$row2 = mysqli_fetch_array($query2);
$table2_first_name = $row2['first_name'];
$table2_last_name = $row2['last_name'];
echo "First Name: ".$table2_first_name."<br>"; //print first name
echo "Last Name: ".$table2_last_name."<br>"; //print last name
}
}
else{
echo "No Result Found.";
}
?>
This question already has answers here:
Select Name instead OF ID in table with ID-Ref Column SQL
(2 answers)
Show Name Instead of ID from Different Table
(2 answers)
Closed 1 year ago.
I have 2 tables
rankID | name
1 | new
2 | learner
3 | experienced
4 | pro
And another with all the user info and passwords and stuff
id | username | rankID
1 | hello | 3
2 | hey | 3
I have come so far so I can display their rank number, but I want to display the rank name. How can I do that? I have tried a lot of things but I'm not so good at sql and the php part of it.
This is the code I use to display the rank number
//Get rankID
$query = "SELECT rankID FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];
And to display the rank number:
Rank: <?php echo $rank; ?>
Simple JOIN query :-
"SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'"
And then After:-
$query = "SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
Do:-
$rank = $row['rankID'];
$rank_name = $row['rank_name'];
Rank: <?php echo $rank; ?>
RankName: <?php echo $rank_name; ?>
Or
$rank_data = $row;
Rank: <?php echo $rank_data['rankID']; ?>
RankName: <?php echo $rank_data['rank_name']; ?>
Not:- lot of other possible ways are there which are listed by other programmers in comment and answer as well.
//Get datas
$query = "SELECT rankID, name FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];
$rank = $row['name'];
And to display the datas:
Rank: <?php echo $rank; ?>
Name: <?php echo $name; ?>
Hope so this should make a trick for you.
$query = "SELECT rankID FROM users WHERE id = '".$userId."'";
$result = $conn->query($query);
$count = $result->num_rows;
if($count==0)
{
return false;
}
else
{
$rows=[];
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
}
Please use below code
$query = "SELECT name FROM users as u JOIN rank as r ON r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
Name: <?php echo $name; ?>
When you want to get data from two different table.You need join query.
Here is your query which will solve your proble definitely :
$q="select a.name,b.rankID from rankname as a INNER JOIN user as b
ON a.rankID = b.rankID";
For more know about How to join two tables see this:http://www.tutorialspoint.com/sql/sql-using-joins.htm
Hope this will help you better.
Please try this
//Get rankID
$query = "SELECT r.name as rank_name FROM rank as r inner join users as u on r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];
echo 'Rank: '. $rank;
try this:
//Get rankID
$query = "SELECT rankID, rank.name AS rank_name FROM rank, users WHERE id = '$userId' and users.rankid = rank.rankid";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];
echo $rank;
the below is my mysql table structure, the values inside are not fixed and can get changed by admin.
town_name | product_name| pending_quantity
------------------------------------------
Jaipur | Mobile | 5
Jaipur | Charger | 3
Surat | wallet | 2
Surat | Mobile | 1
Surat | battery | 3
Surat | cover | 2
In my php code, i stored all these values in 3 different arrays (one for each column) and everything is fine. I want to show this data in HTML table but the structure it needs to be shown is a problem to me. Below is the expected HTML table structure.
town_name | Mobile | charger | wallet | Battery | cover
-------------------------------------------------------
Jaipur | 5 | 3 | | |
Surat | 1 | | 2 | 3 | 2
So far, I've achieved to show rows and column headers the way it should be. But am now unable to put the pending quantity values in its place.
This is my php code if its of any help
<tbody>
<?php
$count = 1;
$row=0;
foreach($townid as $townKey=>$townValue) {
echo "<tr>";
echo "<td>$count</td>";
echo "<td>$townValue</td>";
foreach($items as $productKey=>$productValue) {
echo "<td>$pendingqty[$townKey]</td>";
$row++;
}
$row++;
echo "</tr>";
$count++;
}
?>
</tbody>
The column headers (mobile, charger etc etc) are dynamic and the town names are also dynamic. Please help me in achieving the desired result via mysql or html.
PHP code that gets values inside arrays
$townid2 = array();
$itemname = array();
$pendingqty = array();
$items = array();
$query = mysql_query("select o.town_id as townid, od.item_name as itemname, sum(od.pending_qnty) as pendingqty FROM tbl_order o JOIN tbl_order_data od on o.id = od.order_id where month(o.order_date)='1' GROUP BY o.town_id, od.item_name ");
while($row = mysql_fetch_array($query)) {
$townid2[]=$row['townid'];
$pendingqty[] = $row['pendingqty'];
$items[] = $row['itemname'];
}
$townid = array_unique($townid2, SORT_REGULAR);
$query2 = mysql_query("select od.item_name FROM tbl_order_data od JOIN tbl_order o on o.id=od.order_id where od.order_id IN (select id from tbl_order where month(order_date)='1') group by od.item_name order by o.item_name ");
$productArray = array();
while($row2 = mysql_fetch_array($query2)) {
$productArray[] = $row2['item_name'];
}
Here is how I would do it (I'm using mysql_query because you did, but it's deprecated so you really should switch):
$things = array();
$columns = array('Mobile','charger','wallet','Battery','cover'); //this can/should be populated dynamically using a distinct product query, but I'm hard-coding it because I'm lazy
$query = mysql_query("select o.town_id as townid, od.item_name as itemname, sum(od.pending_qnty) as pendingqty FROM tbl_order o JOIN tbl_order_data od on o.id = od.order_id where month(o.order_date)='1' GROUP BY o.town_id, od.item_name");
while($row = mysql_fetch_array($query)) {
$things[$row['townid']][$row['itemname']] = $row['pendingqty'];
}
... //whatever code until you're ready for the table
echo "<table><thead><tr>";
foreach($columns as $column){
echo "<th>".$column."</th>";
}
echo "</tr><thead><tbody>";
foreach($things as $key=>$value){
echo "<tr><td>".$key."</td>";
foreach($columns as $column){
echo "<td>".(isset($value[$column]) ? $value[$column] : null)."</td>";
}
echo "</tr>";
}
echo"</tbody></table>";
Here's my take
$itemnames = array();
$pendingqtys = array();
$query = mysql_query("SELECT
od.item_name AS itemname
FROM
tbl_order o
JOIN
tbl_order_data od ON o.id = od.order_id
WHERE
MONTH(o.order_date) = '1'
GROUP BY o.town_id");
while($row = mysql_fetch_array($query)) {
$itemnames[] = $row['itemname'];
}
$query = null;
$query = mysql_query("SELECT
o.town_id AS townid,
od.item_name AS itemname,
SUM(od.pending_qnty) AS pendingqty
FROM
tbl_order o
JOIN
tbl_order_data od ON o.id = od.order_id
WHERE
MONTH(o.order_date) = '1'
GROUP BY o.town_id , od.item_name");
while($row = mysql_fetch_array($query)){
$pendingqtys[$row['townid']][$row['itemname']]=$row['pendingqty'];
}
Then to display the results
echo "<table><thead><tr><th>Town Names</th>";
foreach($itemnames as $itemname){
echo "<th>".$itemname."</th>";
}
echo "</tr></thead><tbody>";
foreach ($pendingqtys as $town => $pendingqty){
echo "<tr><th>".$town."</th>";
foreach ($itemnames as $itemname){
echo "<td>".$pendingqty[$itemname]."</td>";
}
echo "</tr>";
}
echo "</tbody></table>";
I can't figure out join..
need to select all rows from one table where a column equals something in another table..
like this:
SELECT ALL FROM someTable
WHERE COLUMN someColumn = '123' (IN A DIFFERENT TABLE)
something like that..
and the IDs need to match of course..
Just use an INNER JOIN:
SELECT *
FROM SomeTable S
JOIN SomeOtherTable S2
ON S.SomeKey = S2.SomeKey
WHERE S.SomeColumn = '123'
A Visual Explanation of SQL Joins
I wasn't completely clear of your question, so you may not need the WHERE clause if that represented your JOIN criteria.
A bit error in my question, let me clarify
tblplace
id place
1 London
2 Paris
3 New York
tbltraveller
tr_id tr_name id
1 John 3
2 Jackson 2
3 Susanna 1
4 Jimmy 3
5 Lucy 2
The problem is missing some data for New York:
Paris Jackson Lucy
New York
My code(guess there is an error in the while loop):
<?php
require_once("connMysql1.php");
$qry = "SELECT * FROM tblPlace WHERE tblPlace.id > 1 ORDER BY tblPlace.id";
$result = mysqli_query($db_link, $qry);
$qry1 = "SELECT tblPlace.id, tblPlace.Place, tbltraveller.tr_id,
tbltraveller.tr_name, tbltraveller.id FROM tblPlace INNER JOIN tbltraveller ON
tblPlace.id = tbltraveller.id WHERE tblPlace.id > 1 ORDER BY tbltraveller.id";
$result1 = mysqli_query($db_link, $qry1);
$no_of_row1 = mysqli_num_rows($result1);
$no_of_row = mysqli_num_rows($result);
echo "<table border=1 cellpadding=10>";
if ($no_of_row >0){
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>";
echo $row['place']."<br>";
echo "</td>"." ";
echo "<td>";
while ($row1 = mysqli_fetch_assoc($result1)){
if($row1['id'] == $row['id']){
echo $row1['tr_name']." ";
}
}
echo "</td>";
"</tr>";
}
}
echo "</table>";
?>
`
My application requires to create a stock management table which has a lot of items categorised into subgroups. For and idea, the stock management table looks like:
Location1 Location2 Total
Desktops // Main Category
Microsoft //Sub-Category
Windows 7 23000 150000 173000
Office 2011 203300 3002 206302
....
Apple //Sub-Category
OS Snow Leopard 4000 3000 7003
OS Lion 39494 40034 79528
...
Tablets //Main Category
Lenovo //Sub-Cateogry
LX-243 3434 4399 7833
...
This is a visualisation of what the table should look like, now i have a huge mysql query which does that for me, it is scary. In a gist, what i am doing is the following:
Select 1st category and start a while loop
// echo as the main category
Select sub-category corresponding to the main category and start a while loop again.
// echo as the sub-category
select all items in the sub-category and start a while loop.
select 1st location.
select the current item from 3 and the current location from 4 and echo item.
// echo item names and the quantity in the locations.
Now my question here is is there a better way to display this than using several while loops, i tried using functions but they are becoming a mess too. Also i couldn't figure out where should i perform the calculations to get the total in the last column.
Database structure:
Category: CategoryID, Description
Sub-Cateogry: Sub-Category_ID, Category_ID, Description
Item: Item_ID, Sub-category_id, Description
Location: Location_ID, Description
Stock_Management: Item_ID, Location_ID, Quantity
Code as requested:
$sql = mysql_query("select Board_ID, Title from Board where Company_ID = '$company_id' order by Title");
while($row = mysql_fetch_array($sql)) {
$curr_ID = $row[0];
$curr_category = $row[1];
echo "<tr class='sub-heading' style='background: rgba(76, 178, 255, 0.1)'><td colspan='".$count."'>".$curr_category."</td></tr>";
$sql1 = mysql_query("select Sub_Category_ID, Title from Sub_Category where Category_ID = '$curr_ID' order by Title");
while($row1 = mysql_fetch_array($sql1)) {
$curr_sub_cat_id = $row1[0];
$curr_sub_cate = $row1[1];
echo "<tr style='background: rgba(149, 255, 145, 0.10'><td colspan='".$count."'><b>".$curr_sub_cate."</b></td></tr>";
$sql2 = mysql_query("select Book_ID, title from Book where sub_category_id = '$curr_sub_cat_id' Order by title");
while($row2 = mysql_fetch_array($sql2)) {
$curr_book = $row2[0];
echo "<tr><td>".$row2[1]."</td>";
$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where OfficeTitle IN ('$locations')");
while($row3 = mysql_fetch_array($sql4)) {
$curr_location = $row3[0];
$sql3 = mysql_query("select Quantity from Stock_Management where Book_ID = '$curr_book' and Location_ID = '$curr_location'");
while($row3 = mysql_fetch_array($sql3)) {
echo "<td>".$row3[0]."</td>";
}
}
echo "</tr>";
}
}
}
How about something like this -
<?php
$locations = array('Location 1', 'Location 2', 'Location 3');
$locationCols = array();
$locationList = array();
foreach ($locations as $location) {
$locationColName = preg_replace('[^a-z0-9]', '_', strtolower($location));
$location = mysql_real_escape_string($location);
$locationCols[] = "SUM(IF(Office.OfficeTitle = '$location', Stock_Management.Quantity, 0)) AS `$locationColName`";
$locationList[] = "'$location'";
}
$locationCols = implode(', ', $locationCols);
$locationList = implode(',', $locationList);
$sql = "SELECT Board.Title AS BoardTitle, Sub_Category.Title AS SubCatTitle, Book.title AS BookTitle, $locationCols, SUM(Stock_Management.Quantity) AS Total
FROM Board
INNER JOIN Sub_Category
ON Board.Board_ID = Sub_Category.Category_ID
INNER JOIN Book
ON Sub_Category.Sub_Category_ID = Book.sub_category_id
INNER JOIN Office
LEFT JOIN Stock_Management
ON Book.Book_ID = Stock_Management.Book_ID
AND Office.OfficeID = Stock_Management.Location_ID
WHERE Board.Company_ID = 2
AND Office.OfficeTitle IN ($locationList)
GROUP BY Board.Title, Sub_Category.Title, Book.title";
$result = mysql_query($sql);
$prevBoard = '';
$prevSubCat = '';
echo '<table>';
while ($row = mysql_fetch_object($result)) {
// if new board print board
if ($prevBoard != $row->BoardTitle) {
echo '<tr class="sub-heading" style="background: rgba(76, 178, 255, 0.1)"><td colspan="">' . $row->BoardTitle . '</td></tr>';
}
$prevBoard = $row->BoardTitle;
if ($prevSubCat != $row->SubCatTitle) {
echo '<tr style="background: rgba(149, 255, 145, 0.10)"><td colspan=""><b>' . $row->SubCatTitle . '</b></td></tr>';
}
$prevSubCat = $row->SubCatTitle;
// print product row
echo '<tr>';
echo "<td>{$row->BookTitle}</td>";
foreach ($locations as $location) {
$locationColName = preg_replace('[^a-z0-9]', '_', strtolower($location));
echo "<td>{$row->$locationColName}</td>";
}
echo "<td>{$row->Total}</td>";
echo '</tr>';
}
echo '<table>';