PHP PDO Helper Functions Just recently I've wanted to update the PHP scripts I use to fetch information from a database for an iOS application. I've got around to it today, and I had a few questions that'd I like a second opinion on before I use these scripts.


Will this method of operation work? As in, since the query and connection are in two different try/catch blocks, will the query work differently?
Is this safe against SQL injection?
Can this support multiple/no parameters?
Overall, is this an efficient way of querying a database?


databaseHelper.php

&lt;?php

error_reporting(E_ALL);
ini_set('display errors', 1);

$connection = // redacted
$username = // redacted
$password = // redacted

function initiateConnection() {
    try {
        $dbh = new PDO($connection, $username, $password);
        $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $dbh;
    } catch(PDOException $e) {
        return null;
    }
}

function performQuery($connection, $queryString, $parameters) {
    try {
        $query = $connection-&gt;prepare($queryString);
        $query-&gt;execute($parameters);

        if($sth-&gt;rowCount()) {
            $row = $sth-&gt;fetchAll(PDO::FETCH_ASSOC);
            return $row;
        } else {
            return null;
        }
    } catch(PDOException $e) {
        return null;
    }
}

?&gt;


This is how I would plan on utilizing these functions:

&lt;?php

include '../php_include/database.php';

$connection = initiateConnection();
if($connection != null) {
    $response = preformQuery($connection, 'SELECT * FROM users WHERE username = ?', 'test') // the username will NOT be hardcoded, it will be found in the $POST variable, this is just for example purposes
    if($response != null) {
        // echo json_encode($response);
    } else {
        // print false   
    }
} else {
    // print error message 
}

?&gt;
Wrapping PDO: General Approach

Generally, wrapping PDO without actually adding any functionality is not recommended. See for example here, or pretty much any answer on basic PDO wrapper classes. 

Because what happens is that you take a class with a pretty nice (and well known) interface, and then reduce the power of that interface (you can only perform FETCH_ASSOC, if you ever need a different fetch type, you would probably add a parameter/method to your script, if you follow my advice below, you will throw exceptions, etc; at some point, your script will be very close in use to PDO, just with different function names, and slightly limited functionality).

Wrapping PDO: Swallowing Exceptions

The biggest drawback of your solution is that you take perfectly fine exception and turn them into null returns. This has two downsides: It makes your calling code ugly (too many != null checks), and it makes it really hard to debug your code, as you just swallowed all the information, eg on why the database connection could not be established, or why the query returned nothing (is there nothing in the database, or is the query completely wrong? nobody knows now).

Wrapping PDO: Error Reporting

Another thing that's a real problem is that you are setting error reporting in this script. This is really something that needs to be controllable (for PDO as well as for PHP), because you want all the error reporting possible in development mode, but none of it in production. If you just set these values in various scripts, it will be really hard to control.

Your Questions

So I would definitely not recommend this approach, but if you want to go forward in this direction:


  Will this method of operation work?


Yes.


  Is this safe against SQL injection?


Yes. (assuming it is used correctly, which means no variable input in the querystring ever; and also assuming that this isn't an issue)


  Can this support multiple/no parameters?


Multiple queries definitely, and I would assume that execute(emtpyArray) is valid, but haven't tested it.


  Overall, is this an efficient way of querying a database?


Performance wise? Sure. Code wise? You don't actually save all that much typing. The PDO instantiation only happens once (and having a method for that seems fine to me), so lets look at the queries:

try {
    $query = $connection-&gt;prepare($queryString);
    $query-&gt;execute($parameters);
    if($sth-&gt;rowCount()) {
        // echo json_encode($sth-&gt;fetchAll(PDO::FETCH_ASSOC));
    } else {
        // print false   
    }
} catch(PDOException $e) {
    // print error message 
}


vs

if($connection != null) {
    $response = preformQuery($connection, 'SELECT * FROM users WHERE username = ?', 'test');
    if($response != null) {
        // echo json_encode($response);
    } else {
        // print false   
    }
} else {
    // print error message 
}


So with your approach, you basically saved one line.