I'm new to PHP/MYSQL languages and would like to know if anyone could tell me how to display number of items next to the categories I have given below.
Example,
Art (5)
Drama (2)
Music (5)
Fiction (4)
Computer (5)
And, here is my php code;
index.php
<?php
$dbh=mysql_connect("localhost","root","root") or die ('Cannot connedt to the Database' .mysql_errno());
mysql_select_db("booksdb");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select a Company</title>
</head>
<body>
<?php
$res_query = mysql_query("SELECT * FROM bookcatname ORDER BY category ASC");
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'<br />';
}
?>
</body>
</html>
page.php
<?php
$dbh=mysql_connect("localhost","root","root") or die ('Cannot connect to the Database' .mysql_errno());
mysql_select_db("booksdb");
if ( empty($_GET['cat_id']) )
{
header('Location: index.php');
exit();
}
$getCats = mysql_query("SELECT * FROM books WHERE cat_id = '".intval($_GET['cat_id'])."'");
echo '<ul>';
while ( $book = mysql_fetch_assoc($getCats) )
{
echo '<li>'.$book['title'].'<br />'.$book['author'].'<br />'.'</li><br />';
}
echo '</ul>';
?>
Here are the tables;
table name - bookcatname
+----+--------+----------+
| id | cat_id | category |
+----+--------+----------+
| 1 | 1 | Art |
| 2 | 2 | Drama |
| 3 | 3 | Music |
| 4 | 4 | Fiction |
| 5 | 5 | Computer |
+----+--------+----------+
table name - books
+----+--------+---------------------------------+-----------------------+
| id | cat_id | title | author |
+----+--------+---------------------------------+-----------------------+
| 1 | 1 | Color and Light | James Gurney |
| 2 | 1 | The Art Spirit | Robert Henry |
| 3 | 1 | Art & Fear | David Bayles |
| 4 | 1 | How Pictures Work | Molly Bang |
| 5 | 1 | Imaginative Realism | James Gurney |
| 6 | 2 | A Walk To Remember | Nicholas Sparks |
| 7 | 2 | An Old Fashioned Girl | Louisa May Alcott |
| 8 | 3 | The Rest Is Noise | Alex Ross |
| 9 | 3 | It Still Moves | Amanda Petrusich |
| 10 | 3 | Chronicles | Bob Dylan |
| 11 | 3 | Dream Boogie | Peter Guralnick |
| 12 | 3 | Escaping The Delta | Robert Johnson |
| 13 | 4 | Atlas Shrugged | Ayn Rand |
| 14 | 4 | Anthem | Ayn Rand |
| 15 | 4 | Sons and Lovers | D.H. Lawrence |
| 16 | 4 | Henderson the Rain King | Saul Bellow |
| 17 | 5 | The Art of Computer Programming | Donald Knuth |
| 18 | 5 | The Art of Unix Programming | Eric Raymond |
| 19 | 5 | Free Software, Free Society | Richard M. Stallman |
| 20 | 5 | Database System Concepts | Abraham Silberschatz |
| 21 | 5 | 3ds Max 2008 in Simple Steps | Kognet Solutions Inc. |
+----+--------+---------------------------------+-----------------------+
SELECT A.cat_id as cat_id, count(A.cat_id) as cnt, B.category as cat_name
FROM books A, bookcatname B
WHERE A.cat_id=B.cat_id
GROUP BY A.cat_id
UPDATE 2 :
<?php
$sql = "SELECT A.cat_id as cat_id, count(A.cat_id) as cnt, B.category as cat_name
FROM books A, bookcatname B
WHERE A.cat_id=B.cat_id
GROUP BY A.cat_id";
$res_query = mysql_query($sql);
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['cat_name'].'<br />';
}
?>
I don't want to complicate things since you are starting to learn PHP and MySQL. There are a lot of ways to achieve what you want but I will hand you a simple solution with your problem.
You can try changing your code from:
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'<br />';
}
To:
while($category = mysql_fetch_assoc($res_query))
{
$categoryID = $category['cat_id'];
$queryCount = mysql_query("SELECT COUNT(id) AS total
FROM books
WHERE cat_id = '$categoryID'");
$row = mysql_fetch_assoc($queryCount);
echo '' . $category['category'] . ' (' . $row['total'] . ')<br />';
// Note: Please try to var_dump($row) and look if $row['total'] contains the number of books under on that category.
}
That's all and Enjoy learning...
You need to use JOIN opertaion on tables "bookcatname" and "books" to get the total count for each category.
SELECT A.cat_id as cat_id, count(A.cat_id) as cnt, B.category as cat_name
FROM books A, bookcatname B
WHERE A.cat_id=B.cat_id
GROUP BY A.cat_id
Check demo on : http://sqlfiddle.com/#!2/73eb29/13
Modify your following part of index.php file:
$res_query = mysql_query("SELECT A.cat_id as cat_id, count(A.cat_id) as cnt, B.category as cat_name FROM books A, bookcatname B WHERE A.cat_id=B.cat_id GROUP BY A.cat_id");
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'('.$category['cnt'].')<br />';
}
Try using SQL code that will count and group the items.
I am sure this code will work but it is UN-TESTED.
SELECT COUNT(*) as cnt,category
FROM books
LEFT JOIN bookcatname ON books.cat_id = bookcatname.cat_id
GROUP BY category
Then in your php code you will use something like this:
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'('.$category['cnt'].')<br />';
}
EDIT
You will add this code to where you load the categories.
Related
This question already has answers here:
How to join two tables mysql?
(4 answers)
Closed 2 years ago.
I have two tables that looks something like this (made as example):
Table sales:
| ID | date | displayname | status |
| 1 | 2020/08/03 16:25:26 | Angel | OK |
| 2 | 2020/08/03 16:25:26 | Angel | OK |
| 3 | 2020/08/03 16:25:26 | Cabil | X |
| 4 | 2020/08/03 16:25:26 | Syed | OK |
...
Table users (all of the columns has value, but removed for GDPR reasons):
| ID | displayname | fullname | email |
| 1 | Angel | | |
| 2 | Nico | | |
| 3 | Raquie | | |
| 4 | Cabil | | |
| 5 | Syed | | |
...
I have a PHP script that looks like this:
<?php
$query = "SELECT * FROM sales WHERE status='OK' ORDER BY STR_TO_DATE(`date`, '%Y/%m/%d %H:%i:%s') DESC LIMIT 5";
if ($result = $link->query($query)) {
$num_rows = 0;
while ($row = $result->fetch_assoc()) {
$num_rows++;
echo '<div class="my-box">';
echo "{$row['id']}";
echo "{$row['date']}";
echo "{$row['dbirth']}";
echo "{$row['email']}";
echo "{$row['displayname']}";
echo '</div>';
}
$result->free();
}
?>
Now it currently displays each displayname for each sale in echo "{$row['displayname']}";, but insted of the displayname, I want to show the fullname for the user that has the current display name. How can I accomplish this?
You seem to be looking for a join:
select s.*, u.fullname
from sales s
inner join users u on u.displayname = u.displayname
This is my table position:
+----+---------+------+--------+---------+
| id | teacher | cook | doctor | dentist |
+----+---------+------+--------+---------+
| 1 | 3 | 4 | 2 | 1 |
+----+---------+------+--------+---------+
And this is my table people:
+----+-----------+--------+-----+
| id | firstname | name | age |
+----+-----------+--------+-----+
| 1 | Fred | Miller | 42 |
| 2 | Emily | Rose | 32 |
| 3 | Ben | Harper | 38 |
| 4 | Samanta | Jones | 35 |
+----+-----------+--------+-----+
My request from the mySQL database
$pdo = $db->query('
SELECT *, position.id AS id, people.id AS people_id
FROM position
LEFT JOIN people
ON position.teacher=people.id;
ON position.cook=people.id;
ON position.doctor=people.id;
ON position.dentist=people.id;
');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "The teacher is "$row['firstname']." ".$row['name'];
echo "The cook is "$row['firstname']." ".$row['name'];
echo "The doctor is "$row['firstname']." ".$row['name'];
echo "The dentist is "$row['firstname']." ".$row['name'];
}
My result is:
The teacher is Ben Harper
The cook is Ben Harper
The doctor is Ben Harper
The dentist is Ben Harper
The result I need:
The teacher is Ben Harper
The cook is Samanta Jones
The doctor is Emiliy Rose
The dentist is Fred Miller
It will be better if you restructure your table.
+----+------------+
| id | position |
+----+------------|
| 1 | teacher |
| 2 | cook |
| 3 | doctor |
| 4 | dentist |
+----+------------+
+----+-----------+--------+-----+-------------+
| id | firstname | name | age | position_id |
+----+-----------+--------+-----+-------------+
| 1 | Fred | Miller | 42 | 4 |
| 2 | Emily | Rose | 32 | 3 |
| 3 | Ben | Harper | 38 | 1 |
| 4 | Samanta | Jones | 35 | 2 |
+----+-----------+--------+-----+-------------+
Here you can have a foreign key reference on people.position_id and position.id.
This way you can have many people with same position.
SELECT position.id id
, people.id people_id
, people.firstname
, people.name
FROM position
LEFT
JOIN people
ON people.position_id = position.id;
As noted in comments and answers above, if you can restructure your table, you absolutely should -- as others have mentioned, it's better to restructure it to have that extra column, and then your query will be both simpler and much more efficient. But if you're stuck in a position where you can't (and if you only have a SMALL amount of data as presented, so that the inefficiency of this isn't too much of a concern), then you could use a UNION to glue several simple queries together :
Select position.id, firstname, lastname, 'cook' AS position
FROM position LEFT JOIN people ON position.cook = people.id
UNION
Select position.id, firstname, lastname, 'teacher' AS position
FROM position LEFT JOIN people ON position.teacher = people.id
UNION
...
Again, this is NOT an efficient approach -- you should restructure your data if you can. But if you can't for whatever reason, then this would get you back the data you need in a set of rows that pulls back what you need.
Try this,
$pdo = $db->query('
SELECT *, position.id AS id, people.id AS people_id,
(case when position.teacher <> '' then 'teacher'
when position.cook <> '' then 'cook'
when position.doctor <> '' then 'doctor'
when position.dentist <> '' then 'dentist') position_name
FROM position
LEFT JOIN people
ON position.teacher=people.id;
ON position.cook=people.id;
ON position.doctor=people.id;
ON position.dentist=people.id;
');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "The ".$row['position_name']." is "$row['firstname']." ".$row['name'];
}
I have two tables in my mySQL database:
table "animals":
| animal | name |
|:-----------|------------:|
| cat | Tom |
| dog | |
table "orders":
| id | animal |
|:-----------|------------:|
| 1 | cat |
| 2 | dog |
At first I select from the table "orders" the following data:
<?php
$pdo = Database::connect();
$sql = 'SELECT * FROM orders ORDER BY id ASC';
foreach ($pdo->query($sql) as $row) {
echo ('<td>a:'.$row['id'].'</td>');
echo ('<td>b:'.$row['animal'].'</td>');
echo ('<td>c:'.$row['animal'].'</td>');
}
Database::disconnect();
?>
Now I want to check if in my mySQL table "animal" the animal has a name. If yes print at position b the name. If there is no name print the animal:
| a:1 | b:Tom | c:cat |
| a:2 | b:dog | c:dog |
Thank you for your answers! I tried to work now with the answer of Jayo2k. I need to do a little change in my question, I found out I did a little mistake. So here I try to describe what I need as specific as possible:
table "animals":
| name | animal |
|:-----------|------------:|
| Tom | cat |
| Jerry | dog |
| Alfred | duck |
| Sam | |
| Donald | |
table "orders":
| id | animal |
|:-----------|------------:|
| 1 | cat |
| 2 | dog |
| 3 | duck |
| 4 | frog |
| 5 | pig |
With the following code from Jayo2k...
<?php
$pdo = Database::connect();
$sql = "SELECT * FROM animals, orders WHERE orders.animal = animals.animal";
foreach ($pdo->query($sql) as $row) {
echo '<tr> ';
echo('<td>a:'.$row['id'].' </td>');
echo('<td>a:'.$row['animal'].' </td>');
echo('<td>b:'.$row['name'].' </td>');
echo '</tr> ';
}
Database::disconnect();
?>
... I get this result:
| a:1 | b:cat | c:Tom |
| a:2 | b:dog | c:Jerry |
| a:3 | b:duck | c:Alfred |
But what I need is:
| a:1 | b:cat | c:Tom |
| a:2 | b:dog | c:Jerry |
| a:3 | b:duck | c:Alfred |
| a:4 | b:frog | c:frog |
| a:5 | b:pig | c:pig |
You can use LEFT JOIN, and use the IF condition to check the value is not empty, along with IFNULL, that will make null values in columns to blank.
SELECT O.id, IF(IFNULL(A.name, '') = '', A.animal, A.name) name, A.animal
FROM orders O
LEFT JOIN animals A
ON O.animal = A.animal
ORDER BY O.id DESC
What I do is (I am using PDO):
SELECT * FROM animal, orders WHERE orders.animal = animals.animal
It will select both animals and orders table and joint the animal row from orders with the animal row from animal.
you should get an array like this
[0] =>
id = 1
name = tom
animal = cat
[1] =>
id = 2
name =
animal = dog
Now up to you to do all the modification you want
I'm very new to php and database programs but trying to learn the language and develop a system for my library. I have a database called booksdb and two tables called "books" which contains titles of books and author and bookcatname which contains categories of books with a unique Category ID.
What I want to do is, display all categories on the page and when one category link is clicked, I want to see the names of books and authors under that particular category displayed on another page,
Example:
Art;
Color and Light by James Gurney
The Art Spirit by Robert Henry
How Pictures Work by David Bayles
Imaginative Realism by James Gurney
Here is my code but it does not work.
<?php
$dbh=mysql_connect("localhost","root","root") or die ('Cannot connedt to the Database' .mysql_errno());
mysql_select_db("booksdb");
//$res = "SELECT * FROM bookstable GROUP BY category ORDER BY category ASC";
$res = "SELECT * FROM bookcatname ORDER BY category ASC";
$res_query = mysql_query($res) or die (mysql_error());
$ra = mysql_fetch_assoc($res_query);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Select a Company</title>
</head>
<body>
<?php do { ?>
<p><?php echo $ra['category']; ?></p>
<?php } while ($ra = mysql_fetch_assoc($res_query))?>
</body>
</html>
1.Table name - bookcatname
+----+--------+----------+
| id | cat_id | category |
+----+--------+----------+
| 1 | 1 | Art |
| 2 | 2 | Drama |
| 3 | 3 | Music |
| 4 | 4 | Fiction |
| 5 | 5 | Computer |
+----+--------+----------+
2.Table name - books
+----+--------+---------------------------------+-----------------------+
| id | cat_id | title | author |
+----+--------+---------------------------------+-----------------------+
| 1 | 1 | Color and Light | James Gurney |
| 2 | 1 | The Art Spirit | Robert Henry |
| 3 | 1 | Art & Fear | David Bayles |
| 4 | 1 | How Pictures Work | Molly Bang |
| 5 | 1 | Imaginative Realism | James Gurney |
| 6 | 2 | A Walk To Remember | Nicholas Sparks |
| 7 | 2 | An Old Fashioned Girl | Louisa May Alcott |
| 8 | 3 | The Rest Is Noise | Alex Ross |
| 9 | 3 | It Still Moves | Amanda Petrusich |
| 10 | 3 | Chronicles | Bob Dylan |
| 11 | 3 | Dream Boogie | Peter Guralnick |
| 12 | 3 | Escaping The Delta | Robert Johnson |
| 13 | 4 | Atlas Shrugged | Ayn Rand |
| 14 | 4 | Anthem | Ayn Rand |
| 15 | 4 | Sons and Lovers | D.H. Lawrence |
| 16 | 4 | Henderson the Rain King | Saul Bellow |
| 17 | 5 | The Art of Computer Programming | Donald Knuth |
| 18 | 5 | The Art of Unix Programming | Eric Raymond |
| 19 | 5 | Free Software, Free Society | Richard M. Stallman |
| 20 | 5 | Database System Concepts | Abraham Silberschatz |
| 21 | 5 | 3ds Max 2008 in Simple Steps | Kognet Solutions Inc. |
+----+--------+---------------------------------+-----------------------+
Your current code to show categories don't work cause your using :
$ra = mysql_fetch_assoc($res_query);
and after you do it again in a loop :
while ($ra = mysql_fetch_assoc($res_query)
Do only one while() to get categories :
$getCategories = mysql_query("SELECT * FROM bookcatname ORDER BY category ASC");
while ($category = mysql_fetch_assoc($res_query) )
{
echo ''.$category['category'].'';
}
Now, you will need another page to get books from this category (or you can do it in same page).
books.php
// Same stuff here to connect database
// you check if a category is sent, else you redirect to categories page.
if ( empty($_GET['cat_id']) )
{
header('Location: index.php');
exit();
}
// Now you get books from category
// intval() convert to number
$getBooks = mysql_query("SELECT * FROM books WHERE cat_id = '".intval($_GET['cat_id'])."'");
echo '<ul>';
while ( $book = mysql_fetch_assoc($getBooks) )
{
echo '<li>'.$book['title'].' by '.$book['author'].'</li>';
}
echo '</ul>';
I have tables illustrated below
//reference type table
+---+-----------+---------+
|ID |Article_ID |Ref_Types|
+---+-----------+---------+
| 1 | 1 | article |
| 2 | 1 | book |
| 3 | 1 | article |
| 4 | 1 | article |
| 5 | 2 | book |
+---+-----------+---------+
//book references table
+---+-----------+--------+
|ID |Article_ID |Title |
+---+-----------+--------+
| 1 | 1 | book1 |
| 2 | 1 | book2 |
| 3 | 2 | book3 |
| 4 | 2 | book4 |
| 5 | 2 | book5 |
+---+-----------+--------+
//article references table
+---+-----------+-----------+
|ID |Article_ID |Title |
+---+-----------+-----------+
| 1 | 1 | article1 |
| 2 | 1 | article2 |
| 3 | 2 | article3 |
| 4 | 2 | article4 |
| 5 | 2 | article5 |
+---+-----------+-----------+
I have to look into first table and check the reference, of which type it is;
for each reference type, I have get reference table from related table
I have to output in order, as shown in table one.
1:
$data=array();
$sql=mysql_query("SELECT * FROM reftypes
WHERE Article_ID=1 ORDER BY ID ASC");
while($row = mysql_fetch_array($sql)){
$data[]=$row[2]; // i store in an array so that i can use later..
}
2:
foreach ($data as $ref) {
$counter=1;
switch ($ref) {
case "article":
$sqlarticle= mysql_query("SELECT Title
FROM book WHERE Article_ID=1 ORDER BY ID ASC");
echo mysql_result($sqlarticle, $counter); //i want to get only one out of book table
$counter++;
break;
...
...
But $sqlarticle does not seem to work.
I want to display as:
+-----------+----------+
|Article_ID |Reference |
+-----------+----------+
| 1 | article1 |
| 1 | book1 |
| 1 | article2 |
| 1 | article3 |
+-----------+----------+
I know it is a long question and for experts or experienced people it is very trivial, but that is where I'm stuck.
SELECT
*
FROM
reftypes R
WHERE
Article_ID=your_id
LEFT JOIN books B ON (B.Article_ID = R.Article_ID AND R.Ref_Types = 'book')
LEFT JOIN articles A ON (A.Article_ID = R.Article_ID AND R.Ref_Types = 'article')
ORDER BY
R.id ASC;
Even if the database is wrongly modeled, I think.
What about the followin model instead?
""although especially question owners should respect any kind of effort and input, -i am thankful- i can not understand why some people try to think of question's holder as well-informed or experienced as themselves, or worse comment from higher level. ""
anyway, my question was about to get values one by one, here is how i did it;
$data=array();
$sql=mysql_query("SELECT * FROM reftypes
WHERE Article_ID=1 ORDER BY ID ASC");
while($row = mysql_fetch_array($sql)){
$data[]=$row[2]; // i store in an array so that i can use later..
}
$articlecount=0;
$bookcount=0;
foreach ($data as $value) {
switch ($value) {
case "article":
$sqlarticle=mysql_query("SELECT RefArticleTitle
FROM ref_article
WHERE $article_ID=Article_ID
ORDER BY ID ASC");
$articles= mysql_result($sqlarticle, $articlecount);
echo $articles;
echo "\n";
$articlecount++;
break;
case "book":
$sqlbook=mysql_query("SELECT RefBookName
FROM ref_book
WHERE $article_ID=Article_ID
ORDER BY ID ASC");
$books= mysql_result($sqlbook, $bookcount);
echo $books;
echo "\n";
$bookcount++;
break;
...
...
as a result, i got what i required..
+-----------+----------+
|Article_ID |Reference |
+-----------+----------+
| 1 | article1 |
| 1 | book1 |
| 1 | article2 |
| 1 | article3 |
+-----------+----------+
thanks to whoever interested in the topic..
$result=mysqli_query("select ref_types from reference type");
while($row=mysqli_fetch_array($result))
{
$table=$row[0];
$result1=mysqli_query("select * from $table");
while($row1=mysqli_fetch_array($result1))
{
var_dump($row1);
}
}