Use multiple conditions in SQL WHERE clause using OR - php

I've got the following SQL statement in my PHP code:
$strSQL = "SELECT * FROM coaches WHERE pastors='1' OR all_categories='1' ORDER BY l_name";
but the WHERE portion after the OR is ignored. Is my code correct? Is there a better way to code it?

Thanks for the suggestions. Even though people said it should work, for some reason it wasn't. The easiest solution was to simply set every true/false to 1 for those individuals who want to be in all categories instead of trying to fight against the OR which looks correct but won't work.

I am trying to get it to select database entries if there is a 1 in a particular category, in this case "pastors", or if there is a 1 in the "all_categories" category.
From the looks of it, your code does just that.
You're just forgetting ASC or DESC at the end of it.
It should look more like this:
$strSQL = "SELECT * FROM coaches WHERE pastors='1' OR all_categories='1' ORDER BY l_name ASC";

Related

PHP - Remove quotes in MySQL query [duplicate]

I am trying to refer to a column name to order a query in an application communicating with an Oracle database. I want to use a bind variable so that I can dynamically change what to order the query by.
The problem that I am having is that the database seems to be ignoring the order by column.
Does anyone know if there is a particular way to refer to a database column via a bind variable or if it is even possible?
e.g my query is
SELECT * FROM PERSON ORDER BY :1
(where :1 will be bound to PERSON.NAME)
The query is not returning results in alphabetical order, I am worried that the database is interpreting this as:-
SELECT * FROM PERSON ORDER BY 'PERSON.NAME'
which will obviously not work.
Any suggestions are much appreciated.
No. You cannot use bind variables for table or column names.
This information is needed to create the execution plan. Without knowing what you want to order by, it would be impossible to figure out what index to use, for example.
Instead of bind variables, you have to directly interpolate the column name into the SQL statement when your program creates it. Assuming that you take precautions against SQL injection, there is no downside to that.
Update: If you really wanted to jump through hoops, you could probably do something like
order by decode(?, 'colA', colA, 'colB', colB)
but that is just silly. And slow. Don't.
As you are using JDBC. You can rewrite your code, to something without bind variables. This way you can also dynamically change the order-by e.g.:
String query = "SELECT * FROM PERS ";
if (condition1){
query = query+ " order by name ";
// insert more if/else or case statements
} else {
query = query+ " order by other_column ";
}
Statement select = conn.createStatement();
ResultSet result = select.executeQuery(query);
Or even:
String columnName = getColumnName(input);
Statement select = conn.createStatement();
ResultSet result = select.executeQuery("SELECT * FROM PERS ORDER BY "+columnName);
ResultSet result = select.executeQuery(
"SELECT * FROM PERS ORDER BY " + columnName
);
will always be a new statement to the database.
That means it is, like Thilo already explained, impossible to "reorder" an already bound, calculated, prepared, parsed statement. When using this result set over and over in your application and the only thing, which changes over time is the order of the presentation, try to order the set in your client code.
Otherwise, dynamic SQL is fine, but comes with a huge footprint.

SQL update with multiple criteria

I know this is quite simple but I've been looking at this for awhile and can't seem to identify what the issue is. I want to update a row in a table using two criteria. When I use either criteria, the table updates fine but when I combine them, it doesn't work.
This is the query
$updatequery = "UPDATE query SET audio='$finalpath' WHERE content='$title' AND WHERE userid LIKE '%$regID%'";
An example of the reg id:
APA91bGHS59rrpM0sbX9PIYT3SzXs-W1yEtGa2xGMGJXi8O1vW2SrgN7koHDj2o6ZwKvkd3TxtzhktsiVtQNSYQRa4uNDF7Yy0VOf0BJfQOnJWMtN2WBQjmVDsuU-0GxmceNLd8SWqOM
An example of content :
Where can I find a car
You only need to use the where keyword once:
$updatequery =
"UPDATE query SET audio='$finalpath' WHERE content='$title' AND userid LIKE '%$regID%'";
# "WHERE" removed here ------------------------------------^
Mandatory comment:
Using string manipulation like this leaves your code vulnerable to SQL-injection attacks. You should really consider using prepared statements instead.
WHERE content='$title' AND userid LIKE '%$regID%'
Where is needed only once
You can have only one WHERE clause, so this is a syntax error:
WHERE content='$title' AND WHERE userid LIKE '%$regID%'
Combine the logic in a single clause:
WHERE content='$title' AND userid LIKE '%$regID%'
The WHERE clause essentially works like conditionals in any other language. You can build up as complex a tree of boolean conditions as you like, as long as the whole thing resolves down to a boolean then it's fine.
Your query is wrong.
Try this:
$updatequery = "UPDATE query SET audio='$finalpath' WHERE content='$title' AND userid LIKE '%$regID%'";
EDIT:
Where is needed only once.

select from a select statement in php & mySQL

I am trying to add filters to a DB search. I have a search that takes some text and tries to find items with that text in the title. I also have a price range filter. That code is below and works just fine
$sql = "SELECT * FROM items where title LIKE '%". $title ."%' AND price > '". $price1 ."' AND price < '".$price2."' Limit 70";
Now I am trying to more and more filters. Is there a select from the above code's output? I don't want to just keep making a longer SELECT statement with tons of if statements. I'd prefer to take the output of the previous select and refine that with another select. Is this possible?
EDIT 1 Context:
Users are the ones entering the information. This is for searching the items on my site.
There's no other useful way than adding lots of different conditions to your WHERE cause, if you use plain SQL. It is possible to use several nasted SELECT statements in your query, but this makes your code neither any more readable nor faster.
A more elegant solution is the usage of query objects or another form of object-oriented query abstraction (e.g. ZendDB).
You can use some of the mysql string functions like INSTR(), MATCH which will make your life a little easy and also help the readability of the code.
You can also use REGEXP and NOT REGEXP for pattern matching . The list of string functions are here.

Query Custom WordPress/buddyPress Table (PHP/MySQL)

I have been looking around and trying different things for a while and no luck.
Scenario: I have WordPress/BuddyPress and I added in a few new tables to the database through phpMyAdmin. I cannot run a successful query to them, yet I can to all the original tables. I have tried many things, this is my most recent try, still not working:
$b1_exc = $wpdb->get_results( $wpdb->prepare("SELECT * FROM memberbadge
WHERE 1") );
I would really appreciate a solution to add custom tables and be able to query them.
Thank you in advance!
As of 3.5, wpdb::prepare() enforces a minimum of 2 arguments.
This is the correct syntax for wpdb::prepare(), use this.
$result = $wpdb->get_results( $wpdb->prepare("SELECT * FROM memberbadge WHERE %d", 1) );
It's probably a prefix problem.
Try:
$wpdb->get_results( "SELECT * FROM {$wpdb->prefix}memberbadge") );
If you really need a WHERE clause and the variable comes from user input, then use prepare.

What's wrong with this mySQL IF Statement?

I'm trying to do this IF statement in a mySQL query which I learnt from a YouTube video. I'm not too sure what's going wrong. I do get the following mysql error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'IF(Cuisine != 'Cuisine', WHERE Cuisine='Cuisine') AS ORDER BY
restaurantID' at line 2
Ok, sorry about the lack of detail. Let me explain this a little more.
On my page, I have a HTML form which has 3 drop-downs which act as 'filters'. The default option for one of these 'filters' is Cuisine, which acts as a title, and if it hasn't been changed it means that the user does not want to use the Cuisine as a filter for their search. However if it has changed to say 'Western', then obviously the user wants to use it.
Now, the above problem is quite simple to solve because there is only one filter at a time in place in the above scenario. However, when there are multiple filters being used at once, this is where it gets complicated for me and I don't know how to address this problem.
My solution was to go and search Google for some sort of IF statement in mySQL. I came across this video (which is probably quite good, however since I was very rushed at the time, probably misinterpreted it). Here is the video: http://www.youtube.com/watch?v=3xK5KKQx-J0
I figured that if I could use the condition and try it for the cuisine, I could research and modify it and work on it some more to get it to completely get the filter system to work.
In the code below, my objective is to check what a PHP variable is = to in SQL, and if it's = to 'Cuisine' then I don't want to execute the 'WHERE Cuisine = $cuisine' part of the query. $cuisine is a variable which is taken from a simple HTML/AJAX form dropdown menu using the 'POST' method.
<?php
$result = mysql_query("SELECT * FROM restaurants
IF($cuisine != 'Cuisine', WHERE Cuisine='$cuisine')
ORDER BY restaurantID
")
or die(mysql_error());
?>
P.S I'm not sure if this is the right approach to solving my problem, however I have now described my train of thought and my problem to you above.
I understand your frustration when I left no detail, and once again I apologise, for wasting your time with a poorly written question I will remember to ensure my future questions/answers are more detailed.
I would move the conditional from the SQL query to PHP where the correct query would be built.
if( $cuisine == 'Cuisine' ) ) {
$conditions = '1'; // "WHERE 1" matches every record
}
else {
$conditions = "Cuisine='$cuisine'";
}
$result = mysql_query( "SELECT * FROM restaurants
WHERE $conditions
ORDER BY restaurantID
") or die(mysql_error());
The above assumes that $cuisine is correctly sanitized and escaped.
What are you trying to do? If you want to select all rows where the Cuisine column is not 'Cuisine', use the WHERE clause:
SELECT * FROM restaurants
WHERE Cuisine != 'Cuisine'
ORDER BY restaurantID
Did not fully understand your question, but if you want to select all restaurants by given cuisine and order them by restaurant ID then you can use:
$result = mysql_query("SELECT * FROM restaurants WHERE Cuisine = '$cuisine' ORDER BY restaurantID")
I see multiple problems, which can only be answered if you provide more information. As of now the error in SQL syntax is ,
The syntax of IF condition is
IF(<condition>, <value if true>, <value if false>)
which is troubling you (you have only two parameters for you IF).

Categories