SQLSTATE[HY093]: Invalid Parameter Number with PDO
When attempting to execute a function, an error message indicating "SQLSTATE[HY093]: Invalid parameter number" may appear. This issue arises due to a misunderstanding of the behavior of named parameters with PDO.
The function you provided includes the following code:
$sql = "INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash";
When defining named parameters for a SQL statement, it's crucial to ensure that each unique parameter marker is used only once. However, in this case, ":hash" is used twice, which results in the error.
To resolve this issue, you need to assign a unique parameter marker for each value you pass to the statement when calling PDOStatement::execute():
$sql = "INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash2";
$stm->execute( array(":user_id" => $user_id, ":hash" => $hash, ":expire" => $future, ":hash2" => $hash) );
The resulting SQL query will successfully insert or update the "persist" table without encountering the invalid parameter number error.
The above is the detailed content of Why Does PDO Throw 'SQLSTATE[HY093]: Invalid Parameter Number' and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!