0

I'm building an online shop (not a real one) using PHP. I have a search results page and a full specs page, the full specs page is working perfectly however when I created a shopping cart page that also works perfectly the search results page no longer returns anything. I have found when commenting out the if statement and while statement the "no items found" message does work but cannot get it to return anything if this is a valid search. After a couple of days, I still cannot figure out what the problem is. I will include the adding to basket and form code as the form is also included on the full specs page which does work. If you can point me in the right direction it would be greatly appreciated.

**Search Bar code**
<?php
    global $ConnectingDB;
    if (isset($_GET["SearchButton"])) {
                            
   }
?>
    <form class="mt-5" method="GET" action="searchResults.php" style="width: 100%;">
       <div class="form-group">            
       <input class="form-control mb-2" type="text" name="Search" placeholder="Search for Item" value="">
            <button class="btn btn-success" name="SearchButton" style="width: 100%;">Search</button>
        </div>
    </form> 

Search Results Code

    $db = mysqli_connect("localhost", "root", "", "computerStore") or die (mysqli_error());
    require_once("includes/functions.php");
    require_once("includes/sessions.php");
    include("addingToBasket.php");
?>
<html>
    <head>
        <title>Search Results</title>
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <?php
            include("navbar.php");
        ?>
        <div style="height: 15%;"></div>
        <div class="container mt-5">
            <?php
                echo ErrorMessage();
                echo SuccessMessage();
            ?>
            <div class="row">
                <div class="col-lg-12">
                    <?php
                        if (isset($_GET["productNumber"])) {
                            $Search = $db->real_escape_string($_GET["Search"]);
                            $sql = $db->query("SELECT * FROM products WHERE productName LIKE '%$Search%' OR productNumber LIKE '%$Search%' OR briefProductInfo LIKE '%$Search%'");
                            $result = new mysqli($db, $sql) or die("bad query: $sql");
                            $row = mysqli_fetch_assoc($result);
                            $count = mysqli_num_rows($result);
                            echo $count;
                            //stmt = $db->query($sql);
                            //$row = $stmt->fetchAll();
                            //echo count($row).' rows selected';
                        
                        if ($sql->mysqli_num_rows > 0) { 
                        while ($row = mysqli_fetch_assoc($result)) {
                            $ProductName = $row["productName"];
                            $ProductNumber = $row["productNumber"];
                            $ProductType = $row["productType"];
                            $BriefProductInfo = $row["briefProductInfo"];
                            $FullProductInfo = $row["fullProductInfo"];
                            $Image = $row["image"];
                            $Price = $row["price"];
                            $Quantity = $row["quantity"];
                            include("form.php");
                                }
                            } else {
                                ?> <div class="container"><h2><?php echo "Item has not been found, please try another search"; ?></h2></div>
                        <?php    
                            } 
                        } 
                    ?>
                </div>
            </div>
        </div>
    </body>
</html> 

Adding to Basket Code

<?php 
    if (!(isset($_SESSION['cart']))) {
            $_SESSION['cart'] = array();
        } else {
            echo "";
        }
        if (isset($_GET['clear'])) {
            $_SESSION['cart'] = array();
        }
        if (isset($_GET['productNumber']) && isset($_GET['quantity'])) {
            $ProductNumber = $_GET['productNumber'];
            $Quantity = $_GET['quantity'];
            if ($Quantity > 0) {
                if(isset($_SESSION['cart'][$ProductNumber])) {
                    $_SESSION['cart'][$ProductNumber] += $Quantity;
                } else {
                    $_SESSION['cart'][$ProductNumber] = $Quantity;
                    $_SESSION["SuccessMessage"] = "Item has been successfully added to your basket, feel free to continue shopping if there are more items to wish to purchase. However if you
                    do wish to buy now, amend the item quantity or you added the item by mistake and wish to remove it, please select the view basket link.";
                }
            }
        }
?>

The Form

while ($row = mysqli_fetch_assoc($result)) {
            ?>
            <h2 class="mb-5"><?php echo $row["productName"] ?> - <?php echo $row["briefProductInfo"] ?></h2>
            <p class="text-center mb-5"><?php echo $row["productNumber"] ?></p>
            <img class="img-fluid mx-auto d-block mt-5 mb-5" src="images/<?php echo $row["image"] ?>" alt="Product Image">
            <p style="text-align: justify;"><?php echo $row["fullProductInfo"] ?></p>
            <h1 class="mt-5 mb-5" style="color: red;">£<?php echo $row["price"] ?></h1>
            <p style="text-align: center;" id="numberAvailable"><?php echo $row["quantity"] ?> Available</p>
            <form method="get" action="<?php $_SERVER["PHP_SELF"] ?>">
                <div class="row mt-5 mb-5">
                    <div class="col-lg-2">
                        <p style="font-size: 170%;" id="numberRequested">Quantity</p>
                    </div>
                    <div class="col-lg-2 mt-1">
                        <select class="pt-2 pb-2" name="quantity" class="form-control" id="numberRequestedPulldown">
                            <?php
                                if ($row["quantity"] >= 5) {
                                    for ($i = 1; $i <= 5; $i++) {
                            ?>
                            <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                            <?php
                                    }
                                } else {
                                    for ($i = 1; $i <= $row["quantity"]; $i++) {
                                       ?> <option value="<?php echo $i; ?>"><?php echo $i; ?></option>    
                                    <?php
                                    }
                                }
                            ?>
                        </select>
                        <input type='hidden' name='productNumber' id='productNumber' value='<?php echo $row['productNumber'] ?>'>
                    </div>
                    <div class="col-lg-4 mt-1">
                        <input type="submit" class="btn btn-success btn-block" id="addToBasketLink" value="Add to Basket"> 
                    </div>
                    <div class="col-lg-4 mt-1">
                        <a href="computerStore.php?page=1" class="btn btn-danger btn-block">Return to Items List</a>
                    </div>        
                </div>
            </form>
        <?php
            }
        ?>
  • *Warning*: Your code is vulnerable to [MySQL Injections](https://stackoverflow.com/q/60174/2430549). – HoldOffHunger Oct 29 '20 at 21:50
  • Some tips: 1. `isset()` can take multiple arguments, so `isset($_GET['productNumber']) && isset($_GET['quantity'])` can become `isset($_GET['productNumber'], $_GET['quantity'])`. 2. There is never any benefit to declaring the `value` attribute of an ` – mickmackusa Oct 30 '20 at 14:55
  • Look at this: `$sql = $db->query("SELECT * FROM products WHERE productName LIKE '%$Search%' OR productNumber LIKE '%$Search%' OR briefProductInfo LIKE '%$Search%'"); $result = new mysqli($db, $sql)` ...you use the connection variable `$db` to execute a mysqli-oop-style query query, then save the result object to `$sql`. (A poor choice for the variable name -- I recommend `$result`.) Next you try to instantiate a new mysqli connection object by feeding it the pre-existing connection object (`$db`) and the query's result object (`$sql`). https://www.php.net/manual/en/mysqli.construct.php – mickmackusa Oct 30 '20 at 15:08
  • I reckon this one as Off-topic Typo because it is very unlikely that future researchers will deviate so much from the php manual and call fir a new mysqli connection using the existing mysqli connection variable. Scrap your current techniques and use mysqli's oop-style prepared statements. – mickmackusa Oct 30 '20 at 15:12
  • Would that mean $sql = $result->query (The SQL statement) – Luke Plachta Oct 30 '20 at 19:49

1 Answers1

-1

Your SQL statement for the search may not be formatted correctly:

$sql = $db->query("SELECT * FROM products WHERE productName LIKE '%$Search%' OR productNumber LIKE '%$Search%' OR briefProductInfo LIKE '%$Search%'");

I can tell you from experience that just placing a double apostrophe(") at the start and including the wildcard(%) in your statement may be the wrong way to go try this:

$sql = $db->query('SELECT * FROM products WHERE productName LIKE "%'.$Search.'%" OR productNumber LIKE "%'.$Search.'%" OR briefProductInfo LIKE "%'.$Search.'%"');

This separates the wildcard(%) from the search term that the SQL is looking for. By including the % inside of the statement the SQL statement may run but come up with zero results and move onto your next statement because it is looking for '%book%', when it should be just looking for 'book'. This would give you the "no items found" message, because it moves to the next statement.

This is new information 10/30/2020 You are using the search as your name in this input:

<form class="mt-5" method="GET" action="searchResults.php" style="width: 100%;">
       <div class="form-group">            
       <input class="form-control mb-2" type="text" name="Search" placeholder="Search for Item" value="">
            <button class="btn btn-success" name="SearchButton" style="width: 100%;">Search</button>
        </div>
    </form> 

You are not carrying over the productNumber though that I see to get start the statement.

 if (isset($_GET["productNumber"])) {

Maybe try doing something like this instead:

$Search = filter_input(INPUT_GET, 'Search');
/*use the preg_replace to remove any special characters*/
$Search = preg_replace('/[^a-zA-Z0-9]/', '', $Search);
echo $Search; /*Just to see if it appears*/
/*instead of  if (isset($_GET["productNumber"])) {  use */
if($Search != ''){ 
$sql = $db->query('SELECT * FROM products WHERE productName LIKE "%'.$Search.'%" OR productNumber LIKE "%'.$Search.'%" OR briefProductInfo LIKE "%'.$Search.'%"');
continue with code
  • Thanks for letting me know, sadly having used what you suggested I am still getting the same result – Luke Plachta Oct 30 '20 at 10:26
  • Can you do an echo after the `$Search = $db->real_escape_string($_GET["Search"]);`. You want to see what the $Search item is that may help figure out why it isn't being seen by the query properly. – Josh Carlisle Oct 30 '20 at 11:26
  • Na it still wont display anything but it is coming up in the URL bar what the search result is, just not displaying it on the page – Luke Plachta Oct 30 '20 at 11:54
  • See the edit in the answer for a new thought. – Josh Carlisle Oct 30 '20 at 14:39
  • Nice one, this is now outputting what I put into the search e.g. the product number, will have a play around with it see how it goes. Thanks for your help – Luke Plachta Oct 30 '20 at 19:32