Question

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();
}
Was it helpful?

Solution

Just a few guidelines

  1. Create a class, not set of independent functions
  2. Whatever real_escape_string function does not protect anything and should not used for this purpose. PDO doesn't have a function like this at all. Applying this function to a whole query will make absolutely no sense.
  3. Therefore, qry() function simply won't work.
  4. It won't work also because $db is out of scope.
  5. Please don't die()! Throw an exception instead. PDO does it already, no code required

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top