【问题标题】:'no matching products' message not showing in if else statement / php, sql“没有匹配的产品”消息未显示在 if else 语句/php、sql 中
【发布时间】:2018-10-02 15:39:21
【问题描述】:

如果数据库中没有匹配的产品但没有显示 else 语句,我会尝试显示错误消息。也没有错误出现。 也许 if 语句有问题?我不确定这是否正确,或者我是否可以在 if 语句中放置一段时间?

<!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
}
?>

【问题讨论】:

  • if($row=$result == 1) - 你确定这种情况吗?那应该是什么意思?
  • 我不确定,我和一个朋友想出了这个,我们尝试了很多不同的条件。关于它应该是什么的任何建议?我完全是新手
  • 能否请您在 if 条件之前 print_r($result) 和 die() 并查看显示的结果然后您可以理解我认为是这样的..
  • 解析错误:语法错误,第 30 行 /home/assign043/public_html/search.php 中出现意外的 'if' (T_IF)
  • 使用PDOStatement::rowCount,例如if ($result-&gt;rowCount())

标签: php sql if-statement while-loop


【解决方案1】:

您的代码不起作用的原因是第一个if ($row=$result==1) 语句。 它的主要作用是:

1.) 将变量 $result 与 1 进行比较,后者被视为真(首先执行 == 运算符)。现在如果 $result 变量包含任何数据,如果比较,PHP 会将其视为 TRUE。如果为空,则为假。您可以在here 阅读更多相关信息。

2.) 第一步的求值,现在将 TRUE 赋值给新变量 $row(赋值运算符=)。

3.) If() 检查 $row 的值(我们知道它是 True)。因为它的评估结果为 true ,所以永远不会执行您的 else 条件。 您获得了在 cmets 中使用 PDOStatement::rowCount 的解决方案,但是,您根本不需要检查返回行数量。数据就够了。您可以只在一个 if() 条件下执行简单的 if($result==True) 或 if!empty($result) 。 现在,请注意您的代码也容易受到 sql 注入的影响。不要直接在查询中插入您的 $_GET['product'],而是这样做:

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

现在您的代码是 sql-injection 安全的。阅读关于 sql-injections How can I prevent SQL Injections in PHP?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2012-05-21
    • 2018-10-01
    相关资源
    最近更新 更多