[Solved] Is this prepared statement?


Yes you are using a prepared statement with a parameter. That’s the right thing to do. Parameters are the best way to write safe SQL statements in the majority of cases. There are just a few edge cases where they don’t help (see my answer to how safe are PDO prepared statements)

I can suggest some small changes based on how I would write the code.

$sql = "SELECT id, password FROM users133 WHERE username=:username";

Avoid SELECT *, always spell out your columns explicitly. See

$stmt = $db->prepare($sql);
$stmt->execute(['username' => $username]);

If you have enabled PDO exceptions, this is okay, because any SQL error will interrupt the code and throw an exception. But if you have not enabled exceptions, you should always check the return value of both prepare() and execute(). See http://php.net/manual/en/pdo.error-handling.php and http://php.net/manual/en/pdo.errorinfo.php

The syntax of array() is from old PHP versions, and since PHP 5.4 you can use the shorter syntax with square brackets.

You don’t need to use : in your key for the PDO param. Only in the SQL string. In old versions of PDO you needed : in both places, but not anymore.

while (row = $stmt->fetch()) {
    $hash = $row['password'];
    if (password_verify($password, $hash)) {
        $_SESSION['loggedIn'] = $row['id'];
        header("location: ?page=profile");
    }else{
        header("location: ?page=loginfailed");
    }
}
header("location: ?page=loginfailed");

The above avoids calling rowCount(). If there are no rows, then while() naturally finishes without doing one loop, and then it falls through to the last header() call.

I prefer to avoid calling rowCount() because it’s confusing to remember when it works and when it doesn’t work. The rowCount() will return 0 before the client has fetched all rows from the MySQL server. Sometimes executing the query implicitly fetches all rows into client memory, then calling fetch() just iterates over them. This is called a buffered query. But non-buffered queries are useful if your result will have too many rows to buffer. So it’s not always clear when rowCount() will return the accurate count.

2

solved Is this prepared statement?