How do I filter results when a variable is an array?

Hello,

Here is my sql statement.:

$sql = "SELECT ticket, o_time, type, size, item, o_price, s_l, t_p, c_time, c_price, profit
			   FROM data
			   ORDER BY c_time";

I want to add a WHERE condition to filter my results.
The variable used is an array. how do I add this condition to the function?
Here is one of my attempts.:

function closed_pos_all()
{	
	global $db;
	$days = [3,5];
	try
	{
		$sql = "SELECT ticket, o_time, type, size, item, o_price, s_l, t_p, c_time, c_price, profit
			   FROM data
			   WHERE DAYOFWEEK(c_time) IN $days
			   ORDER BY c_time";
		$stmt = $db->prepare($sql);
		$stmt->execute();
		
		if($stmt->rowCount() == 0)
		return 0;
		else
		return $stmt->fetchAll(PDO::FETCH_ASSOC);
		
	}
	catch(Exception $e) 
	{
	   return false;        
	}
}

What is the right way to use a variable which happens to be an array?

Thanks

Hi @erezvol,

You can do the following:

$daysQuery = join("','", $days);

$sql = "SELECT ticket, o_time, type, size, item, o_price, s_l, t_p, c_time, c_price, profit
			   FROM data
			   WHERE DAYOFWEEK(c_time) IN ('$daysQuery')
			   ORDER BY c_time";

DAYOFWEEK is integer based, you dont need the strings. Just implode the array around commas.

1 Like