-1

I am trying to run a SELECT * FROM <table> WHERE <param> = <value> LIMIT 1 SQL query with MySQLi

I have built this code snippet, which works perfect if the input id is present in SQL DB.

$id = $_GET['id'];

// preparing and binding
$stmt = $conn->prepare("SELECT * FROM `testtable1` WHERE `userid` = ? LIMIT 1");
$stmt->bind_param("i", $id);

// setting parameters and execute
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

echo $row['email'] . '<br><br>';

What I want to know is, how would I know if the input id (which was passed along with the URL) is NOT present in the DB? Currently, If the ID's present in the DB, the email param's value shows up. But if it's not present, nothing shows up..

So with the above piece of code, how do check whether the input ID is correct or not - so if incorrect I could show an 'Incorrect ID' message there?

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

0

First thing to remember is that a valid query can return an EMPTY recordset. Meaning you are not looking for an error, but it is possible to get an empty result.

One way is to check the number of rows returned

$id = $_GET['id'];

$stmt = $conn->prepare("SELECT * 
                        FROM `testtable1` 
                        WHERE `userid` = ? 
                        LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->store_result();
if ( $stmt->num_rows > 0 )
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    echo $row['email'] . '<br><br>';
} else {
    //no rows returned id must not exist
    echo 'That use does not exist';
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

PHP like most programming languages has a language structure called if statement. An if statement expects a boolean value and if the value is true (or true-ish) then the following block of code is executed.

In PHP an empty array is considered to be false-ish so you can simply do the following to check if any value was returned by the SELECT statement:

$stmt = $conn->prepare("SELECT * FROM `testtable1` WHERE `userid` = ? LIMIT 1");
$stmt->bind_param("i", $id);
// setting parameters and execute
$stmt->execute();
$result = $stmt->get_result();

$row = $result->fetch_assoc();
if($row) {
    echo $row['email'] . '<br><br>';
} else { 
    echo 'Incorrect ID - no value found in the database!';
}

The else block will be executed if the condition inside of if(condition) is false-ish. If there is a value returned by SQL then you will have a non-empty array in $row which will evaluate to true and the first block of code will be executed.

Dharman
  • 30,962
  • 25
  • 85
  • 135