Rookie Recruits
Rookie Recruits

Reputation: 93

Comparing a PHP variable to values in MySQL column

Just a little assistance, This is a pretty simple problem but it doesn't seem to work right. I am just comparing the value in a variable with all the values in a sql column. Same as if I were to compare a username input to the list of usernames in a sql column. This however is just to compare that the item id being stored in the column for that row is not an item id that is already in use.

I tested the value that I am getting back from the sql query and it is equal to the item id I typed in the input. What you will see below is the actual test to see if the id I am getting back is the one that I am looking for as well as the id of the row I can find that value in. The results I get is

2, 000002 (which is correct) that is what I am looking for.

$itemId = $_POST['itemId'];


        if($sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'")){
            while($data = $sqlItemId->fetch_assoc()){
                printf("<p>%s, %s</p>", $data['id'], $data['itemId']);
                die();
            }

Then I took this out and tried to compare the value in the variable which is the same itemId already stored (000002). that is where I am going wrong.

I modified the code to look like this for further testing. Seems straight forward yet i am getting a FALSE response providing the latter echo statement "Item Id is not in use" But it is in the DB. I tried it a few different ways based on what I read in stackoverflow but none are giving me the right answer.

    $sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'");

        if($itemId == $sqlItemId){
                echo "This item id is already in use. \n";
                die();
        } else {
                echo "Item Id is not in use:";
                die();
        }

At one point I even tried a while statement to fetch the associated values prior to testing it but that didn't turn up a positive result either. Any suggestions?

Upvotes: 0

Views: 5846

Answers (2)

Jorge Faianca
Jorge Faianca

Reputation: 791

Wy don't you just count it,

$result = $dbCon->query("SELECT COUNT(itemId) FROM CVCinStoreCoins WHERE itemId = $itemId");

if $result > 0

Upvotes: 1

user5192753
user5192753

Reputation:

Inside $sqlItemId you have the full table row (if any), not only its ID; change the SQL into a count and check the number of rows returned (if greater than 0 you have a duplicate):

$rowsCount = $dbCon->query("
    SELECT COUNT(*)
    FROM CVCinStoreCoins
    WHERE itemId = '$itemId'
");

I don't know what $dbCon is (Doctrine DBAL? mysqli?) so I can't tell you how to use query's result.

Upvotes: 1

Related Questions