Into a single query - php

I have got a table
unam fnam
john alex
alex john
I want a query that returns true if unam 'john' == fnam 'alex' or unam 'alex' == fname 'john'
I dont know how to do it in a single query .
My code
$re = mysql_query("SELECT 1 FROM tab WHERE unam='john' and fnam='alex' LIMIT 1");
$ir = mysql_query("SELECT 1 FROM tab WHERE unam='alex' and fnam='john' LIMIT 1");
if ((!(mysql_num_rows($re))) && (!(mysql_num_rows($ir)))) echo 'not exists';
I have executed 2 seperate queries (one for unam 'john' == fnam 'alex' and other for unam 'alex' == fname 'john', if both the queries do not have any rows it echos not exists.
I was thinking may be it can be optimized to a single query.

You can do an OR conditional to check for multiple different conditions.
SELECT 1
FROM tab
WHERE (unam='john' and fnam='alex')
OR (fnam='john' and unam='alex')
LIMIT 1

You can put your logic in the where clause like this:
select 1
from tab
where (uname = 'john' and fname = 'alex') or
(fname = 'alex' and uname = 'john')
limit 1
By the way, if you want to always return a value, say 0 or 1, you can use aggregation:
select coalesce(max(1), 0) as retval
from tab
where (uname = 'john' and fname = 'alex') or
(fname = 'alex' and uname = 'john')
If no rows are selected, then the max() returns NULL which the coalesce() turns into 0.

You can use OR statement to achieve this.
Try this:
mysql_query("SELECT 1
FROM tab
WHERE
(unam='john' and fnam='alex')
OR
(unam='alex' and fnam='john')
limit 1");

$re = mysql_query("SELECT COUNT(*) FROM tab WHERE (unam='john' and fnam='alex') OR (unam='alex' and fnam='john')");

Just a different approach, using EXISTS, and a different syntax:
SELECT
EXISTS (SELECT NULL FROM names
WHERE (unam, fnam) IN (('john', 'alex'),('alex','john')))
Please see fiddle here.

Related

Assigning the same parameter value multiple times in pdo execute

I originally had an SQL statement, this:
SELECT *, COUNT(friend_one) AS pending_count , COUNT(friend_two) AS requests_sent
FROM friends
WHERE friend_one OR friend_two = ?
AND status = ?
In which I assigned my parameters like :
$pending_friend_count_stmt->execute(array($user_id, $status_one));
However, the query was not getting the results I wanted. Someone showed me a different way of doing it, but it has the variable $user_id in it multiple times, so I do not know how to adjust the code to be able to use a parameter.
You can see the new query here:
http://rextester.com/KSM73595
Am I able to just do
SELECT COUNT(CASE WHEN `friend_one` = ? THEN 1 END) as `requests_count`,
COUNT(CASE WHEN `friend_two` = ? THEN 1 END) as `pending_count`
FROM `friends`
WHERE ? IN ( `friend_one` , `friend_two` )
AND `status` = ?
$pending_friend_count_stmt->execute(array($user_id, $user_id, $user_id $status_one));
Using PDO you have the ability to use named parameters, however in your question you want to use 1 parameters for multiple values and that means emulation has to be on:
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
Now you can do the following:
$stmt = $db->prepare("SELECT * FROM table WHERE userid = :userid AND userid = :userid");
$stmt->excecute([
':userid' => 1
]);
Resulting in:
"SELECT * FROM table WHERE userid = 1 AND userid = 1"

Select from 2 tables not working with php mysql

I have two different tables of the following structure:
grouprel
id | userId | pupID | groupId
pupils
id | userId | fname | lname
pupId in groulrel is equal to id in pupils.
I want to fetch pupils from a different group and then order them by fname, lname.
Now I have two queries like this:
$q = "SELECT * FROM grouprel WHERE userid = ". $userid ." AND groupId = ". $_GET['id'] ."";
$r = mysqli_query($mysqli, $q);
while ($rows = mysqli_fetch_object($r)) {
$query = "SELECT id, fname, lname FROM pupils WHERE userid = ". $userid ." AND id = ". $rows->pupId ." AND status = 0 ORDER BY fname, lname";
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_object($result)) {
echo stuff...
}
}
This works, but it doesn't order the names alphabetically like I want to.
How could I fix this?
This is iterating over the first query:
while ($rows = mysqli_fetch_object($r)) {
And this iterates over each instance of the second query:
while($row = mysqli_fetch_object($result)) {
So if the first query returns 1,2,3, and each iteration of the second query returns A,B, then your output would be:
1 A
1 B
2 A
2 B
3 A
3 B
The second query is ordering by the ORDER BY clause you gave it. But you are ordering the entire output by the first query.
Ultimately, why do you need these separate queries at all? Executing a database query in a loop is almost always the wrong idea. It looks like all you need is one query with a simple JOIN. Guessing on your logic, something like this:
SELECT
pupils.id, pupils.fname, pupils.lname
FROM
pupils
INNER JOIN grouprel ON pupils.id = grouprel.pupId
WHERE
pupils.userid = ?
AND grouprel.groupId = ?
AND pupils.status = 0
ORDER BY
fname, lname
It may take a little tweaking to match exactly what you're looking for, but you can achieve your goal with a single query instead of multiple separate queries. Then the results of that query will be ordered the way you told MySQL to order them, instead of the way you told PHP to order them.

MySQL EXISTS return 1 or 0

How can I return the 1 or 0 as true and false for my select query? I've tried every combination of fetch_assoc, arrays, etc. It usually returns as null, which doesn't make sense.
$querydetails = "select exists (select * from customer_det where id = $uid)";
$resultdetails = mysql_query($querydetails) or die(mysql_error());
while ($row = mysql_fetch_assoc($resultdetails)) {
$resultdetails1 = $row[0];
}
That's the latest version of my query. I guess it's not an array, but I'm not sure how to pull the value if there's no row to be named?
This is a post question to my previous thread: MySQL Update WHERE
SELECT IF(EXISTS(...),1,0) AS result
simple use COUNT and IF
SELECT IF(COUNT(*) = 0, 0, 1)
FROM table1
WHERE s = 2
SQLFiddle Demo
SELECT count(*) FROM (
SELECT id FROM table WHERE condition LIMIT 1
) AS result;
i am using mysql version 8.0.23 on AMS
SELECT
column1,
column2,
IF (exists(select * from MeasurementItemNos measureItem where measureItem.itemNo = ib.itemNo and measureItem.IsActive = 1),1,0) as isUploadedSizeSpec
from table
I would do:
select * from customer_det where id = $uid LIMIT 1
You will get either 1 row or zero rows.

Using 'AND' and 'OR' in same mysql statement with PDO

Is it possible to do this?
Lets say I have a table : data
$id_1 = "checking";
$id_2 = "box";
$id_users = 1;
id id_1 id_2 id_users
1 checking box 1
2 checking circle 1
3 box checking 1
4 box checking 1
$sql = $db->prepare("SELECT COUNT(*) FROM data WHERE ((id_1 = ? AND id_2= ?) OR (id_1 = ? AND id_2 = ?)) AND id_users = ?");
$sql -> execute(array($id_1, $id_2, $id_2, $id_1, $id_users));
echo count($sql);
With this, I'm getting an output of 1 only. Technically I should be getting an output of 3, correct? Because there are 3 possibilities with checking and box.
The SQL is supposed to check either table for the two combinations of checking and box.
Can someone tell me what I'm doing wrong here?
Thanks
It looks like you're count()ing the already-counted SQL COUNTed number of rows.
How about just echo $sql?
$sql = $db->prepare("SELECT COUNT(*) FROM data WHERE ((id_1 = ? AND id_2= ?) OR (id_1 = ? AND id_2)) AND id_users = ?");
$sql->execute(array($id_1, $id_2, $id_2, $id_1, $id_users));
echo $sql->fetch();
What MДΓΓ БДLL said is ok, but you could also use named parameters:
$sql = $db->prepare("SELECT COUNT(*) FROM data WHERE ((id_1 = :id1 AND id_2= :id2) OR (id_1 = :id2 AND id_2 = :id1)) AND id_users = :idusers");
$sql -> execute(array(':id1' => $id_1, ':id2' => $id_2, ':idusers' => $id_users));
And you need to fetch result
$result = $sql->fetch();
echo $result[0];
In your query it seems that you are passing id_1 as parameter to id_2 and id_2 parameter as id_1 so as per your query there is only one combination of id_1 = checking and id_2 = box ,
so you are getting output count as 1
instead of this to avoid parameter confusion use
$sql -> execute(array(':id1' => $id_1, ':id2' => $id_2, ':idusers' => $id_users));

problem in counting two fields in one query

guys i need to count new private messages and old one from a table
so first thing come to mind is using mysql_num_rows and easy thing to do
// check new pms
$user_id = $userinfo['user_id'];
$sql = "SELECT author_id FROM bb3privmsgs_to WHERE user_id='$user_id' AND (pm_new='1' OR pm_unread='1')";
$result = $db->sql_query($sql) ;
$new_pms = $db->sql_numrows($result);
$db->sql_freeresult($result);
// check old pms
$sql = "SELECT author_id FROM bb3privmsgs_to WHERE user_id='$user_id' AND (pm_new='0' OR pm_unread='0')";
$result = $db->sql_query($sql) ;
$old_pms = $db->sql_numrows($result);
$db->sql_freeresult($result);
but how can i count these two fields just in one statement and shorter lines ?~
Use this query instead:
SELECT SUM(CASE WHEN pm_new = '1' OR pm_unread = '1' THEN 1 ELSE 0 END) AS new_pms,
SUM(CASE WHEN pm_new = '0' OR pm_unread = '0' THEN 1 ELSE 0 END) AS old_pms
FROM bb3privmsgs_to
WHERE user_id='$user_id'
Here's a MySQL-specific version that reads more cleanly:
SELECT COUNT(IF(pm_new = '1' OR pm_unread = '1', 1, NULL)) AS new_pms,
COUNT(IF(pm_new = '0' OR pm_unread = '0', 1, NULL)) AS old_pms
FROM bb3privmsgs_to
WHERE user_id='$user_id'
MySQL will cast comparisons to 1 or 0. You can use SUM() to add up the portion of the WHERE clause you were trying to count results for.
This is a (MySQL specific) shorter alternative to the CASE WHEN examples.
SELECT
SUM(pm_new='1' OR pm_unread='1') as new_pms,
SUM(pm_new='0' OR pm_unread='0') as old_pms
FROM bb3privmsgs_to
WHERE user_id='$userid'
In SQL Server, you can do something like this:
SELECT
SUM(CASE WHEN pm_new='1' OR pm_unread='1' THEN 1 ELSE 0 END),
SUM(CASE WHEN pm_new='0' OR pm_unread='0' THEN 1 ELSE 0 END)
FROM
bb3privmsgs_to WHERE user_id='$user_id'
I'll suppose you can do about the same thing in mySql, let me get back to you on the details...
As a lazy alternative to some of the other suggestions:
SELECT SUM(newPMS) AS newPMS,
SUM(oldPMS) AS oldPMS
FROM ( SELECT COUNT(author_id) AS newPMS,
0 AS oldPMS
FROM bb3privmsgs_to
WHERE user_id='$user_id'
AND (pm_new='1' OR pm_unread='1')
UNION
SELECT 0 AS newPMS
COUNT(author_id) AS oldPMS
FROM bb3privmsgs_to
WHERE user_id='$user_id'
AND (pm_new='0' OR pm_unread='0')
)

Categories