如何为元素数组动态创建查询?

时间:2017-07-07 11:24:37

标签: php mysql sql

我有一个基本查询如下

$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";

我必须修改此查询以创建一个查询,其中我们从数组中获取了多个主题代码。

$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);

现在结果包含所有必需的subject_codesresult[0]=SC1result[1]=SC2等....

现在我想要修改原始查询,如下所示

$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";

请注意,我不知道 SC1 SC2等的值是什么。它取决于分支,位于$result内。

我怎样才能做到这一点?

7 个答案:

答案 0 :(得分:1)

您可以使用Mysql In 运算符 喜欢这个

SELECT * FROM files WHERE subject_code in ('SC1','SC2')";

您可以使用 implode php函数实现('SC1','SC2')
 像这样:

$subCodes = implode("','", $subject_array ); 
SELECT * FROM files WHERE subject_code in ('".$subCodes ."')"

答案 1 :(得分:1)

$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
$codes=(array)$result; //this will convert it in normal array. old school typecasting ;)
$codes=array_values($codes);
$query = "SELECT * FROM files WHERE subject_code in (".implode(",",$codes).")";
//considering result is an object of subject codes.

CODE UPDATED ABOVE 因为它是一个对象。

您不需要附加到第一个查询。只需在运算符和php implode函数中使用MySQL构建一个新查询。

答案 2 :(得分:1)

您可以使用implode将数组转换为以逗号分隔的字符串

如下所示:

$branch_array = array('subject1', 'subject2', 'subject3');
$branch = implode("','", $subject_array ); 

$query1="SELECT subject_code FROM subject WHERE sbranch  in ('".$branch."')";

结果:

 'subject1', 'subject2', 'subject3' 

希望解决您的问题

答案 3 :(得分:1)

您可以使用这样的子查询:

$query = 'SELECT * FROM files 
WHERE subject_code IN (
    SELECT subject_code FROM subject WHERE sbranch = "' . $branch . '"
)';

答案 4 :(得分:0)

SELECT * FROM files WHERE subject_code in ('SC1','SC2')

答案 5 :(得分:0)

您可以将php数组修改为逗号分隔的SubjectCodes字符串。

然后:

$query1="SELECT * FROM files WHERE subject_code in (".$NewString.") ";

$ NewString看起来像这样:

"'SC1', 'SC2', 'SC3'"

答案 6 :(得分:0)

 $result = array(0=>'SC1',1=>'SC2');  //this is your array
 $branch = implode("','", $result );
 $query .= "
   SELECT * FROM files WHERE subject_code in ('".$branch."') "; //this is query