Search Button in php No Result error message - php

I'm having trouble where should i put my echo 'No Result Found'; in the code code I tried putting it in the last else statement together in code for debugging but it doesn't work. Please help where should I put my no result found. Thanks in advance.
if(!empty($_POST['search'])){
if($result = $db->query("SELECT * FROM product WHERE setname like '%".$_POST['search']."%' OR category like '%".$_POST['search']."%' ")) {
while($row = $result->fetch_assoc()) {
echo '<div class="col-sm-3">';
echo '<form method="POST" action="buynow.php" enctype="multipart/form-data"> ';
echo '<input type="hidden" name="productid" value="'.$row['id'].'">';
echo '<img class="thumbnail img-responsive" src="data:image;base64,'.$row['image'].' " >';
echo '<p>Name : ',$row['setname'], '</span></p>';
echo '<p>Price : ', $row['price'], '</span></p>';
echo '<p>Bonus : <span class="label label-info" style="font-size:16px;">', $row['status'], '</span></p>';
echo '<p>Price Now : ', $row['pricesale'], '</span></p>';
echo '<p>Product Detail: ', $row['productdesc'] ,'</p>';
echo '<button class="btn btn-danger btn-lg btn-block" type="submit" name="submit">Buy Now</button>';
echo '</form>';
echo '<br></div>';
}
echo '</div>';
echo '</div>';
}else{
//code for debugging query
die($db->error);
}
}

You need to count number of num_rows from your query. If no rows found the show no result found
if (!empty($_POST['search'])) {
if ($result = $db->query("SELECT * FROM product WHERE setname like '%" . $_POST['search'] . "%' OR category like '%" . $_POST['search'] . "%' ")) {
$row = $result->num_rows;
if ($row > 0) {
while ($row = $result->fetch_assoc()) {
echo '<div class="col-sm-3">';
echo '<form method="POST" action="buynow.php" enctype="multipart/form-data"> ';
echo '<input type="hidden" name="productid" value="' . $row['id'] . '">';
echo '<img class="thumbnail img-responsive" src="data:image;base64,' . $row['image'] . ' " >';
echo '<p>Name : ', $row['setname'], '</span></p>';
echo '<p>Price : ', $row['price'], '</span></p>';
echo '<p>Bonus : <span class="label label-info" style="font-size:16px;">', $row['status'], '</span></p>';
echo '<p>Price Now : ', $row['pricesale'], '</span></p>';
echo '<p>Product Detail: ', $row['productdesc'], '</p>';
echo '<button class="btn btn-danger btn-lg btn-block" type="submit" name="submit">Buy Now</button>';
echo '</form>';
echo '<br></div>';
}
} else {
echo "No result Forund";
}
} else {
//code for debugging query
die($db->error);
}
}
echo '</div>';
echo '</div>';

You can either use $result->num_rows or mysqli_num_rows($result)
if ($result->num_rows == 0) {
echo 'No Result Found';
}
else {
// Do your while
}
And please use prepared statements

Use prepared statements.
Use PDO, not mysqli.
Use templates.
So it goes
$sql = "SELECT * FROM product WHERE setname like :search OR category like :search";
$stmt = $pdo->prepare($sql);
$stmt->execute(array('search' => '%'.$_POST['search'].'%'));
$data = $stmt->fetchAll();
?>
<? foreach($data as $row): ?>
<div class="col-sm-3">
<form method="POST" action="buynow.php" enctype="multipart/form-data">
<input type="hidden" name="productid" value="<?=$row['id']?>">
<img class="thumbnail img-responsive" src="data:image;base64,<=$row['image']?>">
<p>Name : <?=$row['setname']?></span></p>
<p>Price : <?=$row['price']?></span></p>
<p>Bonus : <span class="label label-info" style="font-size:16px;">
<?=$row['status']?>
</span></p>
<p>Price Now : <?=$row['pricesale']?></span></p>
<p>Product Detail: <?=$row['productdesc']?></p>
<button class="btn btn-danger btn-lg btn-block" type="submit" name="submit">Buy Now</button>
</form>
<br>
</div>
<? endforeach ?>
<? if (!$data): ?>
No Result Found
<? endif ?>

Related

Getting an input

I have to make a website that will rank project si I've decided to use star ranking system. All works well until I add a new project.
The problem is when I rate the second project my code think it is the first one that he need to rate.
When I get all the websites with PHP, the numbers are good (input type text to see the number)
What I see on the index
But when I click on the star below the number 51, the output of the echo is 53.
Gets all the websites :
try
{
$stmt = $db->query('SELECT sites.id, sites.programme, ROUND(AVG(rating.rating_number), 2) AS rating_number, sites.annee, sites.titre, sites.equipe, sites.image_preview, sites.lien, sites.campus, sites.date_send FROM sites
INNER JOIN rating
WHERE sites.id = rating.post_id
GROUP BY sites.id
ORDER BY ROUND(AVG(rating.rating_number), 2) DESC LIMIT 30');
while($row = $stmt->fetch())
{
$date_envoie_site = strtotime($row['date_send']);
$date_maintenant = strtotime("now");
$calcul = $date_maintenant - $date_envoie_site;
echo '<div class="col custom-card">';
echo '<div class="card shadow-6-strong h-100">';
echo '<img src="img/sites/' .$row["image_preview"]. '" class="card-img-top" height="320" alt=""/>';
echo '<div class="card-body">';
if ($calcul < 86400)
{
echo '<h4 class="card-title text-center"><span class="badge bg-primary">NOUVEAU</span> ' .$row["titre"]. '</h4> ';
}
else
{
echo '<h4 class="card-title text-center">' .$row["titre"]. '</h4> ';
}
echo '<hr>';
echo '<h6 class="card-title"><i class="fa-solid fa-city"></i> ' .$row["campus"]. '</h6>';
echo '<h6 class="card-title"><i class="fa-solid fa-book"></i> ' .$row["programme"]. '</h6>';
echo '<h6 class="card-title"><i class="fa-solid fa-calendar-alt"></i> ' .$row["annee"]. '</h6>';
echo '<h6 class="card-title"><i class="fa-solid fa-users"></i> ' .$row["equipe"]. '</h6>';
echo '<form method="POST">';
echo '<input type="text" name="post_id" value="'.$row['id'].'">';
echo '<div class="rating-wrap">
<div class="center">
<fieldset class="rating">
<input type="submit" id="star5" name="star5" value="5"/><label for="star5" class="full" title="Awesome"></label>
</fieldset>
</form>
</div>
<h4 id="rating-value"></h4>
</div>';
echo '<h6 class="card-title"><i class="fa-solid fa-star"></i> ' .$row["rating_number"]. '/5</h6>';
echo '</div>';
echo '<div class="card-footer text-center">';
echo '<button type="button" class="btn btn-primary btn-lg btn-block button-custom"><i class="fa-solid fa-eye"></i> Voir le site</button>';
echo '</div>';
echo '<div class="card-footer text-center">';
echo '<div class="d-flex justify-content-evenly pb-2">';
echo '<i class="fa-brands fa-facebook fa-3x"></i>';
echo '<i class="fa-brands fa-twitter fa-3x"></i>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
catch(PDOException $e) { echo $e->getMessage();}
When I click on the star
if (isset($_POST['star5']))
{
$id = $_POST['post_id'];
echo $_POST['post_id'];
/*
$sql = "INSERT INTO rating(post_id, rating_number) VALUES (:post_id, :rating_number) WHERE post_id = '$id'";
$stmt = $db->prepare($sql);
$stmt->bindParam(':post_id', $_POST['id'], PDO::PARAM_STR);
$stmt->bindParam(':rating_number', $_POST['star5'], PDO::PARAM_STR);
$stmt->execute();
$stmt->closeCursor();
*/
}

how do I store quantity from all items in session?

I'm not seeing what goes wrong here? I want to allow my users to up the quantity from an item in their shopping cart. when they press enter I want the quantity to change from 1 to the number the use rput in and I want that it calculates everything correctly. but right now it only wants to update the last item that the user changed the quantity from. how do I fix this? I thought of using a $_SESSION but that doesn't make any difference. this is part of the code
<body>
<!--navbar-->
<a class="back" href="index.php"> <i class="bi bi-arrow-left-circle-fill bi-5x"></i></a>
<?php
include "config.php";
?>
<div class="text-center" style="font-size: 100px;">🛍</div>
<h2 class="text-center">Winkelmandje</h2><br>
<section class="container content-section">
<!-- <h2 class="section-header">CART</h2> -->
<div class="cart-row">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-item cart-header cart-column">PRICE</span>
<span class="cart-item cart-header cart-column">QUANTITY</span>
<span class="cart-item cart-header cart-column">berekening</span>
<!-- <span class="cart-item cart-header cart-column">Verwijderen</span> -->
</div>
<?php
$broodjes = $_GET['broodjes_ID'];
if (isset($_SESSION['basket'])){
if( in_array( $broodjes ,$_SESSION['basket']) )
{
}else{
$_SESSION['basket'][] = $broodjes;
}
}else{
$_SESSION['basket'][]= $broodjes;
}
$sumtotal = 0;
foreach($_SESSION['basket'] as $key => $value){
//echo "Key = $key; value = $value; <br>";
$sql = "SELECT broodjes_ID, broodnaam, prijs, voorraad FROM broodjes WHERE broodjes_ID=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $value);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
echo '<div class="cart-items">';
echo '<div class="cart-row">';
echo '<div class="cart-item cart-column">';
echo $row['broodnaam'];
echo '</div>';
echo '<div class="cart-item cart-column">';
echo '€ ' . $row['prijs'];
echo '</div>';
//quantity
echo '<div class="cart-item cart-column">';
echo '<form method="POST" action"">';
echo '<div class="col-xs-4">';
echo '<input type="hidden" name="broodnaam" id="broodnaam" value="' . $row['broodnaam'] . '">';
echo '<input type="number" name="quantity" id="quantity" class="form-control input-sm" placeholder="1" min="1" max="100" value="1">';
echo '</div>';
echo '</form>';
echo '</div>';
//session for quantity???'
$_SESSION['quantity'] = $_POST['quantity'];
$quantity = 1;
if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
$_SESSION['quantity'] = $_POST['quantity'];
if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
if ($_POST['broodnaam'] == $row['broodnaam']){
$quantity = $_POST['quantity'];
}
}
}
echo '<div class="cart-item cart-column">';
$rowtotaal = $row['prijs'] * $quantity;
$sumtotal += $rowtotaal;
echo $rowtotaal;
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?> <br />
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price"> € <?php echo $sumtotal;?></span>
</div>
<br/>
and this is what it does
now situation:
how do I store the information in a session??

SELECT query returns 1 row when there is more than 1

I'm working on a project for my university homework. Everything works right now except for my activity list. Issue is that whenever I try to view my activity list, it only returns 1 activity instead of all the activities that are still ongoing, when I manually run the query from phpMyAdmin, it returns all the queries but PHP doesn't seem to get it right and I have no idea why.
I have already tried running the query from phpMyAdmin and simplifying my query, also added a bunch of debugging code to see where I am going wrong but all the values are correct, the query is correct and phpMyAdmin runs the query just fine.
$query = "SELECT * FROM activities"; /*LIMIT " . $limit . ", " . $maxActivity;*/
$result = mysqli_query($link, $query);
echo $query;
if(!$result) {
echo "<p class='text-danger'>There are no activities to display.</p>";
} else {
while($row = mysqli_fetch_assoc($result)) {
$activity_id = $row['id'];
$activity_name = $row['name'];
$activity_description = $row['description'];
$activity_end_date = $row['endDate'];
$activity_start_date = $row['startDate'];
$activity_type = $row['type'];
$activityAuthor = $row['author'];
$activityPublished = $row['publishedAt'];
$activityLikes = $row['likes'];
$activityDislikes = $row['dislikes'];
$activityComments = $row['comments'];
$activityViews = $row['views'];
$query = "SELECT * FROM users WHERE Username = '$activityAuthor'";
$result = mysqli_query($link, $query);
if(!$result) {
die("MySQL Query Failed: " . mysqli_error($link));
}
$row = mysqli_fetch_assoc($result);
$authorID = $row['id'];
?>
<div class="row">
<div class="col-md-6">
<a href="#">
<img class="img-fluid rounded mb-3 mb-md-0" src="img/<?php echo "$activity_type";?>.jpeg" alt="">
</a>
</div>
<div class="col-md-6">
<h3><?php echo $activity_name;?></h3>
<p class="lead text-secondary">Proposed by <a class="text-secondary lead" href="profile.php?id=<?php echo $authorID;?>"><?php echo $activityAuthor;?></a> at <?php echo $activityPublished;?></p>
<p><?php echo $activity_description;?></p>
<p><strong>Starts at:</strong> <?php echo $activity_start_date;?></p>
<p><strong>Ends at:</strong> <?php echo $activity_end_date;?></p>
<a class="btn btn-outline-success" href="config/like.php?page=<?php echo $page;?>&post=<?php echo $activity_id;?>"><i class="far fa-thumbs-up"></i> <?php echo $activityLikes;?></a>
<a class="btn btn-outline-danger" href="config/dislike.php?page=<?php echo $page;?>&post=<?php echo $activity_id;?>"><i class="far fa-thumbs-down"></i> <?php echo $activityDislikes;?></a>
<button class="btn btn-outline-secondary"><i class="far fa-comment-dots"></i> <?php echo $activityComments;?></button>
<button class="btn btn-outline-secondary"><i class="far fa-eye"></i> <?php echo $activityViews;?></button>
<div class="mt-3"><a class="btn btn-primary" href="activity.php?post=<?php echo $activity_id;?>&page=<?php echo $page;?>&commentpage=1">View Activity</a></div>
</div>
</div>
<hr>
<?php }
}?>
<?php
$query = "SELECT * FROM activities";
$result = mysqli_query($link, $query);
if(!$result) {
echo "<p class='text-danger'>There are no activities to display.</p>";
} else {
while($row = mysqli_fetch_assoc($result)) {
$activity_id = $row['id'];
$activity_name = $row['name'];
$activity_description = $row['description'];
$activity_end_date = $row['endDate'];
$activity_start_date = $row['startDate'];
$activity_type = $row['type'];
$activityAuthor = $row['author'];
$activityPublished = $row['publishedAt'];
$activityLikes = $row['likes'];
$activityDislikes = $row['dislikes'];
$activityComments = $row['comments'];
$activityViews = $row['views'];
$query = "SELECT * FROM users WHERE Username = '$activityAuthor'";
$result = mysqli_query($link, $query);
if(!$result) {
die("MySQL Query Failed: " . mysqli_error($link));
}
$row = mysqli_fetch_assoc($result);
$authorID = $row['id'];
}
$output.="<div class='row'>
<div class='col-md-6'>
<a href='#'>
<img class='img-fluid rounded mb-3 mb-md-0' src='img/<?php echo '$activity_type';?>.jpeg' alt=''>
</a>
</div>
<div class='col-md-6'>
<h3><?php echo $activity_name;?></h3>
<p class='lead text-secondary'>Proposed by <a class='text-secondary lead' href='profile.php?id=<?php echo $authorID;?>'><?php echo $activityAuthor;?></a> at <?php echo $activityPublished;?></p>
<p><?php echo $activity_description;?></p>
<p><strong>Starts at:</strong> <?php echo $activity_start_date;?></p>
<p><strong>Ends at:</strong> <?php echo $activity_end_date;?></p>
<a class='btn btn-outline-success' href='config/like.php?page=<?php echo $page;?>&post=<?php echo $activity_id;?>'><i class='far fa-thumbs-up'></i> <?php echo $activityLikes;?></a>
<a class='btn btn-outline-danger' href='config/dislike.php?page=<?php echo $page;?>&post=<?php echo $activity_id;?>'><i class='far fa-thumbs-down'></i> <?php echo $activityDislikes;?></a>
<button class='btn btn-outline-secondary'><i class='far fa-comment-dots'></i> <?php echo $activityComments;?></button>
<button class='btn btn-outline-secondary'><i class='far fa-eye'></i> <?php echo $activityViews;?></button>
<div class='mt-3'><a class='btn btn-primary' href='activity.php?post=<?php echo $activity_id;?>&page=<?php echo $page;?>&commentpage=1'>View Activity</a></div>
</div>
</div>";
}
?>
<?php echo $output; ?>

MySQL separate in to DIV elements

I would greatly enjoy knowing how to separate the results of my query based on the "season" using PHP only. The products should be placed in separate divs according to what season they are for. I would also like to do this in the most efficient way possible. I have thought about his for some time and have failed both in a solution and in finding someone else's similar results on the internet. Please ignore the jquery, it is a leftover for something I may or may not use.
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Shop</title>
<link rel="stylesheet" type="text/css" href="style/main.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0
/jquery.min.js"></script>
<script type="text/javascript" src="script/jquery.simplyscroll.min.js"></script>
<script type="text/javascript">
(function($) {
$(function() {
$("#scroller").simplyScroll();
});
})(jQuery);
</script>
</head>
<body>
<div id="container">
<div id="header">
<div id="menu">
<ul>
<li>Home</li>
<li>About</li>
<li>Shop</li>
<li>Contact</li>
</ul>
</div>
</div>
<div id="content">
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
//$results = $db->query('SELECT id, name, thumb, description, price, season FROM products
BY season ASC');
foreach($db->query('SELECT id, name, thumb, description, price FROM products BY season
ASC') as $results){
if ($results) {
//output results from database
$last_season = 1;
echo '<div class="products">';
while($obj = $results->fetch_object())
{
if ($last_season != $obj->season){
echo '</div><div class="products">';
}
echo '<div class="product">';
echo '<form method="post" action="cart_update.php">';
echo '<div class="product-thumb"><img src="image/'.$obj->product_img_name.'"></div>';
echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
echo '<div class="product-desc">'.$obj->product_desc.'</div>';
echo '<div class="product-info">Price '.$currency.$obj->price.' <button
class="add_to_cart">Add To Cart</button></div>';
echo '</div>';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
$last_season = $obj->season;
}
echo '</div>';
}
}
?>
<div id="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<ol>';
foreach ($_SESSION["products"] as $cart_itm)
{
echo '<li class="cart-itm">';
echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&
return_url='.$current_url.'">×</a></span>';
echo '<h3>'.$cart_itm["name"].'</h3>';
echo '<div class="p-code">P code : '.$cart_itm["code"].'</div>';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div class="p-price">Price :'.$currency.$cart_itm["price"].'</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
}
echo '</ol>';
echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong> Check-out!</span>';
echo '<span class="empty-cart"><a href="cart_update.php?emptycart=1&
return_url='.$current_url.'">Empty Cart</a></span>';
}else{
echo 'Your Cart is empty';
}
?>
</div>
</div>
<div id="footer">Footer goes here.</div>
</div>
</body>
</html>
I am getting an error on line 44, which is the start of the "foreach" statement. I am again at a loss. Thank you a ton for your help so far. If I can get this working, with help of course, I will be extremely excited and in your debt.
Here's a loop that will create a new div each time the season changes in a new row. You will need to change the query to order the results by season, e.g.
ORDER BY season ASC
Here's the loop:
if ($results) {
//output results from database
$last_season = 1; //initial value
echo '<div class="season">'; //opens first season div
while($obj = $results->fetch_object()){
if ($last_season != $obj->season){
echo '</div><div class="season">';
}
echo '<div class="product">';
echo '<form method="post" action="cart_update.php">';
echo '<div class="product-thumb"><img src="image/'.$obj->product_img_name.'"></div>';
echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
echo '<div class="product-desc">'.$obj->product_desc.'</div>';
echo '<div class="product-info">Price '.$currency.$obj->price.' <button class="add_to_cart">Add To Cart</button></div>';
echo '</div>';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
$last_season = $obj->season;
}
echo '</div>'; //closes final season div
}
Regarding the line 44 error in the foreach, I believe what you want there instead of a foreach is simply:
$results = $db->query('SELECT id, name, thumb, description, price FROM products BY season
ASC'); //remember to remove the closing bracket of the foreach

isset within an echo? Or is there a better way?

$sql = "SELECT * from post where forum_id = $_GET[id]";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
while ($row = mysqli_fetch_array($result)) {
echo '' . $row['fourm_id'];
echo '<div id="post3">
<p class="1">
<span class="name">'.'
' .$row['name']. '</span>'.
'<span class="trip">
' .' !'
. $row['title'].''.
' </span>'.
' <span class="time">
' .$row['time']. '' .
' </span>'.
' </p>
<p class="2">
<span class="texts">
' .$row['texts']. '' .
' </span>'.
' </p>'.
if (!isset($_SESSION["user_id"])) {
}
else {
'<a href="delete_post.php?fourm_id=' . $row['id']. '>Delete</a>' . }
' </div>';
}
mysqli_close($conn);
?>
The mistake in the code is obvious, just showing what I am trying to do.
This echo I have here displays the users post, how would I go about sticking an isset in there so only admins can see the delete link? Or is there another way of doing it outside the echo with out it going outside the user post?
<?
$data = array();
$sql = "SELECT * from post where forum_id = ".intval($_GET['id']);
$res = mysqli_query($conn, $sql) or trigger_error(mysqli_error($conn));
while ($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
?>
<?php foreach($data as $row): ?>
<?=$row['fourm_id']?>
<div id="post3">
<p class="1">
<span class="name"><?=$row['name']?></span>
<span class="trip"> !<?=$row['title']?></span>
<span class="time"><?=$row['time']?></span>
</p>
<p class="2">
<span class="texts"><?=$row['texts']?></span>
</p>
<? if (isset($_SESSION["user_id"])): ?>
Delete
<? endif ?>
</div>
<? endforeach ?>
If you want to do it inline, you can either use the ternary operator or something like sprintf.
Ternary operator (best if you only have a couple of insertions):
echo "Foo ".(isset($bar) ? "bar" : "");
(s)printf (best if you have several insertions):
printf("Foo %s", isset($bar) ? "bar" : "");
However this does not scale very much, so when you have large-scale "string construction" it's much saner to split the output into more than one statements:
echo "Foo ";
if (isset($bar)) {
echo "bar";
}
This is best if you have lots of insertions.

Categories