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?

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

$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' )

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.