简体   繁体   中英

How to add PHP inside SQL Query in PHP file

I have a Array named $category which has values in string format. I want to add it in query such that I can filter the results by category.

Something Like this:

SELECT * FROM ig_accounts WHERE category IN (Array Values here)

So the query becomes something like:

SELECT * FROM ig_accounts WHERE category IN ('text','fashion','sports')

Right now I am using this, which has an error:

$query = "SELECT * FROM ig_accounts WHERE category IN (".
                for($i=0;$i<$category[NULL];$i++)
                {
                echo '$category[$i]';   
                }
                .")";

You can use the implode function depending on the structure of your array

http://php.net/manual/fr/function.implode.php

$query = "SELECT * FROM ig_accounts WHERE category IN ('" . implode("','", $category) . "')";

You can do something like this

$query = "SELECT * FROM ig_accounts WHERE category IN ('" . implode("','", $category) . "')";

http://php.net/manual/en/function.implode.php implode — Join array elements with a string

<?php
$a1 = array("1","2","3");
echo "a1 is: '".implode("','",$a1)."'<br>";

?>

will produce:
===========
a1 is: '1','2','3'

Is $category provided by the user? If so, beware, and consider prepared statements. Try the following.

$sql='SELECT * FROM ig_accounts WHERE category IN ('.implode(',', array_fill(0,count($category ), '?')).')';
$stmt=$myDB->prepare($sql);
$stmt->execute($category ); 

Reference http://php.net/manual/en/book.pdo.php

Use join to make the string from an array. This is the way how can you do the thing.

$arr = array();
for($i = 0; $i < count($category); $i++){
    $arr[] = $category[$i];
}
$in = join(" , ", $arr);
$query = "SELECT * FROM ig_accounts WHERE category IN (".$in.")";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM