Reputation: 15498
I was told to use PDO to safely retrieve data from a database. Now I'm wondering if this would be safe or work at all:
$dbtype = "sqlite";
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$firstName = htmlspecialchars($_POST["firstName"]);
foreach($conn->query('SELECT * FROM employeeTable WHERE firstName = ' . $firstName) as $row) {
echo $row['lastName'].' '.$row['email'];
}
Because to me it looks like it would still be possible to "inject" something into the query.
So my question is: Is that really safe and if not how exactly would I make it safe?
Upvotes: 0
Views: 544
Reputation: 1293
I think you'd better use the following to prepare, the process of preparing is to void the injection
$sql = 'SELECT * FROM employeeTable WHERE firstName = :firstName';
$sth = $conn->prepare($sql);
$sth -> bindParam(':firstName', $firstName);
$sth -> execute();
$result = $sth->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $key => $value) {
echo $value->lastName, $value->email;
}
Upvotes: 3
Reputation: 41885
Just remember to don't directly concatenate post variables to your query, just use prepared statements. And after the execution of prepared statements, you need to fetch the results:
$select = $conn->prepare('SELECT * FROM employeeTable WHERE firstName = :firstName');
$select->execute(array(':firstName' => $_POST["firstName"));
while($row = $select->fetch(PDO::FETCH_ASSOC))
echo $row['lastName'].' '.$row['email'];
}
Here is a good read:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Upvotes: 2