[web] PHP, how to put array into a MySQL query?

Started by
9 comments, last by Pete Michaud 16 years, 12 months ago
Suppose I have a combo box from a form. I assign all the elements of the combo box to an array in PHP. Next I want to do a query that involves all the elements from the array. e.g. SELECT Film FROM table1 WHERE (actor=arrayelement1 and actor=arrayelement2 and actor=arrayelement3) Is there a simple way to do this for a whole array?
Advertisement
$newarray = array();foreach ($array as $element){  $newarray[] = "actor = '" . mysql_real_escape_quote($element) . "'";}$query = "SELECT Film FROM table 1 WHERE (" . implode(" OR ",$newarray) . ")";

Alternatively:

foreach ($array as &$element)  $element = "'" . mysql_real_escape_quote($element) . "'";$query = "SELECT Film FROM table 1 WHERE actor IN (" . implode(",", $array) . ")";


I prefer IN clauses over multiple OR's on the same field.

<hr />
Sander Marechal<small>[Lone Wolves][Hearts for GNOME][E-mail][Forum FAQ]</small>

I'm very grateful. Will try this as soon as I fully wake-up.
I'm getting

"Fatal error: Call to undefined function: mysql_real_escape_quote()"

There aren't any tutorials for this on the web which I find strange. I would've thought that this was a common thing for websites.
Oops, my bad.
ok forget the question I asked before, I've found a way around that. But suppose I'm doing a search facility and once I've gotten the results from the first query i.e. films with certain actors

I want to match that with a query from another table. I.e. films above a certain price, released after this year etc.

Would I need to somehow put the results from the first query back into the array or connect to multiple tables?
ah lol I'm such a noob I was looking for a table join. I've heard of the term before I just forgot what it does anyway I think I've got it now.
Just a note, PHP best practices suggest that you use the sprintf function, so it'd actually be:

$query = sprintf("SELECT Film FROM table 1 WHERE actor IN ({1})", implode(",", $array));


(that would only work if your values are all numeric, otherwise put quotes around the values.
sprintf doesn't replace {1} but expects formatting like %d, %s, etcetera. Also, sprintf doesn't escape anything, opening you up to SQL injection attacks.

<hr />
Sander Marechal<small>[Lone Wolves][Hearts for GNOME][E-mail][Forum FAQ]</small>

This topic is closed to new replies.

Advertisement