Home > Software engineering >  PHP SQL shows error while using simple array
PHP SQL shows error while using simple array

Time:10-21

The following SQL PHP query shows error, why ?

$plays = array("bionic","user54");
// Attempt select query execution
$sql = "SELECT * FROM tbl_product WHERE status='winning' AND agent IN (" . implode(",",  $plays) . ");";

Error

ERROR: Could not able to execute SELECT * FROM tbl_product WHERE status='winning' AND agent IN (bionic,user54);. Unknown column 'bionic' in 'where clause'

it says column 'bionic' in error, but bionic is not a column, its just a username in column agent

Instead of array if I use agent='bionic' it will show results.

CodePudding user response:

You have to implode them with quotes around the individual values. The shortest way I can think of is:

$values = "'". implode("','", $plays)."'"

$sql = "SELECT * FROM tbl_product WHERE status='winning' AND agent IN (" . $values . ");";

Essentially you were generating sql like:

IN ( bionic, user54 )

Note the lack of quotation marks which means it's trying to use those names as column names.

You want to generate:

IN ('bionic','user54') for it to compare values.

But I will offer you a word of warning: You should always try to use an ORM or escape utilities to prevent SQL injection.

  • Related