Home >Database >Mysql Tutorial >Why Does `bindParam` Fail with Constant Values in PDO?

Why Does `bindParam` Fail with Constant Values in PDO?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 03:21:101025browse

Why Does `bindParam` Fail with Constant Values in PDO?

bindParam Error with Constant Values in PDO

When attempting to use bindParam with a constant value, such as PDO::PARAM_NULL, developers may encounter the error "Cannot pass parameter 2 by reference."

Code Snippet with the Error

try {
    $dbh = new PDO('mysql:dbname=' . DB . ';host=' . HOST, USER, PASS);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
}
catch(PDOException $e)
{
    ...
}
$stmt = $dbh->prepare('INSERT INTO table(v1, v2, ...) VALUES(:v1, :v2, ...)');
$stmt->bindParam(':v1', PDO::PARAM_NULL); // --> Here's the problem

Solution

The error occurs because bindParam takes a variable by reference and doesn't retrieve a value when called. The correct method for binding a constant value is bindValue.

Corrected Code

$stmt->bindValue(':v1', null, PDO::PARAM_INT);

Note:

Avoid using bindValue(':param', null, PDO::PARAM_NULL), as it may not be reliable.

The above is the detailed content of Why Does `bindParam` Fail with Constant Values in PDO?. 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