Technically, it doesn't all have to be prepared, as the $pdo->query()
method will attempt to run whatever SQL you supply it as is. But from a security standpoint (and possibly other good reasons), it's generally best to use prepared statements. In your simple example where the query is just SELECT name FROM users
, there is no security risk since no external values are being used in the query. However, the moment you try to do something more likely to be done in an actual app, such as $stmt = $pdo->query("SELECT * FROM users WHERE name = '{$_GET['user_name']}');
, you are now at serious risk of an SQL injection attack. Therefore, the preferred method would be more like:
$stmt = $pdo->prepare("SELECT * FROM users WHERE name = :user_name);
$stmt->execute([:user_name => $_GET['user_name']]);
while ($row = $stmt->fetch()) {
// do something with each result row
}