i've wrote a little database class which goes like this:
class dbClass extends mysqli
{
public function execute($sq)
{
$res = parent::query($sq);
$rs = $res->fetch_array();
return $rs;
}
}
works so far, but the poblem is when running a delete query ("delete from mytable where..") the class throws an error on that line: $rs = $res->fetch_array(); (as it doesn't return anything i guess)
the question is: how can i trap this error? it should simple not do fetch_array() on queries like insert, delete, update ..
thanks!
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
you must check the type of result if it is boolean type do not fetch.
And the other solution could be send addition parameter which holds type of query and check that type before fetching.
public function execute($sq)
{
$res = parent::query($sq);
if (is_bool($res))
{
//not to fetch
}
else
{
$rs = $res->fetch_array();
}
return $rs;
}
what is parent::query code ?
You can just check if the array is present using isset
in your fetch_array()
function, and return empty array or null if it is not set.
I'm guessing $res
returns null
in that case, so test for that:
$res ? $rs = $res->fetch_array() : $rs = $res;
Other PHP libraries use two different functions. PHP's PDO
for example uses PDO::query
for queries that return a result set (i.e. SELECT
) and PDO::exec
for queries that do not return any results, aside from the number of affected rows (i.e. UPDATE
, DELETE
, etcetera).
As have already been mentioned, the query function does not return a resultset on write queries.
When you write your own db class, take the chance to differentiate between write and read queries. Make them into different functions. That way you can more easily scale up using simple master-slave replication of the database, since you always want to write to the master but read from one of the slaves. You also make it easier to switch to other database extensions, like PDO.
I'd warn strongly against a function that has no error checking in it. So here's my suggestion - this code will return an array in every case. If there's an error the array will only have one row containing "Error" in dimension [0] and the error message in dimension [1].
If the query doesn't return a result, the code will return [0] = "OK" and [1] = the number of rows affected.
If the query does return a result, the code will build a resultset containing the returned rows.
$retarray = array();
$result = $mysqli->query($sq);
if (!$result) {
$err = $mysqli->error;
echo $err;
$retarray = array(array("Error",$err));
return $retarray;
}else {
if (is_bool($result)){
$retarray = array(array("OK",$mysqli->affected_rows));
return $retarray;
}else{
while ($row = $result->fetch_array()) {
array_push($retarray,$row);
}
}
$result->close();
return $retarray;
}