I am trying to write a series of utility functions for the common queries and other operations I run using php.
Reason I want to do this is so that my applications can be easily upgraded between PDO, mysqli and whatever they come up with next.
Before I jump head first into this approach I wonder if some PHP experts could review this approach and tell me what you think - is this a good idea for future proofing and upgradability? How will this affect performance? Will I be limiting my applications in any way in the future?
//BASIC QUERY EXECUTION (ESCAPED)
function qry($sql)
{
$sql = $db->real_escape_string($sql);
if(!$result = $db->query($sql))
{
die('There was an error running the escaped query [' . $db->error . ']');
}
return $result;
}
//PREPARE AN SQL STATEMENT
function prep($sql)
{
$statment = $db->prepare($sql);
return $statement;
}
//BIND A PARAMETERS AND VARIABLE TYPE
function bnd($statement,$parameter,$type)
{
$statement->bind_param($type, $parameter);
return $statement;
}
//EXECUTE PREPARED QUERY (UNESCAPED)
function ex($statement)
{
if(!$result = $statement->execute())
{
die('There was an error running the prepared query [' . $db->error . ']');
}
return $result;
}
//FETCH ARRAY
function ftch($result)
{
$row = $result->fetch_assoc();
return $row;
}
//GET NUMBER OF ROWS
function num($result)
{
$num = $result->num_rows;
return $num;
}
//FREE THE RESULT
function fre($result)
{
$result->free();
}
Just a few guidelines
qry()
function simply won't work. The rest is quite okay, though I would get rid of bnd()
and prep()
functions to make it all in one ex()
call. And also I would make separate functions to get separate result types, like scalar, row, array of rows and resource. Here is an example of what I am talking about: a safeMysql class based on the pretty similar concept