2

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

1
  • loop through your array and build like query Commented Jun 2, 2014 at 9:54

5 Answers 5

4

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

Comments

0

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;

6 Comments

I wonder will it comply with SQL syntax accepted by the engine.
@Vesper is there any issue?
This is awesome Rakesh very nice.
@RakeshSharma Maybe it's just me, I've yet to face an SQL syntax of multiple pattern matches with "like" condition. I have only seen syntax like where field like "%string%" or field like "%otherstring%", not where field like "%string%" and "%otherstring%". So issues can arise, if this syntax is not valid.
@Vesper i agree with you but answer gives according to OP's question, it's depend on what your requirements
|
0
<?php 
$i=0;
$brand=array("Volvo","BMW","Toyota","Honda","Suzuki");
$qry = 'select * from brand where brand Like '% $brand[i] `enter code here`%'';
$i++;
?>

Comments

0

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

Comments

-1

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])%'";

3 Comments

This is not an answer what OP asked for
That's what he did with $brand = ["Sozuki","Honda"]. And this is not what the OP is looking for.
The array is said to be dynamic, so you can't set a fixed amount of items to put into the $qry.

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.