Home > Database > Mysql Tutorial > Why Does PDO Throw 'SQLSTATE[HY093]: Invalid Parameter Number' and How Can I Fix It?

Why Does PDO Throw 'SQLSTATE[HY093]: Invalid Parameter Number' and How Can I Fix It?

Barbara Streisand
Release: 2024-12-11 10:17:10
Original
455 people have browsed it

Why Does PDO Throw

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";
Copy after login

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";
Copy after login
$stm->execute(
    array(":user_id" => $user_id, 
          ":hash" => $hash, 
          ":expire" => $future,
          ":hash2" => $hash)
);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template