Skip to content
Advertisement

check through second column by first column id

I have 2 columns under sales table in SQL as below

id itemid
1 31
1 32
1 33
1 34

I need through the PHP to check by the id, if the $_SESSION[‘id’] has any item number in the second column then tell the user that the item already exists, otherwise add this item to DB .. I did do fat the below code but it doesn’t work, it will print both conditions if statement

<?php

session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
    
    $itemid = filter_input(INPUT_GET, "itemid", FILTER_VALIDATE_INT);

    if($itemid !== null && $itemid !== false){
        $SQL = $dbh->prepare("SELECT * FROM sales where userid = ?");
        if($SQL->execute([$_SESSION["userid"]])){
            if ($SQL->rowCount() > 0){
                while($row = $SQL->fetch()){
                    if((int)$row['itemid'] === $itemid){
                        echo "item is exist";
                    }else{
                        echo "add it to the table";
                    }                   
                }
            }
        }
    }
}

Advertisement

Answer

You’re reporting “add it to the table” for every row that has a different item ID. You can’t know that the item ID isn’t found until you get to the end of the loop, if it was never matched. See Searching array reports “not found” even though it’s found for this general problem, which is a common beginner error.

But there’s no need for the loop. Check for itemid in the SQL query.

$SQL = $dbh->prepare("SELECT COUNT(*) as count FROM sales where userid = ? and itemid = ?");
$SQL->execute([$_SESSION['userid'], $itemid]);
$row = $SQL->fetch();
if ($row['count'] > 0) {
    echo "item is exist";
} else {
    echo "add it to the table";
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement