SELECT query failing after updating it - php

I modified the following query and am now getting this error.
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
boolean given
I have read into what this error means and I know it is my query that is wrong. This worked perfectly before I changed the query. It was this before...
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
I changed it to...
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3, 4 ,5");
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
What am I doing wrong in the new query?

your query has a mistake.
Try this:
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` in (3, 4 ,5)");
The in serves the same function as an OR

Your query is indeed wrong, you cannot check a value like that.
If you want to check against multiple values, you can make use of the IN keyword.
"SELECT * FROM users WHERE `group` IN (3, 4 ,5)"

If you want to check of either one of the choice use IN instead:
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` IN (3, 4 ,5)");

For comma separated value use IN
SELECT * FROM users WHERE `group` IN(3,4,5);

you may try this following also,may be you will get your result.
SELECT * FROM users WHERE group = 3 or group = 4 or group = 5;
Thanks.

Related

Php loop all result in next mysql query

i have a small problem. I use two mysql queries for getting data.
First i want to get IDs from groups
$sqlGoups = "SELECT * from `groups` WHERE `Date`='$TodayDate' ";
$result = $conn->query($sqlGoups);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$IDgroups = $row["ID"];
With that, I'll get those IDs, for example 5, 7, 12, 15, 22
I want to put them all in the next mysql query:
$sqlNext = "SELECT * FROM `orders` WHERE ID = '$IDgroups' ORDER BY `ID` ASC ";
$result = $conn->query($sqlNext);
When I do this, I get the result only for the first ID (5). And I want for each
I can not INNER JOIN tables because I use this in next query.
I tried with foreach loop, but no effect.
Try this code
SELECT * FROM `orders`
WHERE ID REGEXP CONCAT('(^|,)(', REPLACE('$IDgroups', ',', '|'), ')(,|$)')
ORDER BY `ID` ASC
Just like #Elanochecer commented the best bet should be a JOIN statement, but if you wish to go through your route, you could use the IN and provide the IDs as comma separated string, your query should look similar to the one below:
...
$sqlNext = "SELECT * FROM orders WHERE ID IN ('$IDgroups') ORDER BY ID ASC ";
...
Also, confirm if $IDgroups is in the format 1,2,3,4
If you provide the schema I could come up with a workable JOIN statement for you, preferably you can create a repo with the schema

Check if specific value exists in mysql column

I have mysql column called categories. It can contain single or multiple values like this: 1 or 2 or 1,2,3 or 2,12...
I try to get all rows containing value 2.
$query = "SELECT * FROM my_table WHERE categories LIKE '2'";
$rows = mysql_query($query);
This returns row if column only has value 2 but not 1,2,3 or 2,12. How I can get all rows including value 2?
You can use either of the following:
% is a wildcard so it will match 2 or 1,2, etc. Anything on either side of a 2. The problem is it could match 21, 22, etc.
$query = "SELECT * FROM my_table WHERE categories LIKE '%2%'";
Instead you should consider the find_in_set mysql function which expects a comma separated list for the value.
$query = "SELECT * FROM my_table WHERE find_in_set('2', `categories`)";
Like #jitendrapurohut said, you can do it using
$query = "SELECT * FROM my_table WHERE categories LIKE '%2%'";
$rows = mysql_query($query);
But is really bad to store collections like this. A better aproach is as follow:
categories(id_c, name) => A table with each category
my_table(id_m [, ...])
categories_my_table(id_c, id_m)
Then use this query:
SELECT *
FROM my_table m
INNER JOIN categories_my_table cm ON m.id_m = cm.id_m
INNER JOIN categories c ON cm.id_c = c.id_c
WHERE
c.id_c = 2;
EDIT:
#e4c5 link explains why it is bad to store collections like this...
SELECT * FROM my_table WHERE categories LIKE '%2%' AND categories!='1,2,3' AND categories!='2,12';

issue with SELECT COUNT(id)

I've been using this command to retrieve the number of the fields which have same email address:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
There are 3 records in users table with the same email address. The problem is when I put * instead of COUNT(user_id) it returns correctly: $query->num_rows gives 3 but when I use COUNT(user_id) then $query->num_rows returns 1 all the time. how can I correct this or where is my problem?
When you use $query->num_rows with that query it will return 1 row only, because there is only one count to return.
The actual number of rows will be contained in that query. If you want the result as an object, or associative array give the count a name:
$query = $db->query("SELECT COUNT(`user_id`) AS total FROM `users` WHERE `email`='$email'") or die($db-error);
And in the returned query total should be 3, while $query->num_rows will still be 1. If you just want the value a quick way would be using $total = $query->fetchColumn();.
As others have said though, be careful with NULL user ids, because COUNT() will ignore them.
Emails have to be uinque in users table. Thus, you need no count at all.
You ought to use prepared statements.
You shouldn't post a code that will never run.
Here goes the only correct way to run such a query:
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->execute([$email]);
$user = $stm-fetch();
(the code was written due to erroneous tagging. For mysqli you will need another code, but guidelines remains the same.)
Something like this
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->bind_param('s',$email);
$stm->execute();
$res = $stm->get_result()
$user = $res->fetch_assoc();
in $user variable you will have either userdata you will need in the following code or false which means no user found. Thus $user can be used in if() statement all right without the need of any counts.
In case when you really need to count the rows, then you use this count() approach you tried. You can use a function from this answer for this:
$count = getVar("SELECT COUNT(1) FROM users WHERE salary > ?", $salary);
That's the correct behaviour: If you use the COUNT function, the result of your select query will be just one row with one column containing the number of data sets.
So, you can retrieve the number of users with the given E-mail address like this:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
$row = $query->fetch_row();
$count = $row[0];
Note that this is faster than querying all data using SELECT * and checking $query->num_rows because it does not need to actually fetch the data.

How to look at the result of a query

I have a SQL Query, although it is executing, but how should i verify if it is giving me the desired result.
For example: My query
$query3 = "SELECT COUNT(DISTINCT(uid)) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
In the above query i am trying to count the number of distinct user ID's(uid) from the table named user-infowhere date is 2011-10-10.
How should i display the count which is calculated for the given date?.I need to know it and perform some further operations on it!
$query3 = "SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
$result = mysql_query($query3);
$row = mysql_fetch_array($result);
echo $row['num'];
Just do:
SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'
This SO post goes into some details about how count and count(distinct ...) work. With just count, there is a hidden/assumed function of count(all ... ) actually happening (it's just the default value). If you want to only count distinct things, switch it to the non-default and do the count(distinct ...) instead. I didn't know it existed for my first 6 months of writing sql or so...
You can set a variable sing the result...
SET #userVar=SELECT
COUNT(DISTINCT uid)
FROM
user_info
WHERE
DATE(starttime)='2011-10-10';
Then you can use that variable in your next operation or query.

[PHP][MySQL]How To SELECT data with two constrain?

I'm new to PHP+MySQL programming
I want to SELCET data using tow constrain at once,
the cons1 is
Tid=user02 and Fid=user01
and cons2 is
Tid=user01 and Fid=user02
the data I want to output is something like:
$result1 = mysql_query("SELECT * FROM myTable WHERE Tid='user02' AND Fid='user01');
+
$result2 = mysql_query("SELECT * FROM myTable WHERE Tid='user01' AND Fid='user02');
= what I want
can it be done in single line?
or can make a result which stored $result1 and $result2
thanks for taking time reading my question
You can OR the two conditions resulting in a single query:
SELECT * FROM chat
WHERE (Tid='user02' AND Fid='user01')
OR (Tid='user01' AND Fid='user02')
$result1 = mysql_query("SELECT * FROM chat WHERE Tid='user02' AND Fid='user01' OR Tid='user01' AND Fid='user02'");
Some reading : boolean algebra and the mysql doc
Try this one:
$result1 = mysql_query("SELECT * FROM chat WHERE Tid='user02' AND Fid='user01'
UNION SELECT * FROM chat WHERE Tid='user01' AND Fid='user02'");

Categories