duanpuqi9965 2013-12-02 18:51
浏览 44
已采纳

复杂查询,重复参数在PHP PDO中不起作用

I have a somewhat complex query (using a subquery) for an election database where I'm trying to get the number of votes per particular candidate for a position.

The headers for the votes table are: id (PRIMARY KEY), timestamp, pos1, pos2, ..., pos6 where pos1-pos6 are the position names. A cast ballot becomes a new row in this table, with the member id number of the selected candidate (candidates are linked to profiles in a "membership" table in the database) stored as the value for each position. So for instance, one row in the database might look like the following (except with the actual 6 position names):

id    timestamp    pos1   pos2   pos3 (and so on)
=================================================
6     1386009129   345    162    207

I want to get the results for each position using PHP PDO, listing for each position the candidate's name and the number of votes they have received for this position. So the raw database results should appear as (for "pos1", as an example):

name         votecount
======================
Joe Smith    27
Jane Doe     45

I have a raw SQL query which I can successfully use to get these results, the query is (making pos1 the actual column/position name President):

SELECT (SELECT fullname FROM membership memb WHERE member_id=`President`) name, count(`President`) votecount FROM `election_votes` votes GROUP BY `President`

So as you can see, the position name (President, here) is repeated 3 times in the query. This seems to cause a problem in the PHP PDO code. My code is as follows:

$position = "President";   // set in earlier code as part of a loop

$query = "SELECT (SELECT fullname FROM membership memb WHERE member_id=:pos1) name, count(:pos2) votecount FROM `election_votes` votes GROUP BY :pos3";
$query2 = "SELECT (SELECT fullname FROM membership memb WHERE member_id=$position) name, count($position) votecount FROM `election_votes` votes GROUP BY $position";  // NOT SAFE!

$STH = $DBH->prepare($query);
$STH->bindParam(':pos1', $position);
$STH->bindParam(':pos2', $position);
$STH->bindParam(':pos3', $position);
$STH->execute();

while($row = $STH->fetch(PDO::FETCH_ASSOC)) {
  print_r($row);
  // I'd like to do other things with these results
}

When I run this, using the query $query, I don't get results per-person as desired. My output is:

Array
(
    [name] => 
    [votecount] => 47
)

where 47 is the total number of ballots cast instead of an array for each candidate contianing their name and number of votes (out of the total). However if I use the obviously insecure $query2, which just inserts the value of $position into the query string three times, I get the results I want.

Is there something wrong with my PHP code above? Am I doing something that's impossible in PDO (I hope not!)? My underlying database is MySQL 5.5.32. I've even tried replacing the three named parameters with the ? unnamed ones and passing an array array($position, $position, $position) into the $STH->execute() method with no greater success.

  • 写回答

1条回答 默认 最新

  • dongshimao7115 2013-12-02 20:11
    关注

    Your query isn't complex. I think part of the confusion is that you aren't constructing the basic SQL properly. You are attempting to treat "President" as both a value and column. The final SQL should look something like this:

    SELECT 
        `fullname` AS `name`, 
        COUNT(`id`) AS `votecount` 
    FROM 
        `election_votes` AS `votes` 
    LEFT JOIN 
        `membership` AS `memb` ON `member_id` = `president` 
    GROUP BY 
        `pos1`
    

    You join the election_votes table to the membership table where the value in column pos1 equals the value in column member_id.

    NOTE: you cannot use parameters with table and column names in PDO (Can PHP PDO Statements accept the table or column name as parameter?), so you have to escape those manually.

    /**
     *  Map positions/columns manually.  Never use user-submitted data for table/column names
     */
    $positions = array('President' => 'pos1', 'Vice-president' => 'pos2');
    
    $column = $positions['President'];
    

    You should be able to re-write your query in PDO as:

    /**
     *  Get election results for all candidates
     */
    $sql = "SELECT 
                `fullname` AS `name`, 
                COUNT(`id`) AS `votecount` 
            FROM 
                `election_votes` AS `votes` 
            LEFT JOIN 
                `membership` AS `memb` ON `member_id` = `".$column."` 
            GROUP BY 
                `".$column."`";
    

    As you can see there's nothing to bind in PDO with this particular query. You use BindParam to filter values that appear in the WHERE clause (again: not table/column names). For example:

    /**
     *  Get election results for person named 'Homer Simpson'
     */
    $sql = "SELECT 
                `fullname` AS `name`, 
                COUNT(`id`) AS `votecount` 
            FROM 
                `election_votes` AS `votes` 
            LEFT JOIN 
                `membership` AS `memb` ON `member_id` = `".$column."` 
            WHERE 
                `fullname` = :fullname:
            GROUP BY 
                `".$column."`";
    $STH = $DBH->prepare($sql);
    $STH->bindParam(':fullname', 'Homer Simpson');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下