0

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();
?>
4
  • 1
    it should be where word LIKE '%".addslashes($s)."%'" Commented Feb 27, 2014 at 9:01
  • 1
    A SELECT query doesn't update the affected rows counter. Commented Feb 27, 2014 at 9:02
  • 1
    @Andrew addslashes() is not meant for SQL escaping. Commented Feb 27, 2014 at 9:03
  • Btw, if the array is not too big you can generate a single query that will give you the answer in one shot, i.e. WHERE word LIKE ? OR word LIKE ? OR ... Commented Feb 27, 2014 at 9:05

2 Answers 2

2
$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));
Sign up to request clarification or add additional context in comments.

Comments

-1
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; 
   }
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.