PHP MYSQL Nested While loop skips iterations - php

Need help to get through this Nested WHILE loop.
The Scenario is
These are the 5 tables in my db
user_info(userid,name,picurl)
user_friends(userid,friend_id)
user_post(userid,post_id,post,time)
user_likes(userid,post_id)
user_comments(userid,post_id)
I want to access user_post table and populate the data in my android application. i can access userid,post_id and time from user_post table and using friend_id of the user from friends table. Now to display a complete post with pic and name i need to access name and picurl of the person who's post it is from user_info table. If i need to display one 1 friends post i can do this simply but when there are couple of friends with more than 1 post i can't get the name and picurl of the user and it displays null in json response.
I'm using Nested While loop for this operation following is my code.
$userid = $_POST['userid'];
$query = "SELECT * FROM user_friend WHERE userid = '$userid'";
$result = mysql_query($query);
$return_arr = array();
$return_arr['newsfeed'] = array();
//Access userid
while($row = mysql_fetch_assoc($result)) {
echo "Friend Name is ".$row['friend_id']. "<br>";
$friend_id = $row['friend_id'];
$friend_id = mysql_real_escape_string($friend_id);
//accessing user_info table to access user info
$picquery = "SELECT * FROM user_info WHERE userid = '$friend_id'";
$picresult = mysql_query($picquery);
$pic = mysql_fetch_assoc($picresult);
$row_array['name'] = $pic['name'];
$row_array['picurl'] = $pic['picurl'];
$query2 = "SELECT * FROM user_post WHERE userid = '$friend_id'";
$result2 = mysql_query($query2);
//Access Posts Against userids
while( $row = mysql_fetch_array($result2) ) {
$post_id = $row['post_id'];
//for number of likes
$likesQuery = "SELECT COUNT(*) as totallikes FROM post_likes WHERE post_id = '$post_id'";
$likesResult = mysql_query($likesQuery);
$likesvalues = mysql_fetch_assoc($likesResult);
$num_of_likes = $likesvalues['totallikes'];
//for number of comments
$commentsQuery = "SELECT COUNT(*) as totalcomments FROM post_comments WHERE post_id = '$post_id'";
$commentsResult = mysql_query($commentsQuery);
$commentsvalues = mysql_fetch_assoc($commentsResult);
$num_of_comments = $commentsvalues['totalcomments'];
$row_array['post_id'] = $row['post_id'];
$row_array['userid'] = $row['userid'];
$row_array['post_text'] = $row['post_text'];
$row_array['post_time'] = $row['post_time'];
$row_array['post_num_likes'] = $num_of_likes;
$row_array['post_num_comments'] = $num_of_comments;
array_push($return_arr['newsfeed'],$row_array);
}
}
date_default_timezone_set('Asia/Karachi');
$date = date(' h:i:s a d/m/Y', time());
echo json_encode($return_arr,JSON_UNESCAPED_SLASHES);

something like this could help. As I don't have any test data I cannot see how it's working. It should display the post_id along with the count of the likes and the comments
SELECT
p.post_id,
COUNT(c.post_id) AS comments_count,
COUNT(l.post_id) AS like_count
FROM user_post p,
user_likes l,
user_comments c
WHERE p.post_id = l.post_id
AND p.post_id = c.post
GROUP BY p.post_id

Related

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

MySql, php: Read from 2 Tables with same User ID

Hello Sorry for the previously Post:
I habe a table ´Nachrichten´ and a table 'user'.
I want the rows from 'Nachrichten' where Quelle is like $_SESSION["id"]. Quelle is a UserID. Now I need the rows from 'user' where ID is like $_SESSION["id"], too beacause I need the name and lastname from the user: This is my Query but I get no faild but no results too. Thanks for support.
$abfrage = "SELECT * FROM Nachrichten n JOIN user u ON u.id = n.Quelle WHERE n.Quelle LIKE '".$_SESSION["id"]."'";
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis))
{
$id = $row["n"]->ID; $ziel = $row["n"]->Ziel; $uhrzeit = $row["n"]->Uhrzeit; $gelesen = $row["n"]->Gelesen; $inhalt = $row["n"]->Inhalt; $vorname = $row["u"]->Vorname; $nachname = $row["u"]->Nachname;
kontakt($ziel, $vorname, $nachname, $uhrzeit, $gelesen);
echo "hjfe";
}
Just guessing...
$abfrage = "
SELECT *
FROM Nachrichten n
JOIN user u
ON u.id = n.Quelle
WHERE n.Quelle = '{$_SESSION['id']}';
";

Looping through a mysqli result

I'm trying to display a list of status updates from artists that a logged in user is following.
So far I have this:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
}
But i'm not sure how to loop through and display the returned status updates?
This isn't a strong point of mine, so any pointers would be greatly appreciated!
What prevented you from doing similar to what you'd already done for the first query? Something like follows:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
while($status_result_row = mysqli_fetch_assoc($status_result)) {
echo $status_result_row['mycol']; // This is where you know better than us
}
}
Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).
Just for avoiding multiple query, you can use one query like this:
SELECT l.*, s.*
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'
or
SELECT l.*, s.*
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'

Multiple objects per array row

I'm trying to create an API and I need to put multiple queries into my JSON ouput, the issue is everything is returned as an object of class stdClass... here is my code:
$querystr = "SELECT entry_id AS id FROM {$wpdb->prefix}connections_term_relationships WHERE term_taxonomy_id = '{$_GET['catID']}'";
$cID = $wpdb->get_results($querystr);
$dirCount=count($cID);
$arrayCategory= array();
$androidArray = array();
if($dirCount > 0){
foreach($cID as $company){
$querycInfo = "SELECT id, organization, contact_first_name, contact_last_name, bio FROM {$wpdb->prefix}connections WHERE id = '{$company->id}'";
$companyInfo = $wpdb->get_row($querycInfo);
$queryAddress = "SELECT line_1, line_2, line_3, state, zipcode FROM {$wpdb->prefix}connections_address WHERE entry_id = '{$company->id}'";
$address = $wpdb->get_row($queryAddress);
$queryEmail = "SELECT address FROM {$wpdb->prefix}connections_email WHERE entry_id = '{$company->id}' AND type = 'work'";
$email = $wpdb->get_row($queryEmail);
$queryWebsite = "SELECT title, url FROM {$wpdb->prefix}connections_link WHERE entry_id = '{$company->id}' AND type = 'website'";
$website = $wpdb->get_row($queryWebsite);
$queryPhone = "SELECT number FROM {$wpdb->prefix}connections_phone WHERE entry_id = '{$company->id}' AND type = 'workphone'";
$phone = $wpdb->get_row($queryPhone);
$arrayCategory[]= $companyInfo;
}
}else{
$arrayCategory[0]=array('organization'=>'No Company Found Within This Category');
}
$androidArray = array('companies'=>$arrayCategory);
echo json_encode($androidArray);
}
I need $arrayCategory to hold more then just $companyInfo, I need it to hold the other variables as well. This is being built for WordPress. Thanks in advance!
I ended up just formatting my SQL query in a matter that made more sense:
$querycInfo = "SELECT main.id, organization, contact_first_name, contact_last_name, bio, number FROM {$wpdb->prefix}connections main
JOIN {$wpdb->prefix}connections_phone phone ON phone.entry_id = main.id AND main.id = '{$company->id}'";
This solved the issue.

Get a number in one table and print the number's referenced name in another table

I need to create a friend system, but my loop always skips the first match and sometimes it prints copies of the same name
$result = mysql_query("SELECT * FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id");
while($row = mysql_fetch_array($result))
{
if ($row['username_id'] == 1)//the 1 will be a variable, username_id is in friends
$count = $row['friendname'];//friendname is in friends
if ($row['id'] == $count)//id is in users
echo $row['username'];//username is in users
}
Can someone see what my problem is ?
2 things:
if ($row['username_id'] == 1)
you should put that in your sql:
$result = mysql_query("SELECT username, friendname FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id where tbusers.id = ".$yourVariable);
In your query, user and friend are linked, and can only be equal.
Now, this:
$count = $row['friendname'];//friendname is in friends
if ($row['id'] == $count)//id is in users
is equal to
if ( $row['id'] == $row['friendname'] )
this sounds plain wrong. You compare a numerical id with a name. Moreover, your sql query already retrives all friends from users. In the version I showed here, it retrieves only friends of the user you are interested in.
finally, you print (echo) the name of the user, not of the friend. In my opinion the following code will do what you want:
$result = mysql_query("SELECT friendname FROM tbfriends WHERE username_id = ".$yourUserVariable);
while($row = mysql_fetch_array($result))
{
echo $row['friendname']; // or better: echo $row['friendname'], '<br>';
}
edit: after comment...
so if ( $row['id'] == $row['friendname'] ) means the user is his own friend. can that happen?
this code shall print what you want, friend names.
/*
$result = mysql_query("
SELECT username as friend_name,
friendname as friend_id,
username_id as user_id
FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id
WHERE tbusers.id = ".$yourVariable);
*/
$result = mysql_query("
SELECT username as friend_name,
friendname as friend_id,
username_id as user_id
FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.friendname
WHERE tbfriends.username_id = ".$yourVariable);
while($row = mysql_fetch_array($result))
{
echo $row['friend_name']; // or better: echo $row['friend_name'], '<br>';
}

Categories