Category - Products [PHP , MySQL PDO] - php

This is my category & products SQL/PHP schema.
I need to echo the <hr> for each of my categories and not for each products.
This is my code :
$sql = $db->query("SELECT * from cat,products where cat.cat_id = products.cat_id order by products.cat_id desc");
while ($row = $sql->fetch(PDO::FETCH_ASSOC)){
$ID = $row["id"];
$Title = $row["title"];
$CatID = $row["cat_id"];
$row["cat_id"] = $row["cat_name"];
switch ($row["cat_id"]){
case $row["cat_id"] == $row["cat_name"]:
echo "<hr>";
break;
default:
break;
}
echo $row["cat_id"];
echo "<a href='test.php?cat=$CatID&prod=$ID'>$Title</a><br/>";
}
Image :
thanks and sorry for my poor English...

You can write the following due to the fact that your SQL statement is sorted by the categories:
$tmp_category = '';
$sql = $db->query("SELECT * from cat,products where cat.cat_id = products.cat_id order by products.cat_id desc");
while ($row = $sql->fetch(PDO::FETCH_ASSOC)){
$ID = $row["id"];
$Title = $row["title"];
$CatID = $row["cat_id"];
if ($row["cat_id"] <> $tmp_category){ //you can use != instead of <> as well
$tmp_category = $row["cat_id"];
echo "<hr>";
echo $row["cat_id"];
echo "<a href='test.php?cat=$CatID&prod=$ID'>$Title</a><br/>";
}
else
{
echo $row["cat_id"]; // this is optional, you can delete the cat ID from here and it will show you only the above link.
echo "<a href='test.php?cat=$CatID&prod=$ID'>$Title</a><br/>";
}
}

Related

Query dont want to show all related post from table

I try to retrive all rows related to the specific category(continent table) but it only shows one and not all.
<?php
$townid = $_GET['id'];
$query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";
$row = mysqli_fetch_assoc(mysqli_query($link, $query));
// The category/Continent
echo '<h1>';
echo $row['catname'];
echo '</h1>';
//The post name/Town name
echo $row['title'];
?>
You need to call mysqli_fetch_assoc() in a loop.
$result = mysqli_query($link, $query);
$first = true;
while ($row = mysqli_fetch_assoc($result)) {
if ($first) { // Only show the category header once.
// The category/Continent
echo '<h1>';
echo $row['catname'];
echo '</h1>';
$first = false;
}
//The post name/Town name
echo $row['title'];
}
You can do something like:
<?php
$townid = $_GET['id'];
$query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";
$rows = mysqli_fetch_all(mysqli_query($link, $query), MYSQLI_ASSOC);
// The category/Continent
foreach ($rows as $row) {
echo '<h1>';
echo $row['catname'];
echo '</h1>';
//The post name/Town name
echo $row['title'];
}
?>
On another note, its better to parameterised your query since you are getting the $townid from a GET params.
This is how to do it in PHP https://www.php.net/manual/en/mysqli-stmt.bind-param.php

paginate the list in php

i have this php code that fetches images from the database using the userid, then displays all the images in a list form. im trying to paginate the images, in a limit of 5 items per page. but the code is showing only the first page, without a link to the other pages. here's my php code
<?php
include 'connect.php';
$Category = " ";
$query = "SELECT Img_dir, Caption, Category FROM images WHERE Category = '". $_REQUEST['Category'] ."' AND user_id = '". $_SESSION['user_id'] ."' LIMIT 0,5";
$result = mysqli_query($conn,$query);
while ($row=mysqli_fetch_array($result)){
$image = $row["Img_dir"];
$Caption= $row["Caption"];
$Category = $row["Category"];
echo "<dl>";
echo "<dd>$Category &nbsp&nbsp <img src='base64_encode($image)' />&nbsp&nbsp $Caption<dd>";
echo "</dl>";
}
//number of total pages available
$results_per_page = 10;
$number_of_results = mysqli_num_rows($result);
echo $number_of_pages = ceil($number_of_results / $results_per_page);
echo "<br>"; echo "<br>";
for($r=1;$r<=$number_of_pages;$r++)
{
?><?php echo $r." "; ?><?php
}
?>
You can try this:
Change your query (use prepare statments):
$query = "SELECT Img_dir, Category FROM images WHERE user_id = ? AND Category = ? ";
As for the structure of your data.
$results = [];
while ($row = $result->fetch_assoc()){
$key = $row['Category'];
if(!isset($results[$key])) $results[$key] = [];
$results[$key][] = $row['Img_dir ']; //['Category' => [Img_dir,Img_dir, ...]]
}
And your HTML. I would use a description list or dl as it has a nice place for the title:
foreach($results as $Category => $image){
echo "<dl>";
echo "<dt>$Category</dt>";
foreach($data as $row){
echo "<dd><img src='base64_encode($image)' /><dd>";
}
echo "</dl>";
}
Untested.
The order will probably be all wanky, so you can use ksort on it. Simply
ksort($results);
Before the foreach loops.
Cheers.

How to display category and list

I'm new to php and mysql. I want to display the category and it's list. And I want it to happen like this. Please help me. I'm really stuck to it.
My Database table:
How it is now:
How I need it
Book
Math
Physics
Gadget
Cellphone
Laptop
Power Bank
My code:
$getitems = mysql_query("SELECT category,
name
FROM items_for_checking
WHERE status = 'approved' ");
$numrows = mysql_num_rows($getitems);
if($numrows > 0){
$row = mysql_fetch_assoc($getitems);
$category = $row['category'];
$name = $row['name'];
$last = $category;
echo "<div class='cat'>
<div class='cat-head'>
CATEGORY
</div>
<div class='main-cat'>
<li>$category<li>
<ul>
</div>
</div>
</div>";
while($row = mysql_fetch_assoc($getitems)){
$category = $row['category'];
$name = $row['name'];
if($last != $category){
echo "</ul><li>$category</li><ul>";
}
echo "<li>$name</li>";
$last = $category;
}
echo "</ul>";
}
get the unique category list of array,as like this
$row = mysql_fetch_assoc($getitems);
$uniqueCategory = array_unique($row['category']);
$uniqueCategoryCount=count($uniqueCategory);
for($i=0;$i< $uniqueCategoryCount;$i++)
{
echo "</ul><li>$uniqueCategory[$i]</li><ul>";
while($row = mysql_fetch_assoc($getitems)){
$category = $row['category'];
$name = $row['name'];
if($uniqueCategory[i]==$row['category']){
echo "<li>$name</li>";
}
}
}

Catgories didn't work

So I try to learn php and decided to make one site where I add images, save them in folder and id, name,type, path in mysql. Then show on page. So far I have upload form and I can upload and save images. Also I showing them successfully on the page.
Now I'm trying to make categories like - Nature, Funny ... etc. So I added one field in my main table -> img_category.
Also I madded second table - cats whit cat_id and cat_name fields. Using this to show the categories on the page:
<?php
$q = mysqli_query($con,"select * from cats");
while ($res = mysqli_fetch_assoc($q))
{
echo '<a href="pic.php?cat_id='. $res['cat_id'] .'">'.$res['cat_name'].'<br/>';
}
So now how can I make when I click on some category link to load images only from this category?
I have managed to make something like this but it doesn't work like is expected
<?php
$q = mysqli_query($con,"select * from cats");
while ($res = mysqli_fetch_assoc($q))
{
echo '<a href="pic.php?cat_id='. $res['cat_id'] .'">'.$res['cat_name'].'<br/>';
}
?>
<hr>
<?php
$cat_id = $_GET['cat_id'];
$query = "SELECT * FROM images JOIN cats ON images.img_category = cats.cat_id WHERE cats.cat_id = '$cat_id'";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
do {
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = $currid;
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"picture\">";
echo "<img style=\"width:100%;margin:0 auto;\" src=\"upload/".$line['name']."\" /></a><br />";
echo "<div id=\"caption\">".$line['caption']."</div><br />";
}
else echo "There is no images!\n";
if ($previd > -1) echo '<span>Prev</span>';
echo str_repeat(' ', 5);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
$query = "select * from images order by RAND() LIMIT 1";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
while ($row = mysqli_fetch_array($result, MYSQL_BOTH)){
echo 'Random';
}
echo str_repeat(' ', 5);
if ($line) echo '<span>Next</span> <br /><br />';
echo "</div>";
?>
The results are:
When there is image in the category is showed but and if I click on 'Next' button I get the same image.
If there is no image in the category I get all echoes like link whit the ID of last category for exam: There is no image like link and if I click it I get last category ID loaded. In my case I have 8 categories so ID=8.
Any help is appreciate!
Thank's
EDIT:
Ok this line:
echo '<span>Следваща</span>
Where is pic.php?cat_id=... i think is wrong. Here I must take next image ID not next category ID. But how to change it for image? If i make it pic.php?id=... I get empty page.
I don't understand it. I know that is messy code but is best I can do for now.
EDIT 2:
I've made something like this. Now can you help me how to make query's for next image because now didn't get next image and stay the same.
$cat_id = $_GET['cat_id'];
$cat_id = mysqli_real_escape_string($con, $cat_id);
$query = "SELECT * FROM images JOIN cats ON images.img_category = cats.cat_id WHERE cats.cat_id = '$cat_id'";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
$prevSQL = mysqli_query($con,"SELECT cat_id FROM cats WHERE cat_id < $cat_id ORDER BY cat_id DESC LIMIT 1") or die (mysqli_error($con));
$nextSQL = mysqli_query($con, "SELECT cat_id FROM cats WHERE cat_id > $cat_id ORDER BY cat_id ASC LIMIT 1") or die (mysqli_error($con));
$prevobj=mysqli_fetch_object($prevSQL);
$nextobj=mysqli_fetch_object($nextSQL);
$pc = mysqli_fetch_object(mysqli_query($con, "SELECT COUNT(cat_id) as pid FROM cats WHERE cat_id<$cat_id ORDER BY cat_id DESC")) or die (mysqli_error($con));
$nc = mysqli_fetch_object(mysqli_query($con, "SELECT COUNT(cat_id) as nid FROM cats WHERE cat_id>$cat_id ORDER BY cat_id ASC")) or die (mysqli_error($con));
$prev=$pc->pid>0 ? 'Prev |' : '';
$next=$nc->nid>0 ? 'Next' : '';
$row = mysqli_fetch_array($result);
echo "<div id=\"picture\">";
echo "<img src=\"upload/" . $row['name'] . "\" alt=\"\" /><br />";
echo $row['caption'] . "<br />";
echo "</p>";
echo $prev;
echo $next;
As you stated, I guess the error is with the line:
echo '<span>Следваща</span>
I think it should be:
echo '<span>Следваща</span>
EDIT:
Your code should look like:
<?php
$q = mysqli_query($con,"select * from cats");
while ($res = mysqli_fetch_assoc($q))
{
echo '<a href="pic.php?cat_id='. $res['cat_id'] .'">'.$res['cat_name'].'<br/>';
}
?>
<hr>
<?php
$cat_id = $_GET['cat_id'];
$query = "SELECT * FROM images JOIN cats ON images.img_category = cats.cat_id WHERE cats.cat_id = '$cat_id'";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
do {
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = $currid;
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"picture\">";
echo "<img style=\"width:100%;margin:0 auto;\" src=\"upload/".$line['name']."\" /></a><br />";
echo "<div id=\"caption\">".$line['caption']."</div><br />";
}
else echo "There is no images!\n";
if ($previd > -1) echo '<span>Prev</span>';
echo str_repeat(' ', 5);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
$query = "select * from images order by RAND() LIMIT 1";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
while ($row = mysqli_fetch_array($result, MYSQL_BOTH)){
echo 'Random';
}
echo str_repeat(' ', 5);
if ($line) echo '<span>Next</span> <br /><br />';
echo "</div>";
?>
Try this
<?php
if(isset($_GET['cat_id'])){
$cat_id = $_GET['cat_id'];
$query = "SELECT * FROM images WHERE img_category = '$cat_id'";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
$previous_ids = array();
do {
$previous_ids[] = $line[0];
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = end($previous_ids);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"picture\">";
echo "<img style=\"width:100%;margin:0 auto;\" src=\"upload/".$line['name']."\" /><br />\r";
echo "<div id=\"caption\">".$line['caption']."</div><br />";
}
else echo "There is no images!\n";
if ($previd > -1)
echo '<span>Prev</span>';
echo str_repeat(' ', 5);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
$query = "select * from images WHERE img_category = '$cat_id' order by RAND() LIMIT 1";
$result = mysqli_query($con, $query) or die("Query failed: " . mysqli_errno($con));
while ($row = mysqli_fetch_array($result, MYSQL_BOTH)){
echo 'Random';
}
echo str_repeat(' ', 5);
if ($line) echo '<span>Next</span> <br /><br />';
echo "</div>\r";
}
?>

How do you display a "No Results Found" message (PHP)

Just wondering how I can display this message when I type something in my search bar, and nothing matches what is stored in my MySQL database.
So far what I have is this.
<?php
if(isset($_POST['submit'])){
$search = trim($_POST['search']);
if($search != ""){
//echo "search: ". $search;
$result = mysql_query("SELECT * FROM catalogue WHERE
name LIKE '$name' OR
category LIKE '$category' OR
brand LIKE '$brand' OR
season LIKE '$season' OR
price LIKE '$price' OR
store LIKE '$store' OR
description LIKE '%$search%' ");
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$file = $row['file'];
$description = $row['description'];
$category = $row['category'];
$brand = $row['brand'];
$season = $row['season'];
$price = $row['price'];
$store = $row['store'];
$cid = $row['cid'];
echo "\n<div class=\"thumb\">";
echo "\n\t<img src=\"thumbs/$file\" class=\"thumbnailImg\" width=\"150\" height=\"200\"/><br/>";
echo "\n\t".$name. " ";
echo "\n\t$". $price;
echo "\n</div>";
}//end while loop
}else{
echo "<h2><em>No results were found.</em></h2>";
}//end if search ,else
}//end if submit
?>
This code snippet works if I just click search without typing anything in, but if I type something in the search that doesn't match up, nothing is displayed. How do I fix that?
Set a flag counter and you will get it working.
$results=0; // Setting a flag here
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$file = $row['file'];
$description = $row['description'];
$category = $row['category'];
$brand = $row['brand'];
$season = $row['season'];
$price = $row['price'];
$store = $row['store'];
$cid = $row['cid'];
echo "\n<div class=\"thumb\">";
echo "\n\t<img src=\"thumbs/$file\" class=\"thumbnailImg\" width=\"150\" height=\"200\"/><br/>";
echo "\n\t".$name. " ";
echo "\n\t$". $price;
echo "\n</div>";
$results++; //Incrementing flag if results found.
}//end while loop
}
else if($results==0)
{
echo "<h2><em>No results were found.</em></h2>";
}
else{
echo "<h2><em>No results were found.</em></h2>";
}//end if search ,else
Set a variable to 0 before the while() loop. Set it to 1 inside the loop. Print some text if it's still 0 after the loop. Like this:
$found=0;
while($row = mysql_fetch_array($result)){
$found=1;
...
}//end while loop
if ($found==0) {
echo "no results found";
}
You need to see if any rows were returned. According to the php.net manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement or mysql_affected_rows() to find out how many rows
were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
Something like this would help in your code:
...
$result = mysql_query("SELECT * FROM catalogue WHERE
name LIKE '$name' OR
category LIKE '$category' OR
brand LIKE '$brand' OR
season LIKE '$season' OR
price LIKE '$price' OR
store LIKE '$store' OR
description LIKE '%$search%' ");
if (mysql_num_rows($result) == 0 ) {
// display no results found
} else {
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$file = $row['file'];
$description = $row['description'];
$category = $row['category'];
$brand = $row['brand'];
$season = $row['season'];
$price = $row['price'];
$store = $row['store'];
$cid = $row['cid'];
echo "\n<div class=\"thumb\">";
echo "\n\t<img src=\"thumbs/$file\" class=\"thumbnailImg\" width=\"150\" height=\"200\"/><br/>";
echo "\n\t".$name. " ";
echo "\n\t$". $price;
echo "\n</div>";
$results++; //Incrementing flag if results found.
}//end while loop
}
}
...
}
Easy. Just take those echo statements & place them in a variable. If the variable is not empty, echo it. If the statement is empty, echo your “No results were found.” message. Adjusted code below:
if(isset($_POST['submit'])){
$ret = '';
$search = trim($_POST['search']);
if($search != ""){
//echo "search: ". $search;
$result = mysql_query("SELECT * FROM catalogue WHERE
name LIKE '$name' OR
category LIKE '$category' OR
brand LIKE '$brand' OR
season LIKE '$season' OR
price LIKE '$price' OR
store LIKE '$store' OR
description LIKE '%$search%' ");
while($row = mysql_fetch_array($result)){
$name = $row['name'];
$file = $row['file'];
$description = $row['description'];
$category = $row['category'];
$brand = $row['brand'];
$season = $row['season'];
$price = $row['price'];
$store = $row['store'];
$cid = $row['cid'];
$ret = "\n<div class=\"thumb\">"
. "\n\t<img src=\"thumbs/$file\" class=\"thumbnailImg\" width=\"150\" height=\"200\"/><br/>"
. "\n\t".$name. " "
. "\n\t$". $price
. "\n</div>"
;
}//end while loop
}
// Check if '$ret' has content or not.
if (!empty($ret)) {
echo $ret;
}
else {
echo "<h2><em>No results were found.</em></h2>";
}
}//end if submit

Categories