如何在SQL查询中使用数组

时间:2010-05-18 07:51:25

标签: php mysql arrays

所以我试图获取一个搜索字符串(可能是任意数量的单词)并将每个值转换为一个列表以在以下IN语句中使用)此外,我需要计算所有这些值以用于我有计数过滤器

$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";

目前没有结果,有什么想法吗?

解决方案:

$search_array = explode(" ",$this->search_string);

foreach ($search_array as $key => $value) {

    $new_search_array[] = "'$value'";

}

$search_string = implode(',', $new_search_array);

这给了我一个以逗号分隔的列表

8 个答案:

答案 0 :(得分:6)

$search_array = implode(",", $search_array);

因为IN采用逗号分隔的值列表。 (但是你需要确保引用$ search_array的内容,如果它们是单词的话。)

一步完成可能如下所示:

function quoteAndComma($result, $each) {
  return $result . ', "'.$each.'"';
}

$search_array = array_reduce($search_array, "quoteAndComma", '');

答案 1 :(得分:4)

您应首先从此数组构建一个字符串:

// 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) ..."

答案 2 :(得分:0)

使用

and c.value IN (implode(', ', $search_array))

$ search_array是一个直接连接成字符串的数组。在执行此操作之前,您需要将其转换为字符串。

另外,为什么你没有回应你的sql语句,看你实际上是在为MySQL服务呢?

答案 3 :(得分:0)

IN需要以逗号分隔的值列表,(如果它们是字符串则引用)。 你对$ this-> search_string的价值是什么? 将它爆炸成一个数组是行不通的...尝试回显你的$查询,看看到底是什么。

答案 4 :(得分:0)

...

$search_array = explode(" ",$this->search_string);
$search = implode(",", $search_array);
$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)
          group by p.id
          having count(c.value) >= $tag_count";

答案 5 :(得分:0)

我不是PHP开发人员,请原谅我,如果我错过了什么,但数组值应该用逗号和单引号括起来:

WHERE c.value IN ('a','b','c')

答案 6 :(得分:0)

你没有以正确的方式填充你的IN语句,你有两个选择,要么传递用逗号分隔的搜索字符串,要么自己做,如:

$search_array = explode(" ", $this->search_string);

for ($i = 0; $i < count($search_array); $i++)
{
   $search_array[$i] = "'" . $search_array[$i] . "'";
}

$list = implode(",", $search_array);

$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 ($list)
          group by p.id
          having count(c.value) >= $tag_count";

答案 7 :(得分:0)

    $search_array = explode(" ",$this->search_string);

    foreach ($search_array as $key => $value) {

        $new_search_array[] = "'$value'";

    }

    $search_string = implode(',', $new_search_array);