Home >Backend Development >PHP Tutorial >Why Does My PHP PDO Code Throw a \'SQLSTATE[HY093]: Invalid parameter number\' Error?

Why Does My PHP PDO Code Throw a \'SQLSTATE[HY093]: Invalid parameter number\' Error?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 06:51:10824browse

Why Does My PHP PDO Code Throw a

PDOException: "SQLSTATE[HY093]: Invalid parameter number" in PHP

When encountering the error "SQLSTATE[HY093]: Invalid parameter number" while using PHP's PDO, it typically indicates an issue with the parameter binding in the SQL statement. In this specific case, the number of named placeholders in the prepared SQL statement does not match the number of values passed to the execute() method.

The provided code попытка inserted into the persist table, with the unique columns user_id, hash, and expire, and updates the hash column if a row with the provided user_id already exists. However, the SQL statement contains a duplicate named parameter marker for :hash.

To resolve this error, you can use a different named parameter for the ON DUPLICATE KEY UPDATE clause. Here's the corrected code:

$sql = "INSERT INTO persist (user_id, hash, expire)
        VALUES (:user_id, :hash, :expire)
        ON DUPLICATE KEY UPDATE hash=:hash2";

$stm = $db->prepare($sql);
$stm->execute(
    array(
        ":user_id" => $user_id,
        ":hash" => $hash,
        ":expire" => $future,
        ":hash2" => $hash,
    )
);

In this corrected version, the :hash2 parameter is used to resolve the binding issue, ensuring that the SQL statement has the correct number of placeholders and values.

The above is the detailed content of Why Does My PHP PDO Code Throw a \'SQLSTATE[HY093]: Invalid parameter number\' Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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