Home >Database >Mysql Tutorial >Why Does My PHP PDO Prepared Statement Throw 'Invalid Parameter Number'?

Why Does My PHP PDO Prepared Statement Throw 'Invalid Parameter Number'?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 07:22:11327browse

Why Does My PHP PDO Prepared Statement Throw

PDO Exception: Invalid Parameter Number in PHP

Encountering the error "SQLSTATE[HY093]: Invalid parameter number" when attempting to use PHP's PDO? The underlying cause may be related to parameter usage in prepared statements.

Problem Description:

In the provided code snippet:

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

There's a missing ":hash2" parameter marker in the UPDATE clause. This discrepancy leads to the PDO exception because PDO requires unique parameter markers for each value to be bound in the statement.

Solution:

Adjust the prepared statement's SQL query to the following:

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

Correspondingly, modify the execute() statement to include the ":hash2" parameter marker:

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

Background:

PDO's prepare() method requires unique parameter markers to bind values when calling execute(). Using repeated parameter markers is disallowed, and assigning multiple values to the same parameter is not supported in clauses like the "IN()" clause.

The above is the detailed content of Why Does My PHP PDO Prepared Statement Throw 'Invalid Parameter Number'?. 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