Home >Database >Mysql Tutorial >Why Can't I Use `bindParam` with Constant Values in PDO?

Why Can't I Use `bindParam` with Constant Values in PDO?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-08 05:10:12293browse

Why Can't I Use `bindParam` with Constant Values in PDO?

Can't Pass Parameter By Reference with bindParam for Constant Values?

When working with PDO, you may encounter the error "Cannot pass parameter 2 by reference" when using bindParam with constant values. Here's why and how to resolve it:

The Issue

bindParam expects a variable to bind as a reference, not a constant value. Constant values like null, '' (empty string), or PDO::PARAM_NULL cannot be passed by reference.

The Solution

To bind constant values, use bindValue instead of bindParam. bindValue accepts a literal value without passing it by reference. The following code uses bindValue to insert a NULL value:

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

Note:

  • bindParam requires a variable because it creates a reference to the variable's value.
  • bindValue does not create a reference and accepts a constant value directly.
  • PDO::PARAM_NULL cannot be used with bindValue.

The above is the detailed content of Why Can't I Use `bindParam` 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