Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use an array within a SQL query

Tags:

arrays

php

mysql

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

like image 354
ThinkingInBits Avatar asked May 18 '10 07:05

ThinkingInBits


People also ask

Can we use array in SQL query?

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.

How do you access an array in SQL?

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.

How do I select an array column in SQL?

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.


2 Answers

$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", '');
like image 145
Frank Shearar Avatar answered Oct 20 '22 00:10

Frank Shearar


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) ..."
like image 37
Alexander Konstantinov Avatar answered Oct 20 '22 00:10

Alexander Konstantinov