2021年4月6日星期二

PHP ODBC PDO bindParam causing "Must Declare Scalar variable @P1"

Long story short I need to connect to a Micrsoft Azure database using PHP, PDO, and ODBC. However I am unable to use parameters in the query without getting the error below (I have removed some information).

[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Must declare the scalar variable "@P1".  RequestId: TDS;;7  Time: (SQLExecute[40000] at /ext/pdo_odbc/odbc_stmt.c:259)'  

Here is my code:

    // Establish connection      $db = new \PDO($dsn, $user, $password);        $lastName = '%{Bank2}%';        // Option 1 - Does not work      $query = "SELECT * FROM contact WHERE lastName LIKE ?";      $prep = $db->prepare($query);      $prep->execute([$lastName]);      $results1 = $prep->fetchAll(PDO::FETCH_ASSOC);      $error1 = $prep->errorInfo();        // Option 2 - Does not work      $query = "SELECT * FROM contact WHERE lastName LIKE ?";      $prep = $db->prepare($query);      $prep->bindParam(1, $lastName);      $prep->execute();      $results2 = $prep->fetchAll(PDO::FETCH_ASSOC);      $error2 = $prep->errorInfo();        // Option 3 - Does not work      $query = "SELECT * FROM contact WHERE lastName LIKE :lastName";      $prep = $db->prepare($query);      $prep->bindValue(':lastName', $lastName);      $prep->execute();      $results3 = $prep->fetchAll(PDO::FETCH_ASSOC);      $error3 = $prep->errorInfo();  

I have tried adding the param type to the binding $prep->bindValue(':lastName', $lastName, PDO::PARAM_STR) and that doesn't resolve anything

I know that my connection is good because the below query works fine and returns results:

    $query = "SELECT * FROM contact WHERE lastName LIKE '%Bank2%'";      $prep = $db->prepare($query);      $prep->execute();      $results = $prep->fetchAll(PDO::FETCH_ASSOC);  

Any ideas with why this is not working?

This is running on PHP 7.4.5 using the PHP installation instructions: https://www.php.net/manual/en/ref.pdo-odbc.php

./configure --with-pdo-odbc=unixODBC,/usr/local  
https://stackoverflow.com/questions/66911474/php-odbc-pdo-bindparam-causing-must-declare-scalar-variable-p1 April 02, 2021 at 04:58AM

没有评论:

发表评论