I’ve been batting this one around for a bit, and I cannot seem to solve it on my own. I’ve run into known issues/features with PDO and MYSQL that have lead me to the below code.
I’m searching a database for tag IDs that match multiple criteria. I ran into a MYSQL bug that seems to have forced me to use a temporary table to house some of my results before being processed a second time. PDO would not let me reference the temporary table after the first execute (I may have been doing it wrong) or let me prepare multiple statements, so it then lead me to create a stored procedure for this call. After some recent testing I have found yet another issue/feature with PDO that does not allow me to call the stored procedure in the manner that I was looking for.
Here is the SP:
DELIMITER $$
CREATE PROCEDURE sp_searchPrevArticles(IN tagList VARCHAR(255), IN firstArticle INT(10))
BEGIN
CREATE TEMPORARY TABLE at_results (
id INTEGER(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
article_id INTEGER(10) NOT NULL,
datetime DATETIME NOT NULL,
common_tags INTEGER NOT NULL)
SELECT at.article_id, art.datetime, Count(at.article_id) AS common_tags
FROM article_tags AS at
INNER JOIN articles AS art ON at.article_id = art.article_id
WHERE at.tag_id IN (tagList)
GROUP BY at.article_id
ORDER BY common_tags DESC, art.datetime DESC;
CREATE TEMPORARY TABLE at_article
SELECT id
FROM at_results
WHERE article_id = firstArticle;
SELECT article_id
FROM at_results, at_article
WHERE at_results.id < at_article.id
ORDER BY at_results.id DESC;
END $$
DELIMITER ;
The parameter that isn’t working correctly is tagList. I create tagList with
foreach ($tag_ids as $tag) {
$tag_list = ($tag_list . $tag . ",");
}
$tag_list = rtrim($tag_list, ',');
Which gives me a dynamic list of tag ids. For this, we can say “4,3,2,1”. When I run this SP without PDO it returns the proper data set. Any time I run this with PDO it only gives me the first tag in the list. In this case it will only return results for “4”.
The PDO call I have is:
$sql = "CALL sp_searchPrevArticles(:tag_list, :first_article)";
$tag_sth = $this->db->prepare($sql);
$tag_sth->execute(array(':tag_list' => $tag_list, ':first_article' => $first_article));
$tag_sth->setFetchMode(PDO::FETCH_ASSOC);
$data = $tag_sth->fetchAll();
As I continue writing them this way I cannot help but think that I am making everything more difficult for myself. I’m still learning and this is the best solution that I have come up with so far. Anyone have an idea on how to get this functioning properly?
Any help is appreciated.
Thanks!
PDO quite simply does not handle lists properly unless they are a static length and defined like
IN(?,?,?,?). I get around it by:It’s kludge-y, but I have yet to see a real solution from PHP regarding lists of dynamic length.
I just thought of an uglier, but more compliant way to write this:
It’s rough and general, but you get the idea. Unless you’re really committed to parameterizing absolutely everything I prefer the first snippet.