Group result by field - php

Am building a messaging system for a site, but i want it to have an instant messaging app feel.
I have table with a structure like this:
<!-- language: lang-none -->
id
R_id = Reciever's id
S_id = Sender's Id
message
read = 0 if unread, 1 if read
post_time
conv_id = conversation id
I am trying to build a query that retrieves all messages pertaining to a receiving user and display it in a group format i.e all messages from a user grouped with the user's name, sort of like facebook messages.
This is the method in my model, am working with codeigniter
function get_user_conversations($user_id) {
//Load Models
$this->load->model('conversation_model');
//Load helper
$this->load->helper('date');
//database query
$q = $this->db->select('*')
->from('conversations_inbox')
->where('R_id',$user_id)
->group_by('S_id')
->order_by('post_time','desc')
->get();
$conversations = $q->result();
return $conversations;
}

Maybe something like this?
// Presuming you want the most recent ones first
$q = mysql_query("SELECT message FROM `TABLE` WHERE `R_id`='USERNAME_HERE' ORDER BY `post_time` DESC");
while ($row = mysql_fetch_array($q)) {
echo "<li>Message: " . $row['message'];
}
I'm honestly not really sure what you're asking, so that's the best I can do.

Related

Pulling data from multiple mysql tables

Hello I am creating an API for my android application and pulling posts from database so far I successfully pull the posts with its photo and caption yet I have no idea how to pull the posts user profile picture and username which are stored in my users table. Please anyone to point me in the right direction would be a saviour. This is the code I use in php to pull the post's details
$sql = "SELECT * FROM Posts";
$result = $conn->query($sql);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
}
What you want is a join. A good reference for the basics can be found on w3schools.
Basically (and without knowing the details of your database) there has to be a connecting ID in both tables, in this case a user id. For example:
SELECT
Posts.id,
Posts.user_id,
Posts.caption,
Posts.photo,
Users.user_id,
Users.username,
Users.profile_pic
FROM Posts
INNER JOIN Users ON (Users.user_id = Posts.user_id);
This will get every post and for each post it will fetch the relevant line(s) from the Users table (where the user_id is the same as in the post).

MYSQL spillover function

I am currently trying to code a Networking website and am stuck at the spillover function stage.Here is how it works, each registered user of the site is only allowed to refer two people into the network (they have a referral link for this). If however,a member gave his/her link to refer more than two people and the registering folk wants to sign up with the link,the following event should occur:
1. PHP should query MYSQL Database to ascertain if the sponsor has referred up to two(2) people, if YES then MYSQL will search for a random sponsor-username to replace the initial sponsor .
2. If on the contrary,MYSQL checks and found that the sponsor hasn't referred two people yet, then MYSQL will proceed to using the sponsor username for the new registering member.
Below is what the database table looks like:
My MYSQL database snapshot
The table name is affiliateuser, the referedby column is where the sponsors are shown for each member,i need member to only be able to appear as sponsor twice (maximum) under the referedby column.
Looking at the table above,the user yelefash2 has referred two people with his link while user mipe305 hasnt referred anyone with his link or username,i need to set a balance and if a third person tries to register with yelefash2's username/referral link,let PHP/MYSQL replace him with a user who hasnt referred two people yet (it could be random pick or otherwise), this will spill over members automatically as referrals onto available spaces, e.g mipe305
I have tried the following PHP codes but it doesn't work:
$ref=mysqli_real_escape_string($con,$_POST['referral']);//data from the referrer webform field//
$result = mysqli_query($con,"SELECT count(*) FROM affiliateuser where username = '$ref'");
$row = mysqli_fetch_row($result);
$numrows = $row[0];
if ($numrows==0)
{
$msg=$msg."Sponsor/Referral Username Not Found..<BR>";//for checking if provided sponsor exits
$status= "NOTOK";
}
$reea = mysqli_query($con,"SELECT username,referedby, COUNT(username) FROM affiliateuser GROUP BY referedby ASC");
$reeeb = mysqli_query($con,"SELECT count(*) FROM affiliateuser where referedby='$ref' ");
$row = mysqli_fetch_row($reeeb););
$refcount = $rowp[0];
if ($refcount ==2 OR $refcount >2)
{$reee = mysqli_query($con,"SELECT username,referedby, COUNT(username) FROM affiliateuser GROUP BY referedby ASC");
$reeel = mysqli_query($con,"SELECT referedby FROM affiliateuser where COUNT(username)<2 ");
$row = mysqli_fetch_row($reeel);
$refpick = $row[0];
}
else
{$refpick=mysqli_real_escape_string($con,$_POST['referral']);}
I know i must be doing something wrong,am kinda new to MYSQL and PHP, any help would be pretty much appreciated
Changed my awnser:
$reea = mysqli_query($con,"SELECT username,referedby, COUNT(username)
FROM affiliateuser GROUP BY referedby ASC");
is not doing anything.but it could be something going somewhere else in the page and its not in this post.
but your result array variable is wrong.
$refcount = $rowp[0];
should be
$refcount = $row[0];
because $rowp is not defined anywhere.... also its row result:
$row = mysqli_fetch_row($reeeb););
is wrong. it should be:
$row = mysqli_fetch_row($reeeb);
at the end, the else condition:
{$refpick=mysqli_real_escape_string($con,$_POST['referral']);}
can be simplified by:
{$refpick=$ref;}
One thing about comparing,
the if ($refcount ==2 OR $refcount >2) should work,
but if (($refcount ==2) OR ($refcount >2)) will guarantee the correct operation.
I personally use || (double pipe) instead of "or" personally.
so I would have wrote it as: if (($refcount ==2) || ($refcount >2)) {

Compare columns from multiple tables in one query PHP/SQL

I'm trying to change my user's news feed to only show posts from friends, instead of from all users on the site. I managed to do so doing something like this:
function friend_posts(){
global $session_user_id;
if(friends_exist($session_user_id) === true){
$friends = mysql_query("SELECT * FROM `friendship` WHERE `user_id` = $session_user_id AND `pending` = 0");
while($friend = mysql_fetch_array($friends)){
$friendID = $friend['friend_id'];
$posts = mysql_query("SELECT * FROM `posts` WHERE `userid` = $friendID ORDER BY `timestamp` DESC");
while($post = mysql_fetch_array($posts)){
$friendData = user_data($post['userid'],'username','first_name','last_name');
echo $friendData['username'].": ".$post['status']."<br>";
}
}
} else {
echo "Nothing to display. Try adding some friends!";
}
}
However, this isn't that convenient. For example, if I want to paginate, I don't know how I'd even start to do that using something like this. Also if multiple users post, how would I sort them by 'timestamp' descending?
I'm guessing the only route I can take is accessing columns from multiple tables somehow, then sorting by the timestamp, which is stored in the posts table. The friendship table just has id, user_id, friend_id and pending.
How would I go about doing that? Is there an easier way to do what I'm trying to do?
I'm very new to SQL. I don't know too much other than inserting/deleting/updating.
You could use a single statement like this:
SELECT * FROM posts WHERE userid in
(SELECT friend_id FROM friendship WHERE user_id = $session_user_id AND pending = 0)
ORDER BY `timestamp` DESC
This way you get only the posts of the friends of the current user. If you also need data from the friendship table then use a join.

How to make a Twitter-like following system

How can i make a Twitter-like following system where, if you follow someone, you will receive their tweets. I have a database table called "users", "followings", and "posts". The users table holds the users that are on my site. The followings shows the persons followers, this table is setup like this :'id, user_one, user_two'. And the posts table holds all the tweets or posts that the unique user has.
I have a profile page set up for each user, with a follow button. And also I have a news feed for the user, but in that news feed I need it to show posts from users that the logged-in user is following. So is there anyway for me to have a user follow someone and receive the posts from that user on their news feed.
Now I did some research: their system wouldn't seem to work. I kept getting this error:
Warning: implode() [function.implode]: Invalid arguments passed in function.php on line 12
SELECT
user_id,
body,
stamp
FROM posts
WHERE user_id in ()
ORDER BY stamp DESC
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in function.php.
This line right here was suppose to help make it where when you follow that person you will receive there tweets and stuff
function show_posts($userid,$limit=0){
$posts = array();
$user_string = implode(',', $userid);
$extra = " and id in ($user_string)";
if ($limit > 0){
$extra = "limit $limit";
}else{
$extra = '';
}
$sql = "select user_id,body, stamp from posts
where user_id in ($user_string)
order by stamp desc $extra";
echo $sql;
$result = mysql_query($sql);
while($data = mysql_fetch_object($result)){
$posts[] = array( 'stamp' => $data->stamp,
'userid' => $data->user_id,
'body' => $data->body
);
}
return $posts;
}
I believe this piece of code, which is supposed to show posts from other users, is causing this problem but I don't know why.
Use a join. For example:
select user_id, text from posts
inner join followings on posts.user_id = followings.followed_id
where followings.follower_id = :user_id;
If I may recommend, stop using the mysql_ functions; they are deprecated and should not be used in newer applications. Instead, I'd recommend using PDO.

Ordering retrieved information from a database

I'm creating a feed by retrieving information from my database using nested while loops (is there a better way to do this?).
I have one table called users with all the names amongst other things. The other table is called messages which has messages, the user who posted it, and a timestamp.
$userQuery = mysql_query("SELECT name FROM users");
while ($user = mysql_fetch_array($userQuery, MYSQL_NUM)) {
$messageQuery = mysql_query("SELECT message FROM messages WHERE user = $user ORDER BY timestamp DESC");
while ($message = mysql_fetch_array($messageQuery, MYSQL_NUM)) {
echo "$user[0]: $message[0]";
}
}
The problem is that it doesn't order by the timestamp and I can't tell how it's ordered. I've tried timestamp, datetime, and int types with UNIX timestamps.
EDIT: I should add that the user and message matches up fine, it's just the ordering that doesn't work.
I guess you get your users in more or less random order and "within" one user the sorting is ok?!
use:
$result = mysql_query('select users.name,messages.message from messages join users on (users.name=messages.user) order by messages.timestamp');
while($row = mysql_fetch_row($result))
echo "$row[0]: $row[1]";
That should give you an ordered result (at least if you have a column called messages.timestamp. Check the name ;-)). And all in one query...
For the query, you could create a join
SELECT u.name as name, m.message as message
FROM users u inner join messages m
on u.user = m.user
order by
m.timestamp DESC
As for the second part, I don't see anything wrong with your could. May be you could post some samples of your data to see if that is making any difference.

Categories