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));
Related
I am trying to do a subquery using PDO:
$stmt = $pdo->prepare("SELECT sum(ros_ranking) FROM (SELECT ros_ranking FROM players WHERE teamid = 1 and positionid = 1 ORDER BY ros_ranking ASC LIMIT 1) AS totalrankings");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$num_rows= $stmt->rowCount();
echo "tqr= ".$row['totalrankings'];
I keep getting Notice: Undefined index: totalrankings in ...
ros_ranking is definitely a field with numbers in it in my Players table and a teamid of 1 and positionid of 1 definitely exist.
Does anyone see what I'm doing wrong here? FYI, if I do just the subquery as the main query, it works. So something must be wrong with SELECT sum(ros_ranking) FROM or AS totalrankings but they seem pretty straightforward.
Wrong alias use/position
you need a column name alias for totalrankings (not a table name alias as you have done)
$stmt = $pdo->prepare("SELECT sum(t.ros_ranking) totalrankings
FROM (SELECT ros_ranking
FROM players
WHERE teamid = 1
AND positionid = 1
ORDER BY ros_ranking ASC LIMIT 1) t");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$num_rows= $stmt->rowCount();
echo "tqr= ".$row['totalrankings'];
total_rankings is an alias for the subquery, it's not an alias for the column. You need to put AS totalrankings after the SUM() expression.
$stmt = $pdo->prepare("
SELECT sum(ros_ranking) AS totalrankings
FROM (
SELECT ros_ranking
FROM players
WHERE teamid = 1 and positionid = 1
ORDER BY ros_ranking ASC
LIMIT 1) AS subquery");
But LIMIT 1 in the subquery means you're not going to get a sum of anything. The subquery just returns 1 row, and the sum of one thing is just that value.
Though you can fix it, by giving the selected column the right alias, there is no need to fetch an array if your query returns only one column. Use fetchColumn() instead:
$stmt = $pdo->prepare("SELECT ...");
$stmt->execute();
$totalrankings = $stmt->fetchColumn();
$num_rows= $stmt->rowCount();
echo "tqr= ".$totalrankings;
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"
My existing SQL Query:
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID = $id
AND SUBJECT_ID IN (2,3,4)";
So in my Database, each REQUEST_ID can be associated with multiple SUBJECT_IDs
And SUBJECT_ID has values ranging from 1 to 10.
So my existing values in the table are:
REQUEST_ID: 1 -> SUBJECT_IDs: 2,3
REQUEST_ID: 2 -> SUBJECT_IDs: 2,4
REQUEST_ID: 3 -> SUBJECT_IDs: 2,8
So currently when the query runs, REQUEST_ID = 3 will still be included in the results because it has the SUBJECT_ID = 2.
Is there a possible way for me to create a SQL Query where even if one value matches, the Query would ignore the REQUEST_ID because it has different values from the array.
Thank you in advance.
UPDATE
Current Results:
$requestSubjects = array();
// So if I call REQUEST_ID = 3
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID = 3
AND SUBJECT_ID IN (2,3,4)";
$getEdu_answer = mysqli_query($connection, $getEdu);
if(!$getEdu_answer || mysqli_num_rows($getEdu_answer)==0) {
echo "Error";
die();
}
else {
while($subjectRow = mysqli_fetch_assoc($getEdu_answer)) {
$subject = $subjectRow["Subject_ID"];
array_push($requestSubjects, $subject);
}
$reqSub = '{"reqSubject":' .json_encode($requestSubjects). '}';
echo $reqSub; // Returning a JSON to ajax
}
Echoed Results:
{"reqSubject":[2]}
The result is correct as the REQUEST_ID=3 is associated with a SUBJECT_ID = 2.
However what I want is that since REQUEST_ID=3 is also associated with SUBJECT_ID = 8, it should not echo a result at all.
If I understand you correctly, you have ALL SUBJECT_IDS of a REQUEST_ID to match (2,3,4) and only then to print the result?
if so, you can construct the query for each SUBJECT_ID
EDIT:
You must get ALL SUBJECT_IDs of REQUEST_ID using another sqlquery
Contact SUBJECT_IDs to your $getEdu query, and only then execute $getEdu query
Example:
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID = $id";
//$sub_list is the all subect_id of $id
foreach ($sub_list as $sub_id){
$getEdu.=" AND $sub_id IN (2,3,4)";
}
$getEdu_answer = mysqli_query($connection, $getEdu);
If you execute it on your example, REQUEST_ID =3,
Than $qetEdu query should be:
SELECT * FROM Request_Subject WHERE REQUEST_ID = 3 AND 2 IN (2,3,4) AND 8 IN (2,3,4)
meaning that REQUEST_ID = 3 won't return because 8 is not in (2,3,4)
Hope it help a bit.
maybe
$getEdu = "SELECT * FROM Request_Subject WHERE REQUEST_ID=3
AND SUBJECT_ID IN (2,3,4, if(REQUEST_ID=3,8,null))";
if I understand you correctly...
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.
I have code like this:
$p = $db->query("SELECT ads_id FROM ads_submissions WHERE status = '0'");
$c_ads = array();
while($row = $db->fetchAll($p))
{
$c_ads[] = $row;
}
Output
4 6 9
I want to add this line to $new_ads = $db-> after WHERE
AND ads_id = !in_array('$output', $c_ads)
To select all ads_id except id 4 and 6 and 9
$new_ads = $db->fetchOne("SELECT ads_id FROM ads_pack WHERE allowed_countries LIKE '%".$country_tr."%'");
But this never work correctly.
Any help please ?
Thank you.
you should do it like this
AND ads_id NOT IN ( implode(',', $c_ads) )
There's no such thing as in array in sql. There's simply result sets. you want
AND ads_id NOT IN (4,6,9)
Could you rewrite this using a subquery, instead of running 2 queries?
"SELECT ads_id FROM ads_pack WHERE allowed_countries LIKE '%".$country_tr."%' AND ads_id NOT IN (SELECT ads_id FROM ads_submissions WHERE status = '0')"