if(query1value = query2value) {} else {} - php

So, I am wondering how I can compare the result of one query to the result of another query in a if-statement. Like this:
$team = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
if($team==$lplayer){
//Do something
}
else{
//Do something else
}
This does not work... Why?
Now, why doesnt this work:
$tleague = mysql_query("SELECT teamId from team
WHERE leagueId=(SELECT leagueId FROM league WHERE leagueName='$leagueName')");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$row1 = mysql_fetch_array($tleague);
$row2 = mysql_fetch_array($tplayer);
if($row1['teamId']==$row2['teamId']){}
else{}

You need to use mysql_fetch_assoc() on the query, and compare the returned values. Something like the below. What you're comparing is the two returned resource objects:
$team = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$t = mysql_fetch_assoc($team);
$p = mysql_fetch_assoc($tplayer);
if($t['teamId'] ==$p['teamId']){
//Do something
}
else{
//Do something else
}
However, you shouldn't be using mysql_* methods, instead look at using MySQLi // Tutorial.

You are not fetching any result from queries. Do something like
$team_result = mysql_fetch_array($team);
$tplayer_result = mysql_fetch_array($tplayer);
Then use fetched result to make your if condition
if($team_result['teamId'] == $tplayer_result['teamId'])
{
//do something
}
Also please stop using mysql as it is deprecated, switch to PDO or mysqli for new projects
Update
The new query have mistake. Why don't you use a join
$tleague = mysql_query("SELECT a.`teamId` from `team` a LEFT JOIN `league` b ON a.`leagueId` = b.`leagueId` WHERE b.`leagueName` = '$leagueName'");
$tplayer = mysql_query("SELECT `teamId` FROM `player` WHERE `playerName`='$playerName'");
$row1 = mysql_fetch_array($tleague);
$row2 = mysql_fetch_array($tplayer);
if($row1['teamId']==$row2['teamId'])
{
// do something
}
else
{
// do something else
}
UPDATED AGAIN
I merged all queries in one and i encapsuled data in the query '".$playerName."' and '".$leagueName."'
$query = mysql_query("SELECT a.`teamId` from `team` a LEFT JOIN `league` b ON a.`leagueId` = b.`leagueId` LEFT JOIN `player` c ON b.`teamId` = c.`teamId` WHERE b.`leagueName` = '".$leagueName."' and c.`playerName`= '".$playerName."'");
if($row = mysql_fetch_array($query))
{
echo 'Found: ' . $row['teamId'];
}
else
{
echo 'Not Found.';
}

It does not work, because it's not the result of the query. You need to pass to a variable the mysql_result i.e.:
$result1 = mysql_result($team, 0);
$result2 = mysql_result($tplayer, 0);
if ($result == $result2) { ...

Try like this
$teamQuery = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$lplayerQuery = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$team = mysql_fetch_assoc($teamQuery);
$lplayer = mysql_fetch_assoc($lplayerQuery);
if($team['teamId']==$lplayer['teamId']){
//Do something
}
else{
//Do something else
}

do it like that
$team = mysql_query("SELECT teamId FROM team WHERE teamName='$teamName'");
$tplayer = mysql_query("SELECT teamId FROM player WHERE playerName='$playerName'");
$row1 = mysql_fetch_array($team);
$row2 = mysql_fetch_array($tplayer);
if($row1['teamId']==$row2['teamId']){
//Do something
}
else{
//Do something else
}
EDIT:
on your second edit your problem is in the query itself .
try this one
$tleague = mysql_query("SELECT t.teamId from team inner join league l On t.leagueId = l.leagueId
WHERE t.leagueName='".$leagueName."' ");

Related

MySQL - Join part of query to a new query?

I've got the following code which queries a table. Then it uses the result to make another query. That result is then used to make a third query.
But how do I grab the userid field from the 2nd query in order to grab a name from a users table and join that to the result of the 3rd query?
Please note once I figure out the code I will convert this to a prepared statement. It's just easier for me to work with legacy code when figuring out queries.
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "SELECT opid, userid from audioposts WHERE audioid = $newaudio" ;
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$opid = $row[opid];
$opuserid = $row[userid];
$getreplies =
"SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
} "SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
}
echo json_encode($dbdata);
The result I need are rows of json encoded instances of $getreplyresults with the $row[userid] from the original result joined to each row.
Here's what I did in the end. Now I just have to figure out how to convert this to a prepared statement in order to avoid malicious injection.
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "
SELECT ap.audioid, ap.title, us.name FROM audioposts ap
INNER JOIN audioposts a2 ON a2.audioid = ap.opid
INNER JOIN users us ON us.id = a2.userid
WHERE ap.opid = $newaudio AND ap.opid <> '0'
";
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$dbdata[]=$row;
}}}}

How to compare value in two tables from the same database

I have been trying to compare value in a table with another value in another table but only the else part is executing.
<?php
$sql = "SELECT * FROM user WHERE user_id=$row[user_id]";
$result = $conn -> query ($sql);
if ($result -> num_rows > 0) {
while ($row = $result ->fetch_assoc()) {
$sql1 = "SELECT * FROM jobpost WHERE jobpost_id=$_GET[id] ";
$result1 = $conn -> query ($sql1);
$row_count = mysqli_num_rows($result);
$row1_count = mysqli_num_rows($result1);
$remaining_rows = min($row_count, $row1_count);
$row = mysqli_fetch_assoc($result);
$row1 = mysqli_fetch_assoc($result1);
if($row["experience"] > $row1["experience"])
{
//some code to display something
echo "1";
}
else
{
echo "2";
}
} }
?>
Welcome to SO, it is hard to read your source code. You can use a simple query like this:
SELECT IF(u.experience > j.experience,1,0) FROM
(
(SELECT experience FROM user WHERE user_id = 1) u
JOIN
(SELECT experience FROM jobpost WHERE jobpost_id = 8) j
)
Try this query here: http://sqlfiddle.com/#!9/1742c0
Please check our datasource. Maybe the else case is correct.

How to get count of the sql search query?

How to get count of the sql search query
$u = new user();
$sql = "SELECT a.id FROM `accounts` AS a LEFT JOIN `users` AS u ON a.id = u.id WHERE a.id IS NOT NULL ";
$gender = $this->input->post('gender');
if($gender != NULL)
{
$sql .= "AND u.gender = '".$gender."' ";
}
$u->query($sql);
How to get count of the query results in $u->query($sql); .I need to set a validation on it. If the query results count is 0 , i need to set a message. Im using PHP Codeigniter ,datamapper library.
Thank you!!!
Just using count() function like this
...
$result = $u->query($sql);
$total_data = count($result);
if($u->exists())
{
echo "Found" // Do something
}
else
{
echo "Nothing found" //Do something
}
$result = $this->db->get();
For Codeigniter use $count = $result->num_rows(); // HERE IS YOUR COUNT
For OOP PHP use $count = $result->num_rows;

MySQL run query inside a query

I have a query that gets 5 lines of data like this example below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
}
I want to run a query inside each results like this below
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
but for some reason it's only display the first line when I add the query inside it. I can seem to make it run all 5 queries.
SELECT
t1.ref,
t1.user,
t1.id,
t2.domain,
t2.title
FROM
table AS t1
LEFT JOIN anothertable AS t2 ON
t2.domain = t1.ref
LIMIT
0, 5
The problem is that inside the while-cycle you use the same variable $result, which then gets overridden. Use another variable name for the $result in the while cycle.
You change the value of your $query in your while loop.
Change the variable name to something different.
Ex:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$qry = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$rslt = mysql_query($qry) or die(mysql_error());
if (mysql_num_rows($rslt) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}
Use the following :
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query_domain = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result_domain = mysql_query($query_domain) or die(mysql_error());
if (mysql_num_rows($result_domain) )
{
$row_domain = mysql_fetch_row($result_domain);
$title = $row_domain['title'];
} else {
$title = "No Title";
}
echo "$ref - $title";
}
This is a logical problem. It happens that way, because you are same variable names outside and inside the loop.
Explanation:
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
// Now $results hold the result of the first query
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
//Using same $query does not affect that much
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
//But here you are overriding the previous result set of first query with a new result set
$result = mysql_query($query) or die(mysql_error());
//^ Due to this, next time the loop continues, the $result on whose basis it would loop will already be modified
//..............
Solution 1:
Avoid using same variable names for inner result set
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$sub_result = mysql_query($query) or die(mysql_error());
// ^ Change this variable so that it does not overrides previous result set
Solution 2:
Avoid the double query situation. Use joins to get the data in one query call. (Note: You should always try to optimize your query so that you will minimize the number of your queries on the server.)
SELECT
ref,user,id
FROM
table t
INNER JOIN
anothertable t2 on t.ref t2.domain
LIMIT 0, 5
Learn about SQL joins:
SELECT table.ref, table.user, table.id, anothertable.title
FROM table LEFT JOIN anothertable ON anothertable.domain = table.ref
LIMIT 5
You're changing the value of $result in your loop. Change your second query to use a different variable.
it is not give proper result because you have used same name twice, use different name like this edit.
$query = "SELECT ref,user,id FROM table LIMIT 0, 5";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ref = $row['ref'];
$query1 = "SELECT domain,title FROM anothertable WHERE domain = '$ref'";
$result1 = mysql_query($query1) or die(mysql_error());
if (mysql_num_rows($result1) )
{
$title = $row['title'];
} else {
$title = "No Title";
}
echo "$ref - $tile";
}

comparing Query results

$query1= mysql_query("select r.nid from ....");
$query2= mysql_query("select t.nid from....");
Both these queries return a nid. How to compare the 2 returned nid are equal.. I'm just a beginner.
$row1 = mysql_fetch_row($query1);
$row2 = mysql_fetch_row($query2);
if($row1[0] == $row2[0])
{
//something
}
You could do it in pure sql. Like this:
select
r.nid
from
....
WHERE EXISTS
(
select
NULL
from
....
WHERE
t.nid = r.nid
)
If you are certainly sure that the query really returns one id, you can speed up checking it by:
$query1 = mysql_query("select r.nid from ....");
$query2 = mysql_query("select t.nid from ....");
if(mysql_fetch_field($query1, 0) === mysql_fetch_field($query2, 0))
{
//do something
}

Categories