I have this query:
$query = "SELECT pic_square,
name,
highest_score,
num_tries,
avg_total
FROM users
WHERE NOT played_game = '0'
ORDER BY avg_total DESC";
Where I select pic_square,name,highest_score,num_tries and avg_total FROM for all users that
DO NOT have their played game set as ''0''.
I would like to add another condition so I select only the users that:
DO NOT have their played_game set as ''0''
DO NOT have their name empty
PS: The name cannot be null, it just can be empty, I cannot change the DB structure itself.
So how do I add these dual WHERE NOT together?
WHERE NOT (played_game = '0' or name = '')
or
WHERE played_game <> '0' and name <> ''
$query = "SELECT pic_square,name,highest_score,num_tries,avg_total FROM users
WHERE NOT (played_game = '0' OR name IS NULL OR name='' )
ORDER BY avg_total DESC";
$query = "SELECT pic_square,name,highest_score,num_tries,avg_total FROM users
WHERE played_game <> '0' AND name <> '' ORDER BY avg_total DESC";
simply change condition like
where played_game <> '0' AND name <> ''
$query = "SELECT pic_square,name,highest_score,num_tries,avg_total
FROM users
WHERE played_game != '0'
AND name NOT NULL
ORDER BY avg_total DESC";
You can use this query:
$query = "SELECT pic_square,
name,
highest_score,
num_tries,
avg_total
FROM users
WHERE NOT played_game = '0'
AND IFNULL(name,'') <> ''
ORDER BY avg_total DESC";
Using IFNULL you'll get sure that NULL values and empty values are treated just the same.
Related
I'm trying to get a criteria from 2 Columns and indexing them using this query
$query1 = "SET #row_num = 0";
$query2 = "SELECT *, #row_num := #row_num + 1 as row_index FROM gift
WHERE Category = '0' AND ID ='".$ID."'
ORDER BY ID ASC;";
mysqli_query($conn, $query1);
$retrieve = mysqli_query($conn, $query2);
Is there is a way in which I can use the row_index as a variable in the query, like this:
$query1 = "SET #row_num = 0";
$query2 = "SELECT *, #row_num := #row_num + 1 as row_index FROM gift
WHERE Category = '0' AND row_index ='".$ID."'
ORDER BY ID ASC;";
mysqli_query($conn, $query1);
$retrieve = mysqli_query($conn, $query2);
You can test for the $ID in a HAVING clause:
$query1 = "SET #row_num = 0";
$query2 = "SELECT *, #row_num := #row_num + 1 as row_index FROM gift
WHERE Category = '0'
HAVING row_index = $ID
ORDER BY ID ASC;";
mysqli_query($conn, $query1);
$retrieve = mysqli_query($conn, $query2);
There is no need to concatenate the variable in the query. If $ID is an integer there is no need for quotes and if it is alpha-numeric just enclose it in single-quotes as PHP will interpolate the variable correctly.
Reference for HAVING clause
Without actually having tested it, I would expect something like the following to work....
SELECT ilv.*
FROM (
SELECT gift.*, #row_num := #row_num + 1 as row_index
FROM gift
WHERE Category = '0'
ORDER BY ID ASC
) ilv
WHERE row_index ='".$ID."';
(but you shouldn't be quoting an integer value).
Or....
SELECT *
FROM gift
WHERE Category = '0'
ORDER BY ID ASC
LIMIT $ID, 1;
Or, with a recent MySQL, using the MyISAM engine, you can define a primary key based on a natural key and autoincrement value. In your case, the "natural" key would be category. Then if you ensure that you are allocating the id stored in the database at a monotonic interval and simply.....
SELECT *
FROM gift
WHERE category='0'
AND id=($ID * $interval);
I'm trying to make a filter function for servers on my site. Users are able to check different options for the categories they want to filter for, and I have an ajax request that returns the servers satisfying their conditions. However, my mysql_query isn't working, I think I might have the wrong syntax.
By default, each category has the option set as 1. My current query is:
$order = "SELECT * FROM `servers`
WHERE `size` = '$size' or
1 = '$size' and
`type` = '$type' or
1 = '$type' and
`mode` = '$gamemode' or
1 = '$gamemode' and
`main` = '$main' or
1 = '$main'
ORDER BY $orderby
LIMIT 5";
It doesn't seem to get the correct servers, do I have an error in my query?
Thanks!
When mixing and and or in your query you must use parenthesis to group the conditions. Also, I think when you say 1 = '$size', I think you mean `size`=1.
$order = "SELECT * FROM `servers`
WHERE
(`size` = '$size' or `size` = '1') and
(`type` = '$type' or `type` = 1) and
(`mode` = '$gamemode' or `mode`= 1 ) and
(`main` = '$main' or `main` = 1)
ORDER BY $orderby
LIMIT 5";
"SELECT * FROM `servers` WHERE
`size` in ('$size', 1) and
`type` in( '$type' ,1) and
`mode` in('$gamemode' ,1) and
`main` in ( '$main' , 1 )
ORDER BY $orderby LIMIT 5";
You need to add parentheses because or and and have a different order of operations and needs parentheses to allow what you are needing to accomplish
SELECT * FROM `servers` WHERE
(`size` = '$size' or 1 = '$size') and
(`type` = '$type' or 1 = '$type') and
(`mode` = '$gamemode' or 1 = '$gamemode') and
(`main` = '$main' or 1 = '$main')
ORDER BY $orderby LIMIT 5
you must have to use brackets to use multiple OR condition in query
like
mysql_query("SELECT * FROM servers WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo')");
you can change with your column name
and also you can use IN condtion like
mysql_query("SELECT * FROM servers WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo')");
pls let me know if i can help you more
Just try to put brace around the or conditions
$order = "SELECT * FROM `servers` WHERE (`size` = '$size' or 1 = '$size') and (`type` = '$type' or 1 = '$type') and (`mode` = '$gamemode' or 1 = '$gamemode') and (`main` = '$main' or 1 = '$main') ORDER BY '$orderby' LIMIT 5";
I have an SQL statement:
$sql = "SELECT * FROM user_events WHERE userID =" . $uid . " OR groupID = (IN ($gId) WHERE userID IS NULL) ORDER BY timestamp DESC";
This looks like this when printed:
SELECT * FROM user_events WHERE userID = 34 OR groupID =(IN (44,45) WHERE uID IS NULL) ORDER BY timestamp DESC
What I'm trying to do is select from the database any row where either the userId matches a specific variable or where the groupID matches a CSV variable where the userID is NULL.
Can anyone explain what I'm doing wrong here? I'm quite stuck!
IN is an operator, not a... that. You also want AND, not WHERE.
$sql = "SELECT * FROM user_events
WHERE userID = $uid
OR groupID IN ($gId) AND userID IS NULL
ORDER BY timestamp DESC";
$sql = "SELECT * FROM user_events
WHERE userID =" . $uid . "
OR (groupID IN ($gId) AND userID IS NULL) ORDER BY timestamp DESC";
I think that you want something like:
SELECT * FROM user_events
WHERE (userID = 34 OR groupID IN (44,45)) and uID IS NULL
ORDER BY timestamp DESC
In PHP, this might look like:
$sql = "SELECT * FROM user_events WHERE (userID =". $uid . " OR groupID IN ($gId)) AND userID IS NULL ORDER BY timestamp DESC";
I have now three different PHP pages that contain almost the same information so to be able to reduce this to one page I need to have a php variable inside the mysql query.
Today it is like this:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";`
I need that the " AND Bruk = '1'" is removed from this query-line if i put ?nobruk=no in the adressbar. Is this possible and if so, how?
You don't want to (and can't) put an if inside your query; you want to use an if to create your query based on some condition. There are lots of ways to write this, one of which is
if (!empty($_GET['nobruk'])) {
$query1 = "SELECT ... WHERE `Kategori` = '1' ORDER BY ...";
}
else {
$query1 = "SELECT ... WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY ...";
}
Another way, which is shorter and involves the ternary operator, is
$includeBruk = empty($_GET['nobruk']);
$query1 = "SELECT ... WHERE `Kategori` = '1' ".
($includeBruk ? "AND `Bruk` = '1' " : "").
"ORDER BY ...";
A simple if statement:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1'";
if ($_GET['nobruk']!='no') {
$query1.=" AND `Bruk` = '1'";
}
$query1.= " ORDER BY yearstart DESC, mndstart DESC";
Like this :
<?php
$query = ($_REQUEST['nobruk'] == "no") ? "SELECT * FROM `Yrker` WHERE `Kategori` = '1' ORDER BY yearstart DESC, mndstart DESC": "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";
echo $query;
?>
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori`='1' ".($_GET['nobruk'] === 'no' ? "" : "AND `Bruk`='1' ")."ORDER BY yearstart DESC, mndstart DESC";
$activeQuery = mysql_query("SELECT count(`status`) AS `active` FROM `assignments` WHERE `user` = $user_id AND `status` = 0");
$active = mysql_fetch_assoc($activeQuery);
$failedQuery = mysql_query("SELECT count(`status`) AS `failed` FROM `assignments` WHERE `user` = $user_id AND `status` = 1");
$failed = mysql_fetch_assoc($failedQuery);
$completedQuery = mysql_query("SELECT count(`status`) AS `completed` FROM `assignments` WHERE `user` = $user_id AND `status` = 2");
$completed = mysql_fetch_assoc($completedQuery);
There has to be a better way to do that, right? I don't know how much I need to elaborate as you can see what I'm trying to do, but is there any way to do all of that in one query? I need to be able to output the active, failed, and completed assignments, preferably in one query.
You can try something like this query
SELECT Status , COUNT(*) StatusCount
FROM assignments
WHERE Status IN (0, 1, 2)
AND User = $user_id
GROUP BY Status
Try this
$activeQuery = SELECT status, count(status) as "status count" FROM `assignments` WHERE `user` = $user_id GROUP BY `status`
edit: added group by
Instead of doing them individually you could use the following single SQL statement
SELECT count(*), `status`
FROM `assignments`
WHERE `user` = $user_id
AND `status` in (0,1,2)
GROUP BY `status`
ORDER BY `status`
The loop around the result set to extract the results.
SELECT
(SELECT COUNT(*) FROM `assignments` WHERE `user` = $user_id AND `status` = 0) AS active,
(SELECT COUNT(*) FROM `assignments` WHERE `user` = $user_id AND `status` = 1) AS failed,
(SELECT COUNT(*) FROM `assignments` WHERE `user` = $user_id AND `status` = 2) AS completed,
FROM `assignments`
GROUP BY active, failed, completed
Haven't checked the markup, but this is near or near enough.
Use the GROUP BY to get it in one query, but on separate rows.
$query = mysql_query("SELECT `status`, count(*) AS `num` FROM `assignments` WHERE `user` = $user_id AND `status` in (0,1,2) GROUP BY `status` ORDER BY `status` ASC");
$active_count = 0;
$failed_count = 0;
$completed_count = 0;
while ($array = mysql_fetch_assoc($query))
{
if ($array['status'] == 0)
$active_count = $array['num'];
else if ($array['status'] == 1)
$failed_count = $array['num'];
else if ($array['status'] == 2)
$completed_count = $array['num'];
}
When I have the option, I'm in the habit of using prepared statement(s) to help protect against sql-injection protection and for efficiency (requires using mysqli).
But if this is not an option, then
SELECT
CASE `status`
WHEN 0 THEN `active`
WHEN 1 THEN `failed`
WHEN 2 THEN `completed`
ELSE `unknown`
END
AS `statuslabel`,
COUNT(status)
AS `statuscount`
FROM `assignments`
WHERE `user` = $escaped_user_id
GROUP BY `statuslabel`
ORDER BY `statuslabel`
Note the use of the $escaped_user_id, which would be created beforehand:
$escaped_user_id = mysql_real_escape_string($user_id);