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).
Related
What is the simplest way of putting another mysql query inside a where clause in php.
For example I have tried:
$sql = "SELECT app, description FROM all-apps WHERE app!='(SELECT user, app FROM users-apps WHERE user="$user_name")'";
I need to bring up all the apps entries in the database. and then check if the user has the same app name in his list. if so it will not show up.
Basically there are 2 databases one has all apps and the other one has apps which the users have used and I need the query to find all the apps the user has not used.
Please comment bellow if this question is up to standard. Please have an opinion so I can fix on my mistakes in the future.
A few changes needed
"SELECT app, description FROM all-apps WHERE app NOT IN (SELECT app FROM users-apps WHERE user='{$user_name}')";
Note that this and your original query may leave you vulnerable to sql injection. Please use PDO prepared statements.
Thanks, with all of your help I was able to get this query to work:
$sql = "SELECT * FROM all_apps WHERE app NOT IN (SELECT app FROM users_apps WHERE user='{$user_name}') ";
This works by first selecting one table. Then choosing what column you want the WHERE to be. Then put IN if you want it to be in or NOT IN. Then in brackets your second query. Make sure to have it only select the one column. The IN clause also works if there are multiple results.
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";
I am trying to write a script/html page that displays live company information internally. I want to have a widget that counts the amount of live projects from our database.
The widget will need to look on the table called 'projects' then look in the column called 'live' and count how many times 'LIVE' is displayed, but the last problem I have is that we operate two companies so it will need to first check that column 'company' has 'E' there and then count the 'live' column.
I cannot think how to approach this as my php skills are less than novice... more like n00b!
Try a simple select count() mysql query similar to:
SELECT count(*) AS count FROM `projects` WHERE `live` = 'LIVE' AND `company` = 'E'
To return the value back inside the php file and output it as html you need to fetch the results of the query as in:
$result = mysql_query("SELECT count(*) AS count FROM projects` WHERE live = 'LIVE' AND company = 'E'");
$row = mysql_fetch_array($result);
echo $row['count'];
CAUTION
You should not be using any of the mysql_*, they are deprecated and are making your application really vulnerable to attacks. Feel free to use them as learning tools (many tutorials) but once you feel comfortable connecting to databases and fetching results, make sure to move to mysqli or pdo accordingly. Good reads:
PHP Mysql Query
How can I prevent SQL injection in PHP?
G'day,
I'm not familiar with MySQL and this will probably be an easy question!
I am trying to mod a Joomla plugin and am working with this code that works well for a similar function:
$q="SELECT `".$naming."` AS naming FROM `#__users` WHERE `id`='".$jomsocial_event->creator."' ";
$db->setQuery($q);
$eventcreatorname = $db->loadResult();
$eventcreator = ''.addslashes($eventcreatorname).'';
What I need to do is lookup the field id in the table community_groups and return the matching field name. What I have is (note that $jomsocial_event->contentid contains the group ID):
$q="SELECT `".$naming."` AS naming FROM `#__community_groups` WHERE `id`='".$jomsocial_event->contentid."' ";
$db->setQuery($q);
$eventgroupname = $db->loadResult();
$eventgroup = ''.addslashes($eventcreatorname).'';
It returns nothing as the query is wrong; what should it be for my usage?
I'd work backwards from the database.
i.e. turn on SQL logging and look at what's actually arriving in the database. Tweak as necessary by playing with the resulting SQL until you get what you want (and expect) and then implement that in your code.
Take a look at your generated query in the debugging from Joomla.
Run it against mysql directly and see where it goes wrong.
Also, I'd use the JDatabaseQuery API because you are much less likely to get errors with quoting etc. It looks to me like you are treating id as a string not an integer.
Ok, let say we have two rows:
member_id, name
Let say member_id = 15 and name = 'John';
I want to UPDATE this data and do the following query:
mysql_query("UPDATE members SET member_id = 14, name = 'Peter' WHERE member_id = 15
This is just an example, but is it possible that mysql would fail and UPDATE for example only name row. So, after completing mysql_query above, it would become member_id = 15 and name = 'Peter';
It is just an example. Today, a similar situation happened in my website and I checked my code hundred times and I see no errors and there hadn't been no same errors before it at all.
So, should I recheck my code one hundred times more, or it can happen?
Thank you very much.
According to the spec, single UPDATE statements are atomic; ie: either it updates all columns or it doesn't update any of them.
So no, it shouldn't happen. But of course there could be a bug with MySQL.
Put or die(mysql_error()); after your query so that if this really is happening then you would at least know about it.
I think it should not happen that it would become member_id = 15 and name = 'Peter'. The SQL syntax is right as far as i can see and it seems all good. If something wrong happens to your database and your query is executed in that moment God only knows what could happen. Despite this, most of the time either the query is executed entirely or it is not, making mysql_query() return false.
You should, as already suggested at least check if there where any error with a code such as the following if you are in an online business website:
mysql_query($sql) or die('An error occurred');
or something like as follows if you are in debug mode:
mysql_query($sql) or die(mysql_error());
I'm not as sure as everyone else that single-row updates are atomic. MySQL differs from standard SQL in that it does the column assignments of a single-table UPDATE left-to-right. That means member_id = 14 is done before name = 'Peter'. If name = 'Peter' violates a constraint, or triggers another update that fails, then that assignment will fail. However, whether the statement as a whole fails or not may depend on various factors, including whether the table is using a transaction-safe engine.