SQL JOIN does not return any results - php

if(isset($_GET['id']) && $_GET['id'] != null) {
$id = $_GET['id'];
$sql = "SELECT
`maps.name`,
`maps.description`,
`maps.date`,
`maps.mcversion`,
`maps.mapid`,
`maps.category`,
`maps.format`,
`users.username`,
`users.rank`,
`users.verified`,
`users.mcusername`,
COUNT(`views.mapid`) AS `views`,
COUNT(`likes.mapid`) AS `likes`,
COUNT(`downloads.mapid`) AS `downloads`,
COUNT(`subscribes.channelid`) AS `subscribers`
FROM `maps` INNER JOIN `users` ON `maps.userid` = `users.id`
INNER JOIN `views` ON `maps.mapid` = `views.mapid`
INNER JOIN `likes` ON `maps.mapid` = `likes.mapid`
INNER JOIN `downloads` ON `maps.mapid` = `downloads.mapid`
INNER JOIN `subscribe` ON `mapid.userid` = `subscribe.channelid`
WHERE `maps.mapid` = '$id'";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
echo “success”;
} else {
header("LOCATION: index.php");
}
$sql = "SELECT * FROM `maps` WHERE `id`=$id";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
viewer($id);
} else {
header("LOCATION: index.php");
}
This worked, but I need data from more tables.
$sql = "SELECT
`maps.name`,
`maps.description`,
`maps.date`,
`maps.mcversion`,
`maps.mapid`,
`maps.category`,
`maps.format`,
`users.username`,
`users.rank`,
`users.verified`,
`users.mcusername`,
COUNT(`views.mapid`) AS `views`,
COUNT(`likes.mapid`) AS `likes`,
COUNT(`downloads.mapid`) AS `downloads`,
COUNT(`subscribes.channelid`) AS `subscribers`
FROM `maps`
INNER JOIN `users` ON `maps.userid` = `users.id`
INNER JOIN `views` ON `maps.mapid` = `views.mapid`
INNER JOIN `likes` ON `maps.mapid` = `likes.mapid`
INNER JOIN `downloads` ON `maps.mapid` = `downloads.mapid`
INNER JOIN `subscribe` ON `mapid.userid` = `subscribe.channelid`
WHERE `maps.mapid` = '$id'";
Is this sql join good? Why it does not return any results?
with the normal $sql = "SELECT * FROM maps WHERE id=$id"; everything works, but i need data from the other tables too.

The solution:
$sql = "SELECT
maps.name,
maps.description,
maps.date,
maps.mcversion,
maps.mapid,
maps.category,
maps.format,
users.username,
users.rank,
users.verified,
users.mc_username,
(SELECT COUNT(*) FROM likes WHERE likes.mapid = maps.id) AS likes,
(SELECT COUNT(*) FROM downloads WHERE downloads.mapid = maps.id) AS downloads,
(SELECT COUNT(*) FROM subscribe WHERE subscribe.channelid = maps.userid) AS subscribers,
(SELECT COUNT(*) FROM views WHERE views.mapid = maps.id) AS viewers
FROM maps
INNER JOIN users
ON maps.userid = users.id
WHERE maps.id = '$id'";
Thanks for the help!

IF you would like to secure a complex sql statment, how would you do it?
Is it an ok version?:
if(isset($_GET['id']) && $_GET['id'] != null) {
$id = $_GET['id'];
$stmt = $mysqli->prepare('SELECT id FROM maps WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
if (mysqli_num_rows($result) == 1) {
$row = $result->fetch_assoc();
$secid = $row["id"];
} else {
echo "error2";
}
$sql = "SELECT
maps.name,
maps.description,
maps.date,
maps.mcversion,
maps.mapid,
maps.category,
maps.format,
users.username,
users.rank,
users.verified,
users.mc_username,
(SELECT COUNT(*) FROM likes WHERE likes.mapid = maps.id) AS likes,
(SELECT COUNT(*) FROM downloads WHERE downloads.mapid = maps.id) AS downloads,
(SELECT COUNT(*) FROM subscribe WHERE subscribe.channelid = maps.userid) AS subscribers,
(SELECT COUNT(*) FROM views WHERE views.mapid = maps.id) AS viewers
FROM maps
INNER JOIN users
ON maps.userid = users.id
WHERE maps.id = '$secid'";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
echo $row["name"];
} else {
echo "error3";
}
} else {
echo "error1";
}
database connection:
$mysqli = new mysqli('127.0.0.1', 'root', 'pass’, 'db’);

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

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

Using php if...else statement with two queries

I have two queries that count the number of data for both "artists" and "groups" in my database. I want to display a message if there is data to display for either artists or groups (or both), and if the data returns 0 for both of them then not to display anything.
I have the following code which doesn't seem to work:
<?php if (($numrowsartists==0)OR($numrowsgroups==0)) {
} else {
echo "There is information to display.";
}
?>
Below are the queries I have:
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$numrowsartists = mysql_fetch_assoc($res);
$query = "SELECT COUNT(*) FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$numrowsgroups = mysql_fetch_assoc($res);
Thanks in advance. I'm sure it's probably a super basic fix but I'm still very new to php and would appreciate some help.
You should getthe value frorm the row eg using alias for column name
$query = "SELECT COUNT(*) as num_artists FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsartists = row['num_artists'];
$query = "SELECT COUNT(*) as num_groups FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = $id
ORDER BY ag.group_name ASC";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$numrowsgroups = row['num_groups'];
There are several solutions, the easiest being the following:
if($numrowsartists[0]+$numrowsgroups[0] > 0)
However, as people have said, you shouldn't use mysql_* functions anymore.
Assuming the ID is user input, you should really use prepared statements.
Also, you can handle both tests in a single query:
$stmt = $con->mysqli_prepare("SELECT COUNT(1) as `count` FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
INNER JOIN `Artist_Group` AS ag ON ag.group_id = c2a.group_id
WHERE c2a.song_id = ?");
$stmt->bind_param('i',$id);
$stmt->execute();
if($stmt->get_result()->fetch_array()[0] > 0){
...
}else{
//message that nothing was found
}

MySQLi prepared statement within while loop

I'm attempting to execute 4 prepared statement within a mysqli_fetch_row while loop. Currently my code is outputting NULL or empty values for all queries. This is my first time using prepared statements and I am trying to convert my code from mysql queries to mysqli. My code is below:
$users = mysqli_query($link, "SELECT id FROM users WHERE approved = '1'");
while ($user = mysqli_fetch_row($users)) {
if ($twitter_username_query = mysqli_prepare($username_query, "SELECT username FROM personas WHERE user_id = ?")) {
mysqli_stmt_bind_param($username_query, "d", $user[0]);
mysqli_stmt_execute($username_query);
mysqli_stmt_bind_result($username_query, $username);
mysqli_stmt_fetch($username_query);
mysqli_stmt_close($twitter_username_query);
}
if ($count_user_clicks = mysqli_prepare($count_user_clicks, "SELECT count(distinct txid) FROM users_clicks WHERE user_id = ?")) {
mysqli_stmt_bind_param($count_user_clicks, "d", $user[0]);
mysqli_stmt_execute($count_user_clicks);
mysqli_stmt_bind_result($count_user_clicks, $user_clicks);
mysqli_stmt_fetch($count_user_clicks);
mysqli_stmt_close($count_user_clicks);
}
if ($count_user_installs = mysqli_prepare("SELECT count(txid) FROM (SELECT txid FROM users_installs WHERE user_id = ? GROUP BY txid) table1")) {
mysqli_stmt_bind_param($count_user_installs, "d", $user[0]);
mysqli_stmt_execute($count_user_installs);
mysqli_stmt_bind_result($count_user_installs, $user_installs);
mysqli_stmt_fetch($count_user_installs);
mysqli_stmt_close($count_user_installs);
}
if ($calc_user_cost = mysqli_prepare($calc_user_cost, "SELECT sum(earnings) FROM (SELECT max(cost) as earnings FROM users_clicks WHERE user_id = ? GROUP BY txid) table1")) {
mysqli_stmt_bind_param($calc_user_cost, "d", $user[0]);
mysqli_stmt_execute($calc_user_cost);
mysqli_stmt_bind_result($calc_user_cost, $user_cost);
mysqli_stmt_fetch($calc_user_cost);
mysqli_stmt_close($calc_user_cost);
}
if ($user_clicks == '0') {
$user_conv = 0;
} else {
$user_conv = ($user_installs / $user_clicks) * 100;
}
echo "<tr>";
echo "<td><b>".$username."</b></td>";
echo "<td>".number_format($user_clicks)."</td>";
echo "<td>".number_format($user_installs)."</td>";
if ($user_installs[0] == '0') {
echo "<td>$0.00</td>";
} else {
echo "<td>$".number_format($user_cost / $user_installs, 2)."</td>";
}
echo "<td>".number_format($user_conv, 2)."%</td>";
echo "</tr>";
}
Use a single query that JOINs all the subqueries:
SELECT u.id, p.username, IFNULL(c.clicks, 0) AS clicks, IFNULL(i.installs, 0) AS installs, IFNULL(e.earnings, 0) AS earnings
FROM users AS u
JOIN personas AS p ON p.user_id = u.id
LEFT JOIN (
SELECT user_id, COUNT(DISTINCT txid) AS clicks
FROM user_clicks
GROUP BY user_id) AS c ON c.user_id = u.id
LEFT JOIN (
SELECT user_id, COUNT(DISTINCT txid) AS installs
FROM user_installs
GROUP BY user_id) AS i ON i.user_id = u.id
LEFT JOIN (
SELECT user_id, SUM(earnings) AS earnings
FROM (SELECT user_id, txid, MAX(cost) AS earnings
FROM user_clicks
GROUP BY use_id, txid) AS table1
GROUP BY user_id) AS e
WHERE u.approved = 1

Is this query for selecting MUTUAL FRIEND is CORRECT?

<?php
mysql_connect("localhost","root","");
mysql_select_db('db2012');
$uid = 8;
$mid = 10;
$q = mysql_query("select friend from users_friends where user = $uid") or die(mysql_error());
if(mysql_num_rows($q) > 0)
{
while($r=mysql_fetch_array($q))
{
$qq = mysql_query("select friend from users_friends where user = $mid") or die(mysql_error());
while($rr = mysql_fetch_array($qq))
{
if($r[friend]==$rr[friend])
{
$friend_name_query = mysql_query("select name from users where uid = '$rr[friend]'") or die();
$friend_name = mysql_fetch_array($friend_name_query);
echo $friend_name[name];
}
}
}
}
?>
This query is working but any other way out to use less queries ? i m a beginner programmer please let me know if there is n e thng ...
You should use just one query:
$query = 'SELECT u.name
FROM users_friends f1
INNER JOIN users_friends f2 ON (f2.friend = f1.friend)
INNER JOIN user u ON (u.uid = f2.friend)
WHERE f1.user = "'. $uid. '"
AND f2.user = "'. $mid .'"';
run the query
$q = mysql_query($query) or die(mysql_error());
and do the while loop
while($r=mysql_fetch_array($q)){
echo $r['name'];
}
You only need the if(mysql_num_rows($q) > 0) statement if you do an else, otherwise you can just use the while
You could try below in order to get mutual friends of user 8 and 10.
select * from
user_friends a inner join user_friends b on
a.friend=b.friend and (a.user='8' and b.user='10')
U could then join the user table to get the name.

Categories