I have a mysql query that seperates an array of variables and uses each variables to compare inside the database. The query uses a OR clause and I want to make it so it can also use an AND clause. The trick is I want the left side of the query to use the OR clause and the right side use the OR and AND clause. This probably doesnt make sense so let me try to make an example code.

$query = "SELECT * FROM table WHERE name ='$name' OR (number ='$number' AND number2 = '$number2')";

I have not tried making this code at all because I believe it is beyond my knowledge to even attempt. The sample code may be how you actually do it but I do not know.

Here is my actually query

$query = "SELECT * FROM comments WHERE commenter_username IN (" . join(',', $list) . ") Or Number IN (" . join(',', $list) . ") ORDER BY comment_id DESC";

What I want my code to look like and work would be something like this,

$query = "SELECT * FROM comments WHERE commenter_username IN (" . join(',', $list) . ") Or (Number IN (" . join(',', $list) . ") AND Number2 IN (" . join(',', $list2) . ")) ORDER BY comment_id DESC";

Recommended Answers

All 2 Replies

Member Avatar for diafol

I can't see anything wrong with your query, other than the fact that you seem to be looking for data in the same list for the 'left hand' and the first 'right hand' ($list).

You could create the arrays before writing the SQL:

$sqlList1 = implode(',',$list);
$sqlList2 = implode(',',$list2);
$sqlList3 = implode(',',$list3);

$query = "SELECT * FROM comments WHERE commenter_username IN ($sqlList1) Or (Number IN ($sqlList2) AND Number2 IN ($sqlList3)) ORDER BY comment_id DESC";

This is assuming that you have fieldnames Number and Number2.

Thank you so much! It works perfectly!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.