0

I'm trying to show an error message if there are no matching products in the database but the else statement is not showing. No errors are coming up either. Maybe there is something wrong with the if statement? Im not sure if thats correct either or if i can put a while inside an if statement?

<!DOCTYPE html>
<html>
<head>
    <title> Solent E-Stores </title>
    <link rel='stylesheet' type='text/css' href='styles.css'>
</head>

<body>
    <h1>Solent E-Stores</h1><br>
    <?php


    $conn=new PDO("mysql:host=localhost;dbname=assign043;","assign043","eeThotev");

    $product = $_GET["product"];

    $result=$conn->query("SELECT * FROM products WHERE name='$product'");

    if($row=$result == 1)
    {
        while($row=$result->fetch())
        {
            echo "Product name: ".$row['name']."<br>";
            echo "Description: ".$row['description']."<br>";
            echo "Manufacturer: ".$row['manufacturer']."<br>";
            echo "Price: £".$row['price']."<br>";
            echo "Stock Level: ".$row['stocklevel']."<br>";
            echo "Age Limit: ".$row['agelimit']."<br>";

            echo "<p><a href='addtobasket.php?ID=".$row['ID']."'>Add one to basket!</a></p>";
            echo "<p><a href='changequantity.php?ID=".$row['ID']."'>Change quantity!</a></p>";
        }
    }
    else
    {
        echo "There are no matching products!";
        echo "<p> <a href='index.php'>Back to Search page!</a></p>";
    }

    echo "<br><br><p> <a href='basket.php'>View my basket!</a></p>";
    echo "<p><a href='index.php'>Go back to Search page!</a></p>";

    ?>
</body>
</html>

<?php
}
?>

1 Answers1

0

The reason your code did not work is of the first if ($row=$result==1) statement. Wht it basically does is:

1.) Compare variable $result with 1 which is treated as true (the == operator is executed first). Now if $result variable contains any data, PHP will treat it as TRUE if comparing. And if empty, then false. You can read more about it in here.

2.) The evaluation of first step, now TRUE is assigned to new variable $row (the operator of assignment =).

3.) If() checks the value of $row (which as we know is True). Because it's evaluating to true , your else condition is never executed. You got the solution to use the PDOStatement::rowCount in the comments, however, you do not need to check for return row amount at all. Data is enough. You can do simple if($result==True) or if!empty($result) instead in just one if() condition. Now, notice tha your code is also vulnerable to sql injection. Instead of directly inserting your $_GET['product'] in the query, do this:

$st=$conn->prepare('SELECT * FROM products WHERE name=:product');
$st->bindParam('product',$_GET['product']);
$result=$st->execute();

Now your code is sql-injection safe. Read about sql-injections How can I prevent SQL Injections in PHP?

Moe Epo
  • 92
  • 9