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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!