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
<?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->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
} catch(PDOException $e) {
return null;
}
}
function performQuery($connection, $queryString, $parameters) {
try {
$query = $connection->prepare($queryString);
$query->execute($parameters);
if($sth->rowCount()) {
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
return $row;
} else {
return null;
}
} catch(PDOException $e) {
return null;
}
}
?>
This is how I would plan on utilizing these functions:
<?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
}
?>