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 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误