-1

I have a database with four tables and I want my PHP to execute the query dynamically for one of these tables, based on the user's input.

$company = $_POST['company'];
$model = $_POST['model'];

$servername = "localhost";
$username = "user";
$password = "pass";
$database = "ref";

if ($company == "ford") {
  $table = "ref_ford";
} else if ($company = "hyundai") {
  $table == "ref_hyundai";
} else if ($company = "renault") {
  $table == "ref_renault";
} else {
  $table = "ref_fiat";
}

With this code, PHP doesn´t recognize the table, as when I selected it manually

$table = "ref_ford"

it does the query correctly.

I´ve also tried several different comparisons, both ==and ===, as well as,

$company == $_POST["ford"]

Any idea on how can I select the table based on the user's input?

        <select name="company">
          <option value = "ford">Ford</option>
          <option value = "hyundai">Hyundai</option>
          <option value = "renault">Renault</option>
          <option value = "fiat">Fiat</option>
        </select>
GGberry
  • 929
  • 5
  • 21
PatricK
  • 13
  • 1
  • 3
    Does this answer your question? [The 3 different equals](https://stackoverflow.com/questions/2063480/the-3-different-equals) – El_Vanja Dec 20 '20 at 12:38

2 Answers2

1

The problem has already been pointed out (in your if-statements, you have = when it should be == and == where it should be =) so I just wanted to show a, in my opinion, cleaner way of doing the same thing.

I would be to use an array for this. It's not only easier to read the relationships, but it also makes it easier to add/remove companies. Just add/remove them from the array.

$companyTables = [
    'ford'    => 'ref_ford',
    'hyundai' => 'ref_hyundai',
    'renault' => 'ref_renault',
    'fiat'    => 'ref_fiat',
];

// This will return the correct table if the array key exists, otherwise default to `fiat`.
$table = $companyTables[$company] ?? $companyTables['fiat'];

This would do the same as your current if/else's.

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
0

All comparison operations should be using "==" instead of "=". On the other hand,all assignment should be using "=" instead of "=="

Hence, please change

if ($company == "ford") {
  $table = "ref_ford";
} else if ($company = "hyundai") {
  $table == "ref_hyundai";
} else if ($company = "renault") {
  $table == "ref_renault";
} else {
  $table = "ref_fiat";
}

to


if ($company == "ford") {
  $table = "ref_ford";
} else if ($company == "hyundai") {
  $table = "ref_hyundai";
} else if ($company == "renault") {
  $table = "ref_renault";
} else {
  $table = "ref_fiat";
}


Ken Lee
  • 6,985
  • 3
  • 10
  • 29