-2

I am trying the following elseif statement to call the correct code based on a POST from the previous page and it has been defaulting to using only the first block of code i am aware that this might not be the best way to carry out the code in this situation so i'd like to ask if anyone has a more efficient way of doing this THANKS

elseif ($toyota="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";
}
elseif ($bmw="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";
}
elseif ($subaru="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";
}
elseif ($mitsubishi="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";
}
elseif ($nissan="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";
}
elseif ($mazda="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";
}
elseif ($chrysler="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";
}

Forgot to mention,the post from html comes like "toyota=on", "bmw=on" and so on

Ahmed Bakir
  • 59
  • 1
  • 11

3 Answers3

3
$cars = array('toyota', 'bmw', 'nissan');

foreach ($cars as $car) {
    if (!isset($_POST[$car]) || $_POST[$car] != 'on') {
         continue;
    }

    $query = "SELECT * FROM `products` WHERE name LIKE '%$car%'";
    break;
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
1

There is difference between = and ==.

= assigns value, whereas == compares value.

replace all your = with ==

($toyota=="on"){

There is much better way to do that instead of using so many if else blocks. try using a varibale in the query based on the input.

sandyclone
  • 149
  • 4
0

A single = will set a value whereas a double == will test for equality

elseif ($toyota=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";
}
elseif ($bmw=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";
}
elseif ($subaru=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";
}
elseif ($mitsubishi=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";
}
elseif ($nissan=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";
}
elseif ($mazda=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";
}
elseif ($chrysler=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";
}
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46