0

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;
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Haidrex
  • 25
  • 5
  • 4
    This is impossible to answer without knowing what you're passing as `$productname` and `$supplier`. Please provide calling code and schema. On a side note, if all you're trying to do is check whether a row exists for a pair of 'supplier, product name', then this is best solved with a `WHERE` condition in your query. – Ro Achterberg Dec 06 '20 at 15:59
  • 1
    https://stackoverflow.com/questions/2803321/and-vs-as-operator might be relevant here – ADyson Dec 06 '20 at 16:00
  • 1
    Why you don't just select rows you need? `... WHERE supplierid = $supplier and name = $productname` – pavel Dec 06 '20 at 16:07
  • 2
    as Ro Achterbeg says you must solve this with a query. Now you are attempting to load all table rows and this comes with some performance issues. If you only needs to know if the product exists for a supplier the query is the right choice. – Jorge Miguel Sanchez Dec 06 '20 at 16:09

1 Answers1

1

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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39