0

I have five tables in a MySQL database.

Based on user selection in an HTML form, data is dropped into the relevant table.

Here's a simplified example of the PHP that handles the task:

if ( $category == "apple" ) {
    $sql = "INSERT INTO fruits (category,email) VALUES ('$category','$email')";
} elseif ( $category == "broccoli" ) {
    $sql = "INSERT INTO vegetables (category,email) VALUES ('$category','$email')";
} elseif ( $category == "bread" ) {
    $sql = "INSERT INTO grains (category,email) VALUES ('$category','$email')";
} elseif ( $category == "chicken" ) {
    $sql = "INSERT INTO meats (category,email) VALUES ('$category','$email')";
} else {
    $sql = "INSERT INTO catchall (category,email) VALUES ('$category','$email')";
}

This script works as intended. When a user selects any of the category values listed above, the input is dropped into the proper table.

A problem arises, however, when I assign multiple values to the $category variable. For example, the user can select from multiple fruits, each of which should go into the "fruits" table.

Referring to the script above, if I adjust the initial if statement to:

if ( $category == "apple" || "bananas" || "oranges" ) {

... leaving everything else the same, the script no longer works.

Now all input submitted gets dropped into the "fruits" table. Even "broccoli", "bread" and "chicken" go into "fruits". Random values, which should go into the "catchall" table, also go into "fruits".

Just wondering what I'm missing. Thanks.

david
  • 3,225
  • 9
  • 30
  • 43
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 1
    `if ( $category == "apple" || "bananas" || "oranges" ) {` is equivalent to `if ( ($category == "apple") || ("bananas") || ("oranges") ) {` -- should now be easier to see why the behavior is not as expected. – user2864740 Aug 15 '18 at 02:46

1 Answers1

2

Your usage of your code is wrong. It should be like this.

if ( $category == "apple" || $category == "bananas" || $category == "oranges" ) {

There is a better way to write the code that gives similar results.

if (in_array($category, array("apple", "bananas", "oranges"))) {
david
  • 3,225
  • 9
  • 30
  • 43