如果语句无论如何返回

I have a PHP code that gets an id number and then checks if the id exists in the database. If the id is in the database it echos Item Added if not it echos That id is not valid

(Well at least that is what it is supposed to do!)

Right now it echos out Item Added regardless.

$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';
    }
}

My url for the get actions look like this:

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

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.

On an unrelated note: Your code is also vulernable to MySQL injections and you should instead be using prepared statements.

= is assignment

== is comparison.

Change:

if ($result = 0) {

to

if ($result == 0) {

Update:

You also need to retrieve the number of rows from your query properly, like:

$result = mysqli_query($con,"SELECT * FROM items WHERE id='$id'");
$row_cnt = mysqli_num_rows($result);
if ($row_cnt == 0) {
if ($result = 0) {

        echo 'That id is not valid!';
    }

is assigning result, you need to use if($result == 0)

As others have pointed out, using one = sign is assignment, not comparison.

Please refer to the Comparison Operators documentation:

PHP Comparison Operators

You can use this:

$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.