douzhi3667 2015-05-29 13:30
浏览 186
已采纳

绑定准备语句的多个参数

My PHP looks like this:

$sql1="SELECT @rownum := @rownum + 1 Rank, q.* FROM (SELECT @rownum:=0) r,(SELECT  * ,sum(`number of cases`) as tot, sum(`number of cases`) * 100 / t.s AS `% of total` FROM `myTable` CROSS JOIN (SELECT SUM(`number of cases`) AS s FROM `myTable` where `type`=:criteria and `condition`=:diagnosis) t where `type`=:criteria and `condition`=:diagnosis group by `name` order by `% of total` desc) q"";
$stmt = $dbh->prepare($sql1);
$stmt->bindParam(':criteria', $search_crit, PDO::PARAM_STR);
$stmt->bindParam(':diagnosis', $diagnosis, PDO::PARAM_STR);
$stmt->execute();
$result1 = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result1);

I'm getting an error on this line: $stmt->execute();

The error says:

PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number' in php/rankings.php:39

Stack trace:

"#"0 php/rankings.php(39): PDOStatement->execute()

"#"1 {main} thrown in php/rankings.php on line 39

How can I do fix this? I know I can pass multiple variables with a prepared statement, but I'm not quite sure how to do it.

  • 写回答

2条回答 默认 最新

  • douqin231881 2015-05-29 14:01
    关注

    You can use parameters only once in a query

    $sql1="SELECT @rownum := @rownum + 1 Rank, q.* FROM (SELECT @rownum:=0) r,(SELECT  * ,sum(`number of cases`) as tot, sum(`number of cases`) * 100 / t.s AS `% of total` FROM `myTable` CROSS JOIN (SELECT SUM(`number of cases`) AS s FROM `myTable` where `type`=:criteria and `condition`=:diagnosis) t where `type`=:criteria2 and `condition`=:diagnosis2 group by `name` order by `% of total` desc) q";
    $stmt = $dbh->prepare($sql1);       
    $stmt->execute(array(':criteria' => $search_crit, ':diagnosis' => $diagnosis, ':criteria2' => $search_crit, ':diagnosis2' => $diagnosis));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?