Reputation: 1764
I would like to make one universal function for database queries. The function I have below works perfectly for SELECT queries. However I would like to have it working properly for INSERT, UPDATE, DROP and other queries not returning anything. Can someone tell me why using mysqli_fetch_all for such queries prints warning? How to properly handle it? How to obtain status of such queries?
function cms_query($sql_query)
{
// Object returned by mysqli_connect
global $cms_db;
// Perform query
$result = mysqli_query($cms_db, $sql_query);
if(!$result) {
print("ERROR\nFAILED_TO_QUERY\n");
return;
}
// Obtain results
$rows = mysqli_fetch_all($result, MYSQL_ASSOC);
if(!$rows) {
print("OK\n0\n0\n");
return;
}
// Print result array keys
$keys = array_keys($rows[0]);
print("OK\n" . count($keys) . "\n");
foreach($keys as $key)
print($key . "\n");
// Print result rows
print(count($rows) . "\n");
foreach($rows as $row)
foreach($row as $value)
print($value . "\n");
}
Upvotes: 1
Views: 93
Reputation: 157880
Well, it's a good idea per se to have such a function, but there is one thing that your function desperately lacking - the support for prepared statements.
So, to make your function work in its current form, it's not a big deal:
function cms_query($sql_query)
{
// Object returned by mysqli_connect
global $cms_db;
// Perform query
$result = mysqli_query($cms_db, $sql_query);
if(!$result) {
trigger_error(mysqli_error($cms_db));
}
// if it was a DML query
if (if $result === true)
{
return;
}
// Obtain results
return mysqli_fetch_all($result, MYSQL_ASSOC);
}
but you have to understand that such a function should support prepared statements. And for sake of such a support it's better to use PDO. I wrote such a function, or rather, a PDO wrapper which I strongly recommend for you to consider. Note the Examples part of the article - as you can see, this function can run any kind of query.
Upvotes: 2
Reputation: 2743
From the manual:
mysqli_query
Returns
FALSE
on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queriesmysqli_query()
will return amysqli_result
object. For other successful queriesmysqli_query()
will return TRUE.
So, when you do a data modification query (INSERT for example), you get boolean value. When you try to pass it as argument for mysqli_fetch_all()
you get an error, because this function expects an instance of mysqli_result
class.
Upvotes: 0