I'm using Medoo Framework to handle my database queries. It is basically a PDO wrapper, I didn't find in their documentation how to handle errors or check the result, sometimes it return empty array, sometimes FALSE sometimes 0 etc.
As I couldn't understand how to handle errors this is what I'm doing currently using empty() because it can handle FALSE , 0 and empty Array I think it's okay here):
On SELECT (Medoo returns array)
// Same as:
// SELECT username FROM accounts WHERE id=$id AND suspended=0
$select = $database->select("accounts",["username"], [
"AND" => [
"id" => $id,
"suspended" => 0
]
]);
// I have to check if Query failed also if row was not found
if (empty($select) === FALSE && count($select) > 0)
{
// It didn't FAIL
// So i get username like this:
$key = array_keys($select)[0];
$username = $select[$key]['username'];
}
else
{
// It FAILED
}
On INSERT (Medoo says it returns INSERT ID here)
$insert = $database->insert("accounts", [
"username" => "$username"
]);
// Check if query didn't fail and actually inserted (affected rows i think?)
if (empty($insert) === TRUE OR $insert < 1)
{
// It Failed
}
On UPDATE (This is actually the only clear query, it returns affected rows)
$update = $database->update("accounts", ["brute_force[+]" => 1], ["id" => $user_id]);
if (empty($update) === TRUE OR $update < 1)
{
// It FAILED
}
// Check if query didn't fail and also affected row
I am so confused and unsure about these that I'm paranoid maybe I should just completely rewrite and use CodeIgniter like I always do.
To check if SELECT/UPDATE
statement succeeded I use:
if(!$select){
// SELECT failed
}
because MEDOO will return FALSE
or 0
or empty Array
if SELECT/UPDATE
failed or no data were retrieved/updated, and all of these things are equal FALSE
in an if
statement. For INSERT
you can use the same thing if your table in database has ID
field as primary key; if you don't have primary key, then you could use error()
method and parse response to check for errors, because MEDOO
will return 0
even though the statement was executed.