0

I am using this snippet for reading data from my database, this is what I tried:

$sth = $dbh->prepare("SELECT * FROM user");
$sth->execute();

while ($user = $sth->fetch(PDO::FETCH_NUM)) {
    echo htmlspecialchars($user[1]);
}

I hope it cant be hacked using injection´s etc.

You think this is good enough, I mean I use prepared statements and

htmlspecialchars()

Did i forget anything?

user229044
  • 232,980
  • 40
  • 330
  • 338
user3297073
  • 129
  • 1
  • 12

2 Answers2

1

The section of you code that you've shown has no direct vulnerabilities because you're not evaluating any user input in your database query, therefore this is a non issue.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
1

$dbh->prepare() already does the escaping for you. There is a PDO function PDO::quote() to escape strings independently from the prepare method but as the doc says:

If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.

The use of htmlspecialchars() is unnecessary, when you are printing content from the database. The point of escaping is to prevent SQL Injections as you correctly noted. But these injections can only happen within your sql statement and only if (as Ohgodwhy mentioned) userinput from $_POST or $_GET or whaterver the user can manipulate is part of your query.

Markus Kottländer
  • 8,228
  • 4
  • 37
  • 61