1

我有一个获取 id 号的 PHP 代码,然后检查该 id 是否存在于数据库中。如果 id 在数据库中,则回显Item Added,否则回显That id is not valid

(至少这是它应该做的!)

现在它Item Added无论如何都回响了。

$action = $_GET['action'];
$id     = $_GET['id'];

if ($action == 'add') {

    // Check if the id matches one in the database 
    $result = mysqli_query($con,"SELECT COUNT(*) FROM items WHERE id='$id'");

    if ($result = 0) {

        echo 'That id is not valid!';
    }
    else {

        echo 'Item Added';
    }
}

我的获取操作的网址如下所示:

../shopping-functions.php?action=add&id=977
4

5 回答 5

4

=是赋值

==是比较。

改变:

if ($result = 0) {

if ($result == 0) {

更新:

您还需要从查询中正确检索行数,例如:

$result = mysqli_query($con,"SELECT * FROM items WHERE id='$id'");
$row_cnt = mysqli_num_rows($result);
if ($row_cnt == 0) {
于 2013-11-10T05:41:54.727 回答
2

As others have pointed out, you are using the assignment operator instead of comparison in your if statment – i.e. you use = instead of ==. Unfortunately, this is not the only mistake.

mysqli_query returns a MySQL resource, so just comparing it to 0 will not be true, unless the query actually fails. Instead, you need to look at the actual result data from the resource object you get back. An easier solution would be:

if ($action == 'add') {

    // Check if the id matches one in the database 
    $result = mysqli_query($con,"SELECT id FROM items WHERE id='$id'");
    if (mysql_num_rows($result) == 0) {

        echo 'That id is not valid!';
    }
    else {

        echo 'Item Added';
    }
}

So instead of selecting the number of entries with the specific id, you just select the id itself if it exists and then you count the results you get back.

在不相关的说明中:您的代码也容易受到 MySQL 注入的影响,您应该使用准备好的语句。

于 2013-11-10T05:49:27.493 回答
1

你可以使用这个:

$action = $_GET['action'];
$id = $_GET['id'];
if($action == 'add') {
// Check if the id matches one in the database
$result = mysqli_query($con,"SELECT COUNT(*) FROM `items` WHERE `id`='$id'");
$row = $result->fetch_row();
if($row[0] == 0) {
echo 'That id is not valid!';
}
else {
echo 'Item Added';
}
}

You were checking it with a mysql resource before, which was wrong. Also you used an assignment operator (=) rather than a comparism operator (==) just like every one said.

于 2013-11-10T05:49:26.340 回答
0
if ($result = 0) {

        echo 'That id is not valid!';
    }

正在分配结果,您需要使用if($result == 0)

于 2013-11-10T05:42:01.673 回答
0

正如其他人指出的那样,使用一个 = 符号是赋值,而不是比较。

请参阅比较运算符文档

PHP 比较运算符

于 2013-11-10T05:46:23.653 回答