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.