[web] PHP, how to put array into a MySQL query?
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?
$newarray = array();foreach ($array as $element){ $newarray[] = "actor = '" . mysql_real_escape_quote($element) . "'";}$query = "SELECT Film FROM table 1 WHERE (" . implode(" OR ",$newarray) . ")";
Alternatively:
I prefer IN clauses over multiple OR's on the same field.
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.
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.
"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.
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?
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:
(that would only work if your values are all numeric, otherwise put quotes around the values.
$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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement