douou0977 2016-08-13 20:36
浏览 44
已采纳

动态sql查询 - 绑定变量数与令牌数不匹配

I'm trying to create a dynamic query according to the information it gets.

When $query2 is for example: 'type' => 'PvP', 'online' => 'Premium'

And $query is: SELECT * FROM dispserveur WHERE type = :type AND online = :online

This is working,

$req = $bdd->prepare("$query");
$req->execute(array('type' => 'PvP', 'online' => 'Premium'));

But when i use the $query2 variable in the execute, it's not working.

$req = $bdd->prepare("$query"); //C
$req->execute(array($query2));

I get the same error each time.

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

This is the code,

unset($sql);
unset($sql2);

if (isset($type2) AND $type2 != "all") {
$sql[] = " type = :type ";
$sql2[] = " 'type' => '$type2'";

}

if (isset($online2) AND $online2 != "all") {
$sql[] = " online = :online ";
$sql2[] = " 'online' => '$online2'";

}
if (isset($version2) AND $version2 != "all") {
$sql[] = " version LIKE :version ";
$sql2[] = " 'version' => %$version2%";

}

$query = "SELECT * FROM dispserveur";

if (!empty($sql)) {
$query .= ' WHERE ' . implode(' AND ', $sql);
}
if (!empty($sql2)) {
$query2 = implode(', ', $sql2); 
}

echo $query;
echo "<br />";
echo $query2;

$req = $bdd->prepare("$query"); //C
$req->execute(array($query2));
while ($red = $req->fetch())
{echo "$red[ip]<br />";}

Thanks for your help !

  • 写回答

2条回答 默认 最新

  • duanjianhe1388 2016-08-13 20:43
    关注

    The parameter of execute() should be an associative array whose keys match that :paramName. Instead, you're using $query2 which is just a string. That's why your code isn't working.

    Change:

    $sql2[] = " 'type' => '$type2'";
    $sql2[] = " 'online' => '$online2'";
    $sql2[] = " 'version' => %$version2%";
    

    to:

    $sql2['type']=$type2;
    $sql2['online']=>$online2;
    $sql2['version']=>"%$version2%";
    

    And later, change

    $req->execute(array($query2));
    

    to

    $req->execute($sql2);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法