If you are writing new code it is strongly recommended that you use PDO.
/*
* $dsn is a database connection string, containing username, password
* and other connection details as outlined in PDO's manual entry
*/
$db = new PDO( $dsn );
/*
* In PDO we normally prepare statements so that we can reuse them.
* there are two syntaxes for this - ? syntax and :value syntax.
*/
$statement = $db->prepare("
SELECT *
FROM users
WHERE id = ?
");
/*
* Now we look for the user with id 4. The array contains multiple possible
* parameters to the query.
*/
$statement->execute(array(4));
/*
* We can now ask the statement for a rowcount, or we immediately work
* with the results, since if the query has a return an array will be returned,
* else boolean false will be returned.
*/
$user = $statement->fetchAll();
if ($user !== false) {
// work with results.
} else {
// there where no results
}
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
$result = mysqli_query($link, $query);
if ( $result )
{
// results found
echo mysqli_num_rows($result);
}
else
{
// results not found
}
The result can still be empty even if it was succesful.
If you use pdo, as suggested above. You get an array back (empty array if result is empty) so you can do sizeof($array) or count($array) to check if you have 0 results or not.