So I'm trying to take a search string (could be any number of words) and turn each value into a list to use in the following IN statement) in addition, I need a count of all these values to use with my having count filter
$search_array = explode(" ",$this->search_string);
$tag_count = count($search_array);
$db = Connect::connect();
$query = "select p.id
from photographs p
left join photograph_tags c
on p.id = c.photograph_id
and c.value IN ($search_array)
group by p.id
having count(c.value) >= $tag_count";
This currently returns no results, any ideas?
Solution:
$search_array = explode(" ",$this->search_string);
foreach ($search_array as $key => $value) {
$new_search_array[] = "'$value'";
}
$search_string = implode(',', $new_search_array);
This gives me a comma separated list
Conclusion. As you can see, SQL Server does not include arrays. But we can use table variables, temporary tables or the STRING_SPLIT function. However, the STRING_SPLIT function is new and can be used only on SQL Server 2016 or later versions.
To access the elements of an array at a given position (known as the index position), use the element_at() function and specify the array name and the index position: If the index is greater than 0, element_at() returns the element that you specify, counting from the beginning to the end of the array.
Solution. Step 1: Group the data by the field you want to check. Step 2: Left join the list of required values with the records obtained in the previous step. Step 3: Now we have a list with required values and corresponding values from the table.
$search_array = implode(",", $search_array);
because IN takes a comma separated list of values. (But you need to ensure $search_array's contents are quoted, if they're words.)
Doing it in one step might look like this:
function quoteAndComma($result, $each) {
return $result . ', "'.$each.'"';
}
$search_array = array_reduce($search_array, "quoteAndComma", '');
You should build a string from this array first:
// Don't forget to escape the data!
$search_array = array_map('mysql_real_escape_string', $search_array);
// Convert array to a string like "'one', 'two', ..."
$search_values = "'" . implode("', '", $search_array) . "'";
// Build a query
$query = "select ... c.value IN ($search_values) ..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With