Using a PHP variable in the middle of an SQL query

I have an SQL query that looks like:


SELECT Candidates.*
     , COUNT(*) AS rank
  FROM CandidateProfiles
INNER
  JOIN Candidates
    ON Candidates.CandidateID = CandidateProfiles.CandidateID 
 WHERE CandidateProfiles.ProfileID 
       IN(' . implode(',', $ckbox).') 
GROUP 
    BY Candidates.CandidateID 
HAVING COUNT(*) = 2
ORDER 
    BY Candidates.CandidateID

The 2 refers to the number of checkboxes checked in a search page.

It works as above with the 2 hard codes, but will be a different number depending on how many checkboxes are ticked on the search page.

So I have a PHP variable that I would like to insert where the two is, but I’m just not sure of the syntax.

The variable is $total; so I’ve been trying variations like:

HAVING COUNT(*) = $total;
HAVING COUNT(*) = \\"$total;\\"

Thought it might have been:

HAVING COUNT(*) = " . $total . "

No errors, but returned no results at all.

Any other suggestions most welcome.

Hi!

Have you echoed out the query and tested it on the mysql server?

If you use quotes on your query, you have no need to escape the php variable:

$myquery = “SELECT Candidates.*
, COUNT() AS rank
FROM CandidateProfiles
INNER
JOIN Candidates
ON Candidates.CandidateID = CandidateProfiles.CandidateID
WHERE CandidateProfiles.ProfileID
IN(’ . implode(‘,’, $ckbox).')
GROUP
BY Candidates.CandidateID
HAVING COUNT(
) = $total
ORDER
BY Candidates.CandidateID”;

HTH!

Mário

Resolved:

HAVING COUNT(*) = " . $total . "