I have menu that displays entries using php and mysql. What I'm trying to do is to get a list of products that equal clothing for example then shoes and so on. Theirs about 4 main types, this value can't be changed.
So:
$query = mysql_query("SELECT * FROM products WHERE type = 'Clothing'")or die(mysql_error());
Instead of looping through I'll just repeat the process 4 times.
After this I want to display each main category and sub category for each type of clothing with the products table, so that it displays like this.
Clothing
Main Category 1
(1)Sub 1
(35)Sub 2
(4)Sub 3
Main Category 2
(1)Sub 1
(35)Sub 2
(4)Sub 3
Shoes
Main Category 1
(1)Sub 1
(35)Sub 2
(4)Sub 3
Main Category 2
(1)Sub 1
(35)Sub 2
(4)Sub 3
And so on
I get a list of each main catogroy in the DB form a different table and loop through
$get_cats = mysql_query("SELECT * FROM main_cats")or die(mysql_error());
//loop through each
while($main_cat = mysql_fetch_assoc($get_cats)){
//count main cat in products
$check = mysql_real_escape_string($main_cat['cat']);
$p_main_count = mysql_query("SELECT * FROM products WHERE cats = '$check' ORDER BY cats")or die(mysql_error());
//this would get an array of each product that has that main category
}
This looks all well and good but I can't think of a way how to display the data in the format I need it.
The products table has 3 main columns for this:
type
cats (main category)
sub cats (contains string 1,2,4 of multiple sub categorys)
Is there a way selecting and groups each main category and then displaying and counting the sub category's for each main category.
W3Schools has a really good tutorial for counting and displaying MySql Database entries. Here's a snippet of how you could try to display the Data in a table.
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM main_cats");
while($row = mysqli_fetch_array($result))
{
echo $row['type'] . " " . $row['cats'] . " " . $row['subcats'];
echo "<br>";
}
?>
Lets say row 1 has the data Type: 1 Cats: 2 SubCats: 3
and row 2 has the data Type:2 Cats: 4 SubCats: 6
This would output the data like this
1 2 3
2 4 6
You can easily use the tables from HTML to make this look alot nicer.
echo "<table border="1">";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['type'] . "</td><td> " . $row['cats'] . "</td><td> " . $row['subcats'] . "</td>";
echo "</tr>";
}
echo "</table>";
This would output in the same order but in a table.
Hope this helps. Also if you want any good references http://w3schools.com is a very good website.
Related
well, I have 2 Mysql table which structure is bellow :
Table Jobs
job_id---job_cat_id---job_title---job_description---job_data----is_active
=========================================================================
1 1 title 1 description 1 2016-05-06 1
2 2 title 2 description 2 2016-05-06 0
3 2 title 3 description 3 2016-05-06 1
Table job_details
job_cat_id---job_cat_name
=========================
1 cat name 1
2 cat name 2
3 cat name 3
Now I want to show all jobs under each category from jobs table. E.g
What I need to show :
Job Category 1
1. job 1 from category 1
2. Job 2 from category 1
Job Category 2
1. Job 3 from category 2
So to do this I am using following sql query but can't get the correct result :
$get_job = mysqli_query($conn, "SELECT jobs.job_id, jobs.job_title, job_category.job_cat_name FROM jobs LEFT JOIN job_category ON job_category.job_cat_id = jobs.job_cat_id WHERE jobs.is_active = '1' ");
while($result = mysqli_fetch_array($get_job) ) {
$job_id = (int) $result['job_id'];
$job_title = htmlspecialchars($result['job_title']);
$job_category = htmlspecialchars($result['job_cat_name']);
echo "<h4>$job_category</h4>";
echo "<p>$job_title</p>";
}
Now, It's showing me all category with all jobs but I want to show all jobs under each category.
What is showing now :
Job Category 1
1. job 1 from category 1
Job Category 1
1. Job 2 from category 1
Job Category 2
1. Job 3 from category 2
First we have to remember that the result from a SELECT query is a newly generated table. It is not a multi dimensional array. If it were a multidimensional array, then you could get away with printing the job category at the beginning of each new array which could be grouping up all the jobs in a single category, however since this is not the type of result obtained by the SQL SELECT QUERY, you are printing the job category after each line:
echo "<h4>$job_category</h4>";
echo "<p>$job_title</p>";
Solution:
A solution to your problem would be to first use the ORBER BY ASC in your sql query:
$get_job = mysqli_query($conn, "SELECT jobs.job_id, jobs.job_title, job_category.job_cat_name FROM jobs LEFT JOIN job_category ON job_category.job_cat_id = jobs.job_cat_id WHERE jobs.is_active = '1' ORDER BY job_cat_id ASC");
From there, you know that the jobs in each category should at least be grouped up next to each other (from lowest to highest like 1,1,1,1,2,2,3,3,3). What you can now do is have a conditional print the $job_category if AND ONLY IF it hasn't been printed already previously.
Change this line:
echo "<h4>$job_category</h4>";
into this line:
if ($previous_print != $job_category)
{
echo "<h4>$job_category</h4>";
$previous_print = $job_category;
}
Let me know if it works now.
Another solution may be if you just run one query using group by job_cat_id and then inside loop write another query to get desired result with where clause job_cat_id .
You need to do 2 queries here. Here's an exmaple code, might need some tweaks acording to your table column names:
<?php
$query = "SELECT `job_cat_id`, `job_cat_name`, COUNT(`jobs`.`id`) as `jobs`
FROM `job_category`
GROUP BY `job_cat_id`";
$get_cat = mysqli_query($conn, $query);
$cats = [];
while($result = mysqli_fetch_array($get_cat) ) {
$result['jobs'] = [];
$cats[$result['job_cat_id']] = $result;
}
$get_job = mysqli_query($conn, "SELECT jobs.job_id, jobs.job_title, jobs.job_cat_id FROM jobs WHERE jobs.is_active = '1' AND `job_cat_id` IN (" . implode(',', array_keys($cats)) . ")");
while($result = mysqli_fetch_array($get_job) ) {
$cats[$result['job_cat_id']][] = $result;
}
foreach ($cats as $cat) {
$job_category = htmlspecialchars($cat['job_cat_name']);
echo "<h4>$job_category</h4>";
foreach ($cat['jobs'] as $job) {
$job_title = htmlspecialchars($job['job_title']);
echo "<p>$job_title</p>";
}
}
I have the following table:
news(id,cat_id,headline,sub_top_priority)
I create drag and drop sortable list.
It change the sub_top_priority column order in database.
But i need this to change order of sub_top_priority column according to category.
for example.
Database has 6 rows
id cat_id headline sub_top_priority
1 15 good 1
2 15 Bad 2
3 15 Nice 3
4 15 Fine 1
5 16 Test1 2
6 16 Test2 3
if I Drag the second row and drop on first row then it only change order of category = 15 not of category = 16. category 16 sub_top_priority column remains as it is.
plz help me to make update and plz suggest what should i change in code...to update sub_top_priority column order according to cat_id.
I Try to change id with cat_id but this change all category in same sequence.
<?php
while ($sub_top = mysql_fetch_array($sub_top_select))
{
?>
<li id="recordsArray1_<?php echo $sub_top['id']; ?>"> <?php echo $sub_top['category_name']; ?> : <?php echo $sub_top['headline']; ?></li>
<?php } ?>
<?php
if(isset($_POST['change']))
{
$change = mysql_real_escape_string($_POST['change']);
$updateRecordsArray1 = $_POST['recordsArray1'];
if ($change == "updatesubtop")
{
$listingCounter1 = 1;
foreach ($updateRecordsArray1 as $recordIDValue1)
{
$query1 = "UPDATE news SET sub_top_priority = " . $listingCounter1 . " WHERE id = " . $recordIDValue1;
mysql_query($query1) or die($query1."<br/><br/>".mysql_error());
$listingCounter1 = $listingCounter1 + 1;
}
}
}
?>
Hi I want to create Categories listed which are saved in my database so when user upload his images and he select the category it saves the data in database in Cat column
Now I want to show category in PHP like this
Categories Total
Animals (4)
Celebrations (2)
Locations And Travel (11)
Object or still life (1)
Transportation (9)
Here is my PHP I am succeeded to show Categories names but not total category in each category
<?php
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"Select Cat from save_data Group By Cat ")
or die(mysql_error());
echo "<table border='1'>
<tr>
<th>Categories</th>
<th>Total</th>
</tr>";
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['Cat'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Extend the table cell:
<td colspan="2"></td>
This way it extends over another cell.
Also I notice you are mixing mysqli and mysql:
or die(mysql_error());
Try to use mysqli as objects and \Exceptions instead of errors. It's worth learning about :-)
Update:
I did not understand your question at first. Please provide your schema so we can see your table structure.
Usually you would have 2 tables, one with categories and one with data and join them with a GROUP BY (if an item can be in several categories, you would have a third table like category_has_item!):
SELECT c.category AS cat,
COUNT(i.items) AS num
FROM category c
LEFT JOIN items i
ON c.category_id = i.category_id
GROUP BY c.category
Use LEFT JOIN to display empty categories and JOIN (without LEFT) to avoid empty categories.
Change your table echo:
echo "<td>" . $row['cat'] . "</td><td>(" . $row['num'] . ")</td>";
Update:
If you only have 1 table, I strongly suggest you to read about database normalization.
Update your query:
Select Cat,COUNT(Data) AS num from save_data Group By Cat
Replace Data by your data column
and your echo line:
echo "<td>" . $row['Cat'] . "</td><td>(" . $row['num'] . ")</td>";
try to change your sql query like this
SELECT count(*) AS total_count FROM (SELECT Cat FROM save_data GROUP BY Cat HAVING COUNT(Cat) > 1) AS t
We have these two fields in our MySQL database:
in_model , in_color
And we are trying to count the total of model (in_model field), which has the same color (in_color field) in PHP with MySQL as backend database. We tried using the count() function, together with the group by. But it would seem we don't have achieve a desired result
This is our MySQL database:
$query = "SELECT in_model, COUNT(in_color) FROM in_newunit GROUP BY in_color,in_model";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)) {
echo "There are ". $row['COUNT(in_color)'] ."
". $row['in_model'] ." items.";
echo "<br />";
}
This is the output we are receiving
There are 1 C2I items.
There are 2 try items.
There are 2 try items.
There are 4 C2I items.
This is what we are trying to achieve
We are trying to have the color appear in the echo
There are 1 C2I Black items.
There are 2 try White items.
There are 2 try Black items.
There are 4 C2I White items.
I think this is straight enough. Try this.
$query = "SELECT in_model, in_color, count(*) AS counter FROM in_newunit GROUP BY in_model, in_color";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)) {
echo "There are ". $row['counter'] ." ". $row['in_model'] ." ".$row['in_color']." items.";
echo "<br />";
}
The query is actually the other way around:
SELECT in_color, count(*) FROM in_newunit
GROUP BY in_color
And you have actually said it yourself:
we are trying to count the total of model (in_model field), which has the same color (in_color field)
"count the total of model" > count(*)
"which has the same color" > for every color the previous count, which is a group by in_color
Also note that if you do count(in_model) you won't be counting values with in_model as null. If you do count(*) you will be counting the null values too. Up to you.
Update
So you want the amount of elements there are by (model, color) pair. Then this is the query:
SELECT in_model, in_color, count(*) FROM in_newunit
GROUP BY in_model, in_color
Eg:
model1 | black | 2
model1 | white | 1
model2 | black | 5
model3 | white | 4
I'm now hopeless about this problem and that's why I'm here. I'm kind of a starter in PHP and mysql programming. I searched for a solution on the web but I wasn't succeeded. I'm working on a project what is a car repairing administration system. This is a part of it that I need.
I have two tables:
repairs (j_id /this is the primary key/, rendszam, javitas, megjegyzes, datum)
and
pictures (kep_id /this is the primary key/, j_id /it's from repairs j_id/, kepnev)
I need to display a result in a table, where I can see that which of the repairs have a picture in the pictures table, but without redundancy, so I don't want multiple repair rows that are similar to eachother, but one repair row with multiple picture columns after it.
What I have done already:
<?php
$sql = "SELECT $tbl_name2.j_id, $tbl_name2.rendszam, $tbl_name2.javitas, $tbl_name2.megjegyzes, $tbl_name2.datum, $tbl_name3.kepnev FROM $tbl_name2, $tbl_name3 WHERE $tbl_name2.j_id=$tbl_name3.j_id";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "<tr><td>" . $row[$i] . "</td>";
echo "<td>" . $row[$i + 1] . "</td>";
echo "<td>" . $row[$i + 2] . "</td>";
echo "<td>" . $row[$i + 3] . "</td>";
echo "<td>" . $row[$i + 4] . "</td>";
echo "<td>" . $row[$i + 5] . "</td>";
}
?>
This one displays information like this:
repair id | picture
1 | fdgdfg.jpg
1 | fgdfg.jpg
1 | fghh.jpg
25 | dfg.jpg
25 | jkjk.jpg
But I don't want to have multiple repair rows but one repair row with multiple pictures after it.
I tried this:
$sql2="SELECT DISTINCT $tbl_name2.j_id, $tbl_name3.kepnev FROM $tbl_name2, $tbl_name3 WHERE $tbl_name2.j_id=$tbl_name3.j_id";
$result2=mysql_query($sql2) or die(mysql_error());
$sql="SELECT $tbl_name2.j_id, $tbl_name2.rendszam, $tbl_name2.javitas, $tbl_name2.megjegyzes, $tbl_name2.datum, $tbl_name3.kepnev FROM $tbl_name2, $tbl_name3 WHERE $tbl_name2.j_id=$tbl_name3.j_id GROUP BY j_id;
$result=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo "<tr><td>".$row[$i]."</td>";
echo "<td>".$row[$i+1]."</td>";
echo "<td>".$row[$i+2]."</td>";
echo "<td>".$row[$i+3]."</td>";
echo "<td>".$row[$i+4]."</td>";
echo "<td>".$row[$i+5]."</td>";
while($sor=mysql_fetch_array($result2))
{
if($sor['j_id']==$row[$i]){
echo "<td><a href=kepek/".$sor['kepnev']." target=_blank>".$sor['kepnev']."</a></td>";
}
}
}
The sql statement differs in the group by in $sql, but this one displays the results like this:
repair id | picture
1 | fdgdfg.jpg | fgdfg.jpg | fghh.jpg
25 |
So it's just not continuing after the first repair id, not showing the repair pictures for repair id 25.
I don't know, how can I get it right. I need a table which displays information like this:
repair id | picture
1 | fdgdfg.jpg | fgdfg.jpg | fghh.jpg
25 | dfg.jpg | jkjk.jpg
Could you help me out in this?
This sounds fairly straightforward, looks like you're off to a good start.
I've done something similar in the past, and I just used a variable to keep track of the current ID being displayed and the previously displayed ID. Here's a quick code sample to outline what I mean by that.
while($row=mysql_fetch_array($result))
{
$currentID=$row[$i];
if ($currentID != $lastID) {
echo "</tr><tr><td>".$row[$i]."</td>";
} else {
echo "<td>".$row[$i]."</td>";
}
$lastID=$row[$i];
}
So, the idea is to keep track of what the last ID was. In the next row, if the ID is the same, just output <td>"variable goes here"</td> to keep it on the same column. If the ID changed, end the row and create a new row using </tr><tr>". Feel free to comment if you need more help.