M Fayyaz
M Fayyaz

Reputation: 141

How to match a word from string and retrieve data in SQL Query and PHP?

I have a MySql Table just like this

Brand 
--------
Honda
Sozuki
Oddi
.
.
.

Now there is an dynamic array in PHP :

$brand = ["Sozuki","Honda"]

The Question is how to retrieve data that matches the word in above array. I tried this :

$qry = 'select * from brand where brand Like '% $brand[0] %' and '% $brand[1] %';

It works fine but what would I do if I have no specific length of array, you can say dynamic array. Any solution will be appreciated Thanks

Upvotes: 2

Views: 157

Answers (5)

Michel Tomé
Michel Tomé

Reputation: 389

You could try:

$qry = 'select * from brand where brand Like ';
for ($i = 0; $i < sizeof($brands)-1; $i++) {
     $qry .= "'%" . $brand[$i] . "%'";
     if ($i < sizeof($brands) - 2) {
         $qry .= ' AND ';
     }
}

Upvotes: 0

Hidayath Basha
Hidayath Basha

Reputation: 1

<?php 
$i=0;
$brand=array("Volvo","BMW","Toyota","Honda","Suzuki");
$qry = 'select * from brand where brand Like '% $brand[i] `enter code here`%'';
$i++;
?>

Upvotes: 0

Rakesh Sharma
Rakesh Sharma

Reputation: 13728

try

$qry = "select * from brand where brand ";
$i=1;
$count = count($brand); 
foreach($brand as $v) {
  $a = ($i < $count ? 'and' : '');
  $qry .=  " Like '% $v %'  $a ";
  $i++;
}
echo $qry;

Upvotes: 0

Zh0r
Zh0r

Reputation: 565

Wouldn't you rather use OR instead of AND?

If so use something like this (note: UNTESTED):

<?php
$brands     = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($brands), '?'));

$db = new PDO(...);
$stmt = $db->prepare(
    'SELECT *
     FROM brand
     WHERE brand IN(' . $inQuery . ')'
);

foreach ($brands as $k => $brand)
    $stmt->bindValue(($k+1), $brand);

$stmt->execute();

// Or simply $stmt->execute($brands);

Upvotes: 4

Ing. Michal Hudak
Ing. Michal Hudak

Reputation: 5612

You should define array as

$brand = array("Sozuki","Honda");

so then you can use $brand[0], etc ...

$qry = "SELECT * FROM brand WHERE brand LIKE '%{$brand[0]}%' AND '%{$brand[1])%'";

Upvotes: -1

Related Questions