MySQL - Join part of query to a new query? - php

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;
}}}}

Related

Mysql/PHP Json nested array

I got issue with nested array which seems are not Json object for some reason. When i try for e.g access jsonData["user"] it works, but when i try go deeper such as jsonData["user"]["photo_url"] then it's treated like a string and i cant access the value.
Current code:
<?php
require_once("db_connection.php");
$userId = $_GET["user_id"];
$query = "WITH user AS (SELECT id, JSON_OBJECT('display_name', u.display_name, 'photo_url', u.photo_url) AS user FROM users u WHERE id = :userId), info AS (SELECT id, JSON_ARRAYAGG(JSON_OBJECT('text', text, 'start_at', start_at, 'end_at', end_at, 'status', status)) AS information FROM report GROUP BY id), img AS (SELECT report_id, JSON_ARRAYAGG(JSON_OBJECT('name', name)) AS images FROM report_images GROUP BY report_id), cmt AS (SELECT report_id, COUNT(*) AS totalcomments FROM report_comments rc JOIN users u ON rc.user_id = u.id GROUP BY report_id) SELECT u.user, info.information, img.images, cmt.totalcomments FROM report r JOIN user u ON u.id = r.user_id LEFT JOIN info ON info.id = r.id LEFT JOIN img ON img.report_id = r.id LEFT JOIN cmt ON cmt.report_id = r.id";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Old code which worked:
<?php
require_once("db_connection.php");
require_once("functions.php");
$userId = $_GET["user_id"];
$query = "SELECT * FROM report WHERE `user_id` = :userId";
$stmt = $db->prepare($query);
// Bind our variables.
$stmt->bindValue(":userId", $userId);
// Execute.
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
foreach ($result as $key => $value) {
$result[$key]["user"] = getUserById($db, $value["user_id"]);
}
$toJson = json_encode($result);
echo $toJson;
} else {
$toJson = json_encode("Error");
echo $toJson;
}
?>
Because you are aggregating some of the values as JSON in your query, you need to decode those first before attempting to use the values and then JSON encode the whole result set. You need to do that as you fetch the data, so replace:
$result = $stmt->fetchAll();
with:
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row['user'] = json_decode($row['user']);
$row['images'] = json_decode($row['images']);
$row['comments'] = json_decode($row['comments']);
$result[] = $row;
}

I get a NULL value from var_dump when assigning a variable to an array in my select query

I have written a SELECT Query to concatenate a person's name and email address. I then want to echo this string.
Here is the code:
$sqldiv = "Select concat(p1.display_name, " - ", p1.user_email) AS Contact FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
If I use this SELECT QUERY it works:
$sqldiv = "Select p1.display_name FROM wp_players p1
JOIN wp_divisions2 d2 ON p1.id = d2.div_player1_id
JOIN wp_leagues lg ON d2.div_league_ID = lg.league_id
WHERE d2.player_div_id = 2105
ORDER BY d2.div_wins DESC, d2.div_loss ASC, d2.div_rating DESC";
$resdiv = mysqli_query($link, $sqldiv);
$div = array();
while ($rowdiv = mysqli_fetch_array($resdiv)) {
$div[] = $rowdiv[0];
}
echo var_dump($div[0]);
The only difference is that I am using concat. If I run the SELECT Query through SQL I get the output in a single string, which I assume is correct to set $div as an array.
What am I doing wrong?

Three SELECT and two jsons

I created a SELECT to get my communities.
And create two SELECTs to get the communities I'm following.
But I get just my communities.
I do not get the communities I'm following.
$user_id = $_GET["id"];
$row1 = array();
$row2 = array();
// get my communities
$res1 = mysql_query("SELECT * FROM communities where user_id = '$user_id'");
while($r1 = mysql_fetch_assoc($res1)) {
$row1[] = $r1;
}
// get "id" of my communities I'm following
$res = mysql_query("SELECT * FROM communities_follow where user_id = '$user_id'");
while($r = mysql_fetch_assoc($res)) {
$coid = $r["coid"];
// get my communities I'm following
$res2 = mysql_query("SELECT * FROM communities where id = '$coid'");
while($r2 = mysql_fetch_assoc($res2)) {
$row2[] = $r2;
}
}
$resp = array_replace_recursive($row1, $row2);
print json_encode( $resp );
The inner join will get you those communities only, where you are following:
SELECT c.* FROM communities c
INNER JOIN communities_follow cf ON c.id = cf.coid
WHERE cf.user_id = '$user_id';
Or, without a JOIN:
SELECT * FROM communities
WHERE EXISTS (SELECT 1 FROM communities_follow cf
WHERE c.id = cf.coid AND cf.user_id = '$user_id')
Try this sql.
SELECT * FROM communities c LEFT JOIN communities_follow cf ON c.user_id = cf.user_id where
cf.user_id = '$user_id';

adding a where variable inside sql

if user select anything besides "all" it will lead to a where statement involving KodDaerah
$where = '';
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".mysql_real_escape_string($where)."
ORDER BY koddaerah.NamaDaerah ";
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
if user select all then the system will just use the current sql statement that i provided, for now im not sure what's wrong, so here is where user select the KodDaerah from drop down list box
<?php include('dbase.php');
$sql = "SELECT KodDaerah, NamaDaerah FROM koddaerah";
$result = mysql_query($sql);
echo "<select name='KodDaerah' id='KodDaerah' class='input_field' required />
<option>Pilih Daerah</option>
<option value='all'>Seluruh Pahang</option>";
while ($kod = mysql_fetch_array ($result)){
echo "<option value=".$kod['KodDaerah'].">" .$kod['NamaDaerah']."</option>
<option value='all'>Seluruh Pahang</option>";
}
echo "<?select>";
?>
The problem is now even when i select a certain KodDaerah, it will just run the provided sql query without using the WHERE statement in the $where. Can anybody help?
EDIT:
$sql = $sql . $where;
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);
try to move up the if statement:, remove mysql_real_escape_string
(escape before)
$where = '';
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".$where."
ORDER BY koddaerah.NamaDaerah ";
and then do not append $where again
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);

if(query1value = query2value) {} else {}

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."' ");

Categories