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>';
Related
I'm new to the QueryBuilder and I'm trying to do a POST request (with a JSON) to retrieve some informations in my database.
I'm using array because each property can have several values. Here's the JSON I'm currently sending :
{
"name":["Martin"],
"state":["Ohio", "Texas"],
"job":["Photographer", "Reporter"]
}
Here's my database :
ID | NAME | FIRST_NAME | STATE | JOB | SPEAK_FRENCH
1 | Martin | John | Ohio | Photographer | 1
2 | Martin | Max | Ohio | Reporter | 1
3 | Martin | Sophie | Texas | Model | 1
4 | Alexander | David | Kansas | Author | 0
5 | Archie | Kira | Maine | Photographer | 1
6 | Lushen | Albert | Nevada | Pilot, Model | 1
7 | Wilkins | Minnie | Utah | Tailor | 0
8 | Martin | Thomas | Texas | Reporter | 1
9 | Patino | Stephen | Virginia | Pilot, Reporter | 1
10 | Ting | Maria | Nevada | Dentist | 0
11 | Brown | Barbara | Virginia | Reporter | 1
12 | Martin | William | Texas | Photographer | 1
13 | Zachary | Thomas | Virginia | Telephonist | 1
The request I would like to have :
SELECT * FROM 'application'
WHERE SPEAK_FRENCH = 1
AND NAME = "Martin"
AND STATE = "Ohio"
AND JOB LIKE "%Photographer%"
OR SPEAK_FRENCH = 1
AND NAME = "Martin"
AND STATE = "Ohio"
AND JOB LIKE "%Reporter%"
OR SPEAK_FRENCH = 1
AND NAME = "Martin"
AND STATE = "Texas"
AND JOB LIKE "%Photographer%"
OR SPEAK_FRENCH = 1
AND NAME = "Martin"
AND STATE = "Texas"
AND JOB LIKE "%Reporter%"
And what I have currently done in Symfony, doesn't work the way I want it to :
$repository = $this->getDoctrine()->getRepository(Application::class);
$query = $repository->createQueryBuilder('request');
$temp_name = 0;
$temp_state = 0;
$temp_job = 0;
foreach ($app->getName() as $name) {
$temp_name = $temp_name + 1;
$query = $query->orWhere('request.speakFrench = 1')
->andWhere('request.name LIKE :JSONname' . strval($temp_name))
->setParameter('JSONname' . strval($temp_name), $name);
foreach ($app->getState() as $state) {
$temp_state = $temp_state + 1;
$query = $query->andWhere('request.state LIKE :JSONstate' . strval($temp_state))
->setParameter('JSONstate' . strval($temp_state), $state);
foreach ($app->getJob() as $job) {
$temp_job = $temp_job + 1;
$query = $query->andWhere('request.job LIKE :JSONjob' . strval($temp_job))
->setParameter('JSONjob' . strval($temp_job), '%' . $job . '%');
}
}
}
My goal is to get this result :
ID | NAME | FIRST_NAME | STATE | JOB | SPEAK_FRENCH
1 | Martin | John | Ohio | Photographer | 1
2 | Martin | Max | Ohio | Reporter | 1
8 | Martin | Thomas | Texas | Reporter | 1
12 | Martin | William | Texas | Photographer | 1
My code isn't working well, it doesn't send any error but only return ID : 8.
I'm looking for a way to do the query that returns only the ID : 1, 2, 8 and 12.
Thanks a lot for your future answers.
P.S : I'm running Symfony 4.3.11.
With Doctrine you can do for exemple:
$queryBuilder = $this->createQueryBuilder('request');
$queryBuilder
->andWhere($queryBuilder->expr()->andX(
$queryBuilder->expr()->eq('user.speakFrench', ':speakFrench'),
$queryBuilder->expr()->like('request.name', ':name'),
$queryBuilder->expr()->in('request.state', ':states'),
$queryBuilder->expr()->in('request.job', ':jobs'),
))
->setParameter('speakFrench', true)
->setParameter('name', 'Martin')
->setParameter('states', ['Ohio', 'Texas'])
->setParameter('jobs', ['Photographer', 'Reporter'])
->getQuery()
->getResult();
That should be a good start.
To continue:
Many examples of Doctrine usage: Hot examples
Check Doctrine\ORM\Query\Expr class, there's a lot of useful functions. Doctrine Expr GitHub
Check the documentation that provides many examples: Doctrine Query Builder
The following would appear to be a valid query corresponding to your requirements:
SELECT *
FROM application
WHERE SPEAK_FRENCH = 1
AND NAME = "Martin"
AND STATE = IN("Ohio","Texas")
AND (JOB LIKE "%Photographer%" OR JOB LIKE "%Reporter%");
Also, see Is storing a delimited list in a database column really that bad?
I have 2 tables, the 'department' and 'document'.
Table department
| doc_id | dept_name |
----------------------------------
| 1 | Information Technology|
| 2 | Software Development |
| 3 | Human Resource |
| 4 | Accounting |
| 5 | Support |
Table document
| doc_id | doc_name | author | description | department |
----------------------------------------------------------------------------
| 1 | Maps | User1 | sample | Information Technology |
| 2 | Audits | User3 | sample | Software Development |
| 3 | Image | User1 | sample | Information Technology |
| 4 | Papers | User4 | sample | Human Resource |
| 5 | Print Screen| User1 | sample | Software Development |
| 6 | Transaction | User3 | sample | Accounting |
| 7 | Graph | User1 | sample | Support |
| 8 | Excel | User1 | sample | Information Technology |
Now, I want to display the table with two columns: department and total_doc.
Output:
| department |total_doc|
-----------------------------------
| Information Technology| 3 |
| Software Development | 2 |
| Human Resource | 1 |
| Accounting | 1 |
| Support | 1 |
I want to display the total document inside the department and arrange them in ascending order.
Here's my query.(not sure)
SELECT department, count(doc_name) as 'total_doc' FROM tbl_document GROUP BY doc_name
I'm using MVC pattern in Codeigniter.
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('doc_name');
Also, How can I display this in table? like using foreach in html?
You need to do group by with department not with doc_name.
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('department');
$result = $this->db->get()->result();
Hope This will help you.
foreach ($result as $row)
{
echo $row->department."----".$row->total_doc;
}
here you go
SELECT dept_name,COUNT(td.department) FROM department d
LEFT JOIN tdocument td ON td.`department`=d.`dept_name`
GROUP BY td.`department` ORDER BY COUNT(td.`department`) DESC;
You want one line per department. IN SQL words: You want to group by department.
select department, count(*) as total_doc from document group by department;
(BTW: don't use single quotes for column aliases.)
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.
I am trying something here, I want to make a condition that allows me to fetch an info from a row in a Mysql if the page title is the same with a value from table "names"/column "lastname". Here I had made a table "names"
The "firstname" column would be unique in this table.
+---------+-----------+----------+
| id | firstname | lastname |
+---------+-----------+----------+
| 1 | John | Smith |
| 2 | Jane | Smith |
| 3 | Jimbo | Jones |
| 4 | Andy | Smith |
| 7 | Chris | Jones |
| 45 | Anna | Bell |
| 44 | Jimmy | Carr |
| 43 | Albert | Smith |
| 47 | Johnna | Doe |
+---------+-----------+----------+
If the page name is equal to "Jimbo" than display "Jones" else error text (but still showing) or so. I don't know if this way good is while I don't have any ideeas anymore.
The code that i am using so far:
<?php echo get_the_title($ID); ?>
- for fetching the title -
<?php
$result = mysql_query("SELECT lastname FROM names WHERE id = '2'");
if (!$result) {
echo 'error:bla ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 2
echo $row[1]; //
?>
For fetching the row -
In Wordpress I am using PHP code for posts and pages (I can make a shortcode).
http://codex.wordpress.org/Class_Reference/wpdb
global $wpdb;
$result = $wpdb->get_row("SELECT * FROM names WHERE id='2' ");
if($result){
echo $result->lastname;
}
+-------+------+-----------+------------+
|user_id| name | parent_id |grandparentID
+----+--------+-----------+-------------+
| 1 | one | NULL | NULL |
| 2 | two | 1 | NULL |
| 3 | three | 1 | 1 |
| 4 | four | 2 | 1 |
| 5 | five | 2 | 2 |
| 6 | six | 2 | 2 |
| 7 | seven | 2 | 2 |
| 8 | eight | 3 | 3 |
| 9 | nine | 3 | 2 |
| 10 | ten | 3 | 1 |
| 11 | eleven | 3 | 2 |
+-------------+-----------+------------+
I want to create a tree structure with the following DB schema
Something like this below
One
|
two______________three______________four______________five______________Six
| | | | |
n1 n2 n3 n4 n5 t1 t2 t3 t4 t5 h1 h2 h3 h4 h4 a1 a2 a3 a4 a5 s1 s2 s3 s4 s5
I wrote the following code
<?php
function display_tree() {
$result = $this->qry("SELECT * FROM users WHERE Parent='?' or Parent ='?';" ,
'in(select id from user_id from users where Parent = "'.$_SESSION['id'].'")', $_SESSION['id']);
echo '<div align="center">'.$_SESSION['name'].'<br></div>';
echo '<div align="center">|</div>';
echo '<div align="center">';
while( $row=mysql_fetch_assoc($result)){
echo "___".$row['name'].$row['user_id'].'';
};
$result1 = $this->qry("SELECT * FROM users where grandParent='".$_SESSION['id']."'");
echo '<br>|<br>';
while( $row1 =mysql_fetch_assoc($result1)){
echo "--".$row1['name'];
}
echo '</div>';
}
?>
This is what it displays
one
|
___two___three
|
--four--five--six--seven--eight--
But I wish to have it in the order up above, not this,
I have read tutorials but they all dwell on right left branching, none seems to touch on my type
Any links to good examples, I'll be glad
Any insight on my problem would also help me alot
I seem to have reached a fix end for me
Thanks in advance.
I would recommend using some kind of plugin like jquery plugin that would build the tree for you here are couple of plugins.
http://jquery.bassistance.de/treeview/demo/
http://www.jqwidgets.com/jquery-widgets-demo/#demos/jqxtree/treebindingtojson.htm
https://github.com/pioz/jquery-tree