Haidrex
Haidrex

Reputation: 33

Why does this function always return true even if it shouldn't?

I have a function that goes through the product database table and if there is a row with supplierid and name that matches the parameters, then it returns true.

But it always returns true even if it shouldn't.

function checkifhoused($productname, $supplier)
{
    $db = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    $sql = "SELECT * FROM " . TBL_PRODUCTS;
    $result = mysqli_query($db, $sql);
    while ($row = $result->fetch_assoc()) {
        if ($row['supplierid'] == $supplier and $row['name'] == $productname) {
            return true;
        }
    }
    return false;
}

Upvotes: 0

Views: 54

Answers (1)

Slava Rozhnev
Slava Rozhnev

Reputation: 10163

First: I can advice you to use PDO extension. It have better variables binding options. Second: as @pavel & Ro Achterbeg mentioned in theirs comment you need not fetch all rows from DB table, but check only record with needle parameters exists

<?php
define('TBL_PRODUCTS', 'TBL_PRODUCTS');

function checkifhoused($db, $productname, $supplier)
{
    $sql="SELECT * FROM ".TBL_PRODUCTS." WHERE name = ? AND supplierid = ? ";
    $stmt = $db->prepare($sql);
    $result = $stmt->execute([$productname, $supplier]);

    return $stmt->rowCount() > 0;
}

var_dump(checkifhoused($pdo, 'productname', 1));

var_dump(checkifhoused($pdo, 'other_productname', 1));

Here you can test PHP & SQL code

Upvotes: 1

Related Questions