"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does My PHP PDO Prepared Statement Throw an \"Invalid Parameter Number\" Error?

Why Does My PHP PDO Prepared Statement Throw an \"Invalid Parameter Number\" Error?

Published on 2025-01-18
Browse:355

Why Does My PHP PDO Prepared Statement Throw an \

Invalid Parameter Number Error in PHP PDO

When attempting to execute a prepared statement using PDO, you may encounter the error "SQLSTATE[HY093]: Invalid parameter number." This issue arises due to the incorrect usage of parameter markers.

The provided function add_persist uses the following prepared statement:

INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash

When binding the parameter values using execute() method, the function uses the following values:

["user_id" => $user_id, "hash" => $hash, "expire" => $future]

However, the prepared statement contains a duplicate parameter marker for hash, which is not allowed by PDO. To resolve this issue, we need to assign a unique parameter marker for each value being passed.

The corrected code would be:

$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)
);

The additional parameter :hash2 ensures that there are no duplicate parameter markers in the prepared statement, resolving the error.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3