Jump to content
  • Advertisement
Sign in to follow this  
spaceJockey123

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

This topic is 4076 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement
$newarray = array();
foreach ($array as $element)
{
$newarray[] = "actor = '" . mysql_real_escape_quote($element) . "'";
}

$query = "SELECT Film FROM table 1 WHERE (" . implode(" OR ",$newarray) . ")";

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!