I am pretty new with PHP furthermore PDO so I am not fully aware of what to avoid (and include) when accessing databases apart from SQL injection. (FYI, in the example below the table “users” also include passwords), however would accessing the database using a function as below to get information from be safe? is it prone to attacks?
and if you don’t understand why I’ve done this it’s because I find it quicker and it will make it easier when linking tables 🙂
<?php
require("access/common.php");
function getval($username, $column, $table, $datab){
$query = "
SELECT
id,
username,
email
FROM ".$table."
WHERE
username = :username
";
$query_params = array(
':username' => $username,
);
try
{
$stmt = $datab->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die();
}
$row = $stmt->fetch();
if($row)
{
return $row[$column];
}
}
echo getval("USERNAME", "email", "users", $db);
?>
The question you ask is very open-ended. Your biggest vector for attack is always what you do with user input (anything that a user can submit to your application/website through $_GET or $_POST variables). Certainly there are not security threats with the PHP language constructs eg. functions.
In your example I can see that you are binding the “:username” parameter but not the “:table” parameter which might be a vector for injection if you accept unsanitized user input and use it as the “$table” value.
Always be careful how your use $_GET and $_POST values… and when this becomes tedious, look for a framework to make some of this automatic.