Jump to content

Use SELECT statement to compare an array?


K_N

Recommended Posts

Lets say I have an array called $array1

 

This array contains the values value1, value2, value3

 

Right now, I have a query that says something like

SELECT * FROM table WHERE value = $array1['value1'] OR value = $array1['value2'] OR value = $array1['value3']

 

I want to be able to make this query work dynamically, so I can have any number of values in the array, and they would all be compared like the above, without having to modify the query each time a new value is added to the array.

 

What would be the proper syntax for this?

Link to comment
Share on other sites

For further consultation, I attempted some array functions that I think I did wrong.

The array $watching looks like this:

sNmO6.png

 

And here's the code I'm using:

$searchQuery = "SELECT * FROM `status` WHERE ";

foreach($watching as $section){
	$watching['watched'] = "uid = $section";
}
$searchQuery .= implode(' OR uid = ', $watching);
$searchQuery .= " ORDER BY id desc";

 

Here's the output I get:

SELECT * FROM `status` WHERE 1 OR uid = 1 OR uid = 1 OR uid = 1 OR uid = 0 OR uid = uid = 0 ORDER BY id desc

 

 

The output I would like to receive from this is more like:

SELECT * FROM `status` WHERE uid = 0 OR uid = 1 ORDER BY id desc

 

 

MySQL Version 5.1.41

Link to comment
Share on other sites

$values = array('value1', 'value2', 'value3', 'value4');
$implode_string = implode( "', '", $values );
$query = "SELECT `field1` FROM `table` WHERE `field2 IN( '$implode_string' )";

 

echo $query; returns: SELECT `field1` FROM `table` WHERE `field2` IN( 'value1', 'value2', 'value3', 'value4' )

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.