0

I have a small problem with a function that needs to check if there is a row with a specific ID. The database contains a row, but the function does not display anything.

    public function hasInvoice(int $invoice_ID)
{
    var_dump($invoice_ID);
    $stmt_check = $this->db->prepare("SELECT * FROM `Invoice` WHERE 'OrderID'=?");
    var_dump($stmt_check);
    $stmt_check->bind_param("i", $invoice_ID);
    $stmt_check->execute();

    if ($stmt_check->num_rows > 0) {
        var_dump("Invoice already exist");
        return true;
    }
    var_dump("Invoice not exist");
    return false;
}

Invoice DB Does anyone have any idea what I did wrong in the content of the function, that it seems to be correct, but it still doesn't work. Thanks in advance.

  • Did you mean to put single quotes around `OrderID` or backtick characters? I believe that is your problem. – Booboo Jul 17 '20 at 12:21
  • No problem in quotes, the problem is that it does not display my row in the database with this ID. – Overact Overact Jul 17 '20 at 12:31
  • I only need to check if there is a row with this ID and that's it. – Overact Overact Jul 17 '20 at 12:32
  • If `OrderID` is the name of your column, you better not put quotes around it. As your SQL is written it will return *every* row from your Invoice table if and only if `$Invoice_ID` is equal to the string literal 'OrderID'. But of course, that won't be the case since your are binding it as an integer. You can lead a horse to water but you can't make hiim drink. – Booboo Jul 17 '20 at 12:35
  • Okay, so what's the mistake? that I put the quotes in OrderID or which? because even if I remove the quotes from OrderID, this doesn't work anyway – Overact Overact Jul 17 '20 at 12:47
  • Yes, the single quotes is an error as I indicated in my last comment. You can put column names within backticks, but that's only necessary if the name has special characters such as spaces. Make sure `$invoice_ID` has the value you expect (that is, `65`). Then after call to `execute()`: `$result = $stmt_check->get_result(); $num_rows = $result->num_rows;` – Booboo Jul 17 '20 at 13:22
  • Alternatively, following call to `$stmt_check.execute()` just insert: `$stmt_check.store_result();`, which I suppose is even simpler. Then your `$stmt_check.num_rows` will return correct value. – Booboo Jul 17 '20 at 13:37
  • `bind_result($invoiceID, $invoiceName);` `$stmt_check->execute();` `$stmt_check->fetch();` `$stmt_check->close();` `if (isset($invoiceID))` and this would be another alternative. Thanks for the help – Overact Overact Jul 17 '20 at 13:42

0 Answers0