I’ve looked all over the interwebs, and cannot find that simple answer I’m looking for – possibly because it doesn’t exist, but.. possibly because I don’t know the correct terms to search for.
ok, so, i’ve got a variable – it’s actaully a key value pair in an array that i’m passing into my function. the key is args[comments_mentioned] and the value is dynamically generated for me – it’s ALWAYS going to be number, separated by commas (i.e. 1,2,3,4,5)
so, just to be super clear:
$args[comments_mentioned] == "1,2,3,4"; //could be any amount of number, not just 1,2,3,4,5
i’d like to pass this into a sql statement as a variable to use in an “IN” clause, like so:
$sr_sql = <<<SQL
SELECT *
FROM $wpdb->commentmeta
WHERE meta_value = %s
AND comment_ID in ($args[comments_mentioned])
ORDER BY meta_id DESC
SQL;
Then, Prepare it using the wordpress prepare and get results
$sr_query = $wpdb->prepare( $sr_sql, $args[user_id]) );
//receive the correct sql statement, and plug 'er in.
$sr_comment_rows = $wpdb->get_results($sr_query);
and run my foreach loop:
foreach ($sr_comment_rows as $sr_comment) {
$sResults .= 'do something with $sr_comment';
}
now, i realize the code above won’t work – i can’t just pass the variable in there like that. BUT, i can’t pass it as a string (%s), because it wraps it in ‘1,2,3,45’, and so it looks for the entire string, and not each number. I can’t pass it as an int (%d), because of the commas…
In other posts, they mentioned create a temp table or variable, but, i’m not sure if that’s the correct way to do it in mysql, or how to reference it once I do.
so, how do I do this? preference for actual code that works 😉
Thank you for reading and helping out!
One option, if you cannot normalize your data, is to enclose your string in commas such that it be
",1,2,3,4,"
and then you could do:which will match if it finds a eg.
',3,'
in',1,2,3,4,'
(Using 3 as an example)I believe this should be enough:
It will be result something like:
If your mainly issue is regarding the in clause, so you will not have problems if you use double quotes and single variable as illustrated above.