简体   繁体   中英

how to use an array in php mysql query?

I've been trying to retrieve all site_keywords from the database, using where site_keywords in $keyword. But it doesn't show any error or output.

$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search); 
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";

Can anyone help me with this?

There are some missing single quotes in the join (implode) function:

$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join("','",$search); 
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";

Query Without these quotes:

...where site_keywords in ('one,two,three')...

This will not produce any output or error as there are no valid results. The search query is treated as one long string.

Query With these quotes:

...where site_keywords in ('one','two','three')...

Here each query is correctly split in multiple search values.

$query = "select * from sites where site_keywords in (".implode(",",$keywords).") order by rank DESC ";

IN does a literal search, to do a "fuzzy" search you need to do something like:

$query = "SELECT * FROM sites WHERE ".implode(" OR ", array_fill(0,count($search),"site_keywords LIKE ?"); 
 //Query looks like SELECT * FROM sites WHERE site_keywords LIKE ? OR site_keywords LIKE ?

$search = array_map(function ($v) { 
    return "%$v%";
},$search); 

Now for the binding, it depends what you're using:

//MySQLi 
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, array_fill(0,count($search),"s"), ...$search); //Note, you may bet some issues with references here. 
mysqli_stmt_execute($stmt);

//PDO
$stmt = $connection->prepare($query); 
for ($i = 0;$i< $search;$i++) {
    $stmt->bindValue($i+1,$search[$i]);
} 
$stmt->execute();

Always use prepared statements to prevent SQL injection. The following code can be used as a starting point to solve your problem (needs the PDO library, http://php.net/manual/en/book.pdo.php ).

$user_query = $_REQUEST['user_query'];                      // you should better use $_GET or $_POST explicitly
$user_query = preg_replace('#\s{2,}#', ' ', $user_query);   // replace multiple spaces with a single space
$keywords = explode(' ', $user_query);                      // create the keywords array
$placeholders = array_fill(0, count($keywords), '?');       // create the placeholders array

$sql = 'SELECT *
        FROM sites
        WHERE site_keywords IN (' . implode(', ', $placeholders) . ')
        ORDER BY rank DESC';

$stmt = $db->prepare($sql);
$stmt->execute($keywords);
$result = $stmt->fetchAll();

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