将多个参数传递给预准备语句

时间:2016-12-13 11:47:02

标签: php mysql prepared-statement

这是我的服务器端代码:

<?php
    include('DBconnection.php');

    $q = "";
    $q = $_REQUEST["q"];

    function getAlSubjects($searchtext){
        $connection = db_connect();
        $statement = $connection->prepare('select * from olsubjectmaster where (ifnull(?,"")="" or SubjectID like ? or SubjectID like ? ) ORDER BY SubjectID');

        $statement->bind_param(1,$searchtext,PDO::PARAM_STR, 200);
        $statement->bind_param(2,$searchtext.'%',PDO::PARAM_STR, 200);
        $statement->bind_param(3,'%'.$searchtext.'%',PDO::PARAM_STR, 200);        

        $result=$statement.execute();
        $connection.close();
        $statement.close();
        return $result;
    }

    $value='';

    while($row = getAlSubjects($q)->fetch_assoc()) {
        echo $row["SubjectID"];
    }
?>

执行此操作时,会显示以下错误:

  

致命错误:无法在第15行的D:\ xampp \ htdocs \ GetSubject.php中通过引用传递参数2

我该如何解决这个问题?  这是我的DBconnection.php文件代码

<?php
 function db_connect() {

// Define connection as a static variable, to avoid connecting more than once 
static $connection;

// Try and connect to the database, if a connection has not been established yet
if(!isset($connection)) {
     // Load configuration as an array. Use the actual location of your configuration file
    $config = parse_ini_file('config.ini'); 
    $connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}

// If connection was not successful, handle the error
if($connection === false) {
    // Handle error - notify administrator, log to a file, show an error screen, etc.
    return mysqli_connect_error(); 
}
return $connection;
 }
 ?>

1 个答案:

答案 0 :(得分:3)

是的,这是不允许的,

$statement->bind_param(2,$searchtext.'%',PDO::PARAM_STR, 200);
$statement->bind_param(3,'%'.$searchtext.'%',PDO::PARAM_STR, 200);

这些操作会导致创建新的字符串文字。字符串文字无法绑定。你需要

$param2 = $searchtext.'%';
$param3 = '%'.$searchtext.'%';
$statement->bind_param(2,$param2,PDO::PARAM_STR, 200);
$statement->bind_param(3,$param3,PDO::PARAM_STR, 200);

作为旁注,由于您要比较%searchtext%,因此无需查找searchtext%

更新:正如弗雷德指出的那样,您似乎正在使用PDO但是调用bind_param,这是mysqli api而不是PDO的一部分。 PDO中的正确全部是bindParam