Vivek
Vivek

Reputation: 373

search all the elements of array of strings in mysql using php

I need to search all elements of an array of strings of the database and to return how many values are matched to the existing database entries..

database name = words , table name=collection , word is the coloumn in which array to bi searched

<?php
$array=array('abc','xyz','lmn','pqr');
@ $db=new mysqli('localhost','root','','words');

if(mysqli_connect_errno()) {
    echo 'Error:Could not connect to the database';
} else echo 'connected';

$db->select_db('words');

foreach($array as $s) {
    $query="select * from collection where word = '%".$s."%'";
    $result=$db->query($query);
}

if($result) echo $db->affected_rows;
$db->close();
?>

Upvotes: 0

Views: 1669

Answers (2)

Supriya Pansare
Supriya Pansare

Reputation: 559

its not feasible to run query in for loop so, you can try below solution,

$array=array('abc','xyz','lmn','pqr');     
$query="select word from collection where word LIKE '%".$s."%'";
$result=$db->query($query);
while ( $row = mysql_fetch_array($result) )
 {
   $tblarray[] =  $row['word'];
 }
foreach($tblarray as $k => $v)
{
 foreach($array AS $key => $value)
 {
   if (strpos($v, $value) !== false)
   {
    $finalarray[] = $v; 
   }
 }
}

Upvotes: -1

Lo&#239;c
Lo&#239;c

Reputation: 11942

$result = 0;
foreach($array as $s) {
    $query="select count(*) as number_match from collection where word = '%".$s."%'";
    $row = mysql_fetch_row($db->query($query));
    $result+= $row['number_match'];
}

Edit: Yet better :

$words = implode("%','%",$array);
$query="select count(*) as number_match from collection where word in ('%$words%')";
var_dump(mysql_fetch_row($db->query($query));

Upvotes: 2

Related Questions