i am trying to create an instant messaging box for users on my site, badically if a user goes onto another users profile they can write in the chat box and send an instant message to the other user.
I'm having trouble getting the mysql to get the results and filter it so that if
user 1 messages user 2 then only user 1 and user 2 can see the conversation.
At the moment though only the logged in user or ".$_SESSION['user_id']." can see the conversation but i want both users to be able to see their conversation between each other.
the other problem is that if user 3 messages user 2 as well as user 1 then user 2 gets all of the conversations from user 1 and 3 but i only want one conversation between each user per box.
my database ptb_chats looks like this:
id | to_user_id | from_user_id | date_added| content |
2 2 1 April 2011 hello
here's my php:
<?php
$chat_set = get_chats();
while ($chat = mysql_fetch_array($chat_set)) { ?>
<?php echo "<div class=\"chat_row\">".$chat['content']."</div>"; ?>
<? } ?>
here's my mysql:
function get_chats() {
global $connection;
global $profile_id;
$query = "SELECT *
FROM ptb_chats, ptb_profiles
WHERE ptb_profiles.user_id = ptb_chats.from_user_id
AND ptb_chats.to_user_id=".$_SESSION['user_id']."
ORDER BY ptb_chats.date_added ASC";
$chat_set = mysql_query($query, $connection);
confirm_query($query, $connection);
return $chat_set;
}
please can someone show me what i need to do to get this to work? thanks
Related
I have a posts table like this:
post_id user_id title date
12 1 abc 7/20/2014
13 1 cde 7/21/2014
14 2 fgh 7/22/2014
And a users table like this:
user_id username email password
1 name1 email1#domain.com ******
2 name2 email2#domain.com ******
The user_id in the posts table is the foreign key of the users table.
Note:
Assume that I store the user's session successfully by using $_SESSION['user_id'] .
Assume that I can echo all 3 post titles along with their usernames successfully too.
Now I would like to echo the edit hyperlink (Edit) for the post titles of a certain user, for example, user_id 1 or 2 after he's logged in. It means that if the user named name1 signs into his account and browses the post whose id is 14, he cannot see the edit hyperlink because it belongs to the another user named name2, whose session id, if any, should be unableable now, and vice versa.
For me, this is my code:
$q = "SELECT title, post_id, p.user_id AS currentuser
FROM posts AS p
INNER JOIN users AS u USING (user_id)
ORDER BY date ASC
";
$r = mysqli_query ($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$uid = isset($_SESSION['user_id']);// variable for the seesion
$current_user = $row['currentuser'];// variable for the certain user ID
if($uid && $uid == $current_user){
echo " Edit </div>";
}
Then I test it, you know, it shows the edit hyperlink in every post title, but not what i expected.
Can you help? Thanks
$uid = isset($_SESSION['user_id']);
This results to either true or false. try
$uid = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : -1;
What I did was use a ternary operator so if the session variable is set, you set it to it otherwise you set it to -1, which most probably does not exsist in a table id column
I have tried upto end everything to the best of my knowledge but all in vain. I'm building a community website and i am stuck at one thing. I want to display a text on my wall when my friends become friends with other users. Just like Facebook displays it. For eg.
"John doe is now friends with max stone"
And
"John doe is now friends with max stone and 5 other people"
I am successfully getting it displayed but not like the one I showed above. I do it using while loop from notifications table. I tried but couldn't get it like facebook shows. so please help me get this thing done.
I am posting my code so that you can get clear idea of my code and my mistakes in my code so you can clear.
$ check_if_friendship_created = mysql_query ("SELECT * FROM `users_notifications`
WHERE `friend_1_username` IN (SELECT `friend_2_username` FROM `users_friends`
WHERE `friend_1_username` = '". $ logged_user ['username']."')
GROUP BY `friend_2_fullname` ORDER BY `notification_time` DESC");
also to let you all know that my friends table is a symmetrical in design...
looking forward to your positive reponse. Thank you....
why don't you have a separate table for friendship notification? Meaning when user1 is friend with user2 you insert the details to the friendship notification table.
table structure
id reqeust_sent_by request_accepted_by friendship_date
So let's assume John sends friend request and then Jack accepts the request, when Jack accepts the request then you insert that detail to the table. You better use mysqli prepared statements or pdo. So here is mysqli prepared statements
$request_sender = 'John';
$logged_user = 'Jack';
$date = date('Y-m-d H:i:s');
$mydabtase = new mysqli('localhost', 'root', '', 'database_name');
$stmt = $mydatabse->prepare("insert into friendship_notification (request_sent_by, request_accepted_by, friendship_date) values (?,?,?)");
$stmt->bind_param('sss' $request_sender, $logged_user, $date);
$stmt->execute();
$stmt->close();
now to select the data you can do
$stmt = $mydatabase->prepare("select * from friendship_notification where request_sent_by ! = ? or requst_accepted_by ! = ? order by id desc");//do your select here. here we are selecting where either rows are different from the logged in user because we don't want to show the logged in user that he has became friends with somebody else, we show this for other users.
$stmt->bind_param('ss', $logged_user, $logged_user);//follow the same procedure when binding the parameters, s means string. if you have 2 ? then you need 2 s along with 2 variables.
$stmt->execute();
$result = $stmt->get_result();//this gets the results
$total = $result->num_rows;//this returns the total number of rows for the above select query
while($row = $result->fetch_assoc()){
//if the total is less than 3 people we do the below
if($total < 3){
echo $row['request_accepted_by']."is now friends with".$row['request_sent_by'].",";
}
elseif($total > 3 ){
$stmt2 = $mydatabase->prepare("select * from friendship_notification where request_sent_by ! = ? or requst_accepted_by ! = ? order by id desc limit 1");//do your select here
$stmt2->bind_param('ss', $logged_user, $logged_user);
$stmt2->execute();
$result2 = $stmt2->get_result();
$row2 = $result2->fetch_array();//we only need one row so no need for while loop.
echo $row['request_accepted_by']."is now friends with".$row2['request_sent_by']."and ".$total-1." others.";
}
}
So this will display something like
John is now friends with Max and magna. and on the second case
John is now friends with Max and 4 others.
if you want the facebook way then you need to use ajax to auto refresh.
I am trying to display records of a particular job that has already been done by someone else before a new provider sees it. If the status is open, there should not be any information to be displayed as supposedly, no one has made any report about it. If the status is awarded, then necessary data should be displayed. Right now, the information to be shown are viewable. The problem the data is displayed in every job post even it is not the report for such a job.
Example,
Job ID | Title | Description | Subject | Job Status
2 | Math Tutor | I need Math tutor! I need Math tuto... | Mathematics | Open
1 | English Tutor | Edited... | French | Awarded
If I click "Open", I should not be able to see any record because it is still not done. If I click "Awarded", I should see details about the job. Right now, the data is showing properly for JOB ID 1 which was already awarded. However, the same data is shown as well in JOB ID 2.
How do I properly display the data in its proper place? I've been trying everything to do it. I included the JOB ID to be displayed to see if there's something wrong with it. But there's none, it shows JOB ID 1 in both jobs 1 and 2. How do I display it just in job 1 where it belongs?
Here's my code in controller:
public function view_tutors_tutorials()
{
$this->validateRole('provider');
$this->load->model('tutorial_model');
$this->load->model('auth_model');
$data['subject_list'] = $this->array_to_select( $this->tutorial_model->get_all_subjects(), 'id','name');
$my_preference = $this->tutorial_model->get_tutors_tutorials(isset($_GET['subject_id'])?$_GET['subject_id']:'0', isset($_GET['sort_by'])?$_GET['sort_by']:'');
$data['my_preference'] = $my_preference;
$this->load->view('provider/view_tutors_tutorials', $data);
}
and this in my model:
public function get_tutors_tutorials($subject_id = NULL, $sort_by = NULL)
{
//responsible for displaying job contracts for provider user.
$this->db->select('tutorial.status as status, tutorial.client_id as client_id, tutorial.id as tutorial_id, subject.name as name, tutorial.title as title, tutorial.description as description, tutorial.start_date as start_date, tutorial.update_date_time as update_date_time,tutorial_proposal.provider_id as provider_id,provider.first_name as first_name,provider.last_name as last_name,tutorial.contract_status as contract_status,tutorial.provider_feedback as provider_feedback,tutorial.client_notetoself as client_notetoself,tutorial.client_feedback as client_feedback,tutorial.provider_notetoself as provider_notetoself,tutorial.material_used,tutorial.recommendation')->from('tutorial');
$this->db->join('subject', 'subject.id = tutorial.subject_id');
$this->db->join('tutorial_proposal', 'tutorial_proposal.provider_id = tutorial.provider_id');
$this->db->join('provider', 'provider.id = tutorial_proposal.provider_id');
$this->db->where('tutorial.status', 'Awarded');
if ( ! empty($subject_id) )
{
$this->db->where('subject_id', $subject_id);
}
//if there's no sort selection made, the jobs will be sorted from newest to oldest
if ( empty($sort_by))
{
$sort_by = "update_date_time desc";
}
$this->db->order_by($sort_by);
$query = $this->db->get();
return $query->result_array();
}
I look forward to getting any help.
You need to remove where condition for status in you model's query :
$this->db->where('tutorial.status', 'Awarded'); // this should be removed
Also make sure, your subject_id passed properly.
I'm still new to PHP and MySQL. I'm currently working on a random quote generator website. When a user visits for the first time or refreshes the page, the PHP code fetches a random row from the MySQL table and echos the results.
If a user likes a particular quote, I want him/her to be able to bookmark the page the quote is contained in. I believe this requires a unique URL for each random code that is generated. I can't figure out how to do this with the code I currently have and would like anyone's help.
This is my table so far:
+----+-----------+-----------+
| id | quote | source |
+----+-----------+-----------+
| 1 | hello | test1 |
| 2 | world | test2 |
| 3 | random | test3 |
+----+-----------+-----------+
This is my code so far:
<?php
require('connection.php');
// Last query result stored in sessions superglobal to avoid immediately repeating a random quote
session_start();
if (empty($_SESSION['lastresult'])) {
$_SESSION['lastresult'] = null;
}
$query = "SELECT * FROM `test` WHERE `id` != '%s' ORDER BY RAND() LIMIT 1";
$query = sprintf($query, mysql_real_escape_string($_SESSION['lastresult']));
$result = mysqli_query($dbc, $query) or die(mysql_error());
if (mysqli_num_rows($result) == 1) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$_SESSION['lastresult'] = $row['id'];
echo '<p>' . $row['quote'] . '</p>' . '<p>' . $row['source'] . '</p>';
}
} else {
echo '<p>Sorry, there was an error. Please try again by refreshing the page or clicking the query button.</p>';
}
?>
Any other code advice would also be appreciated.
There are three ways that spring to mind.
All require you to implement a version if the page that takes a quote id, similar to the one #DanGoodspeed suggests in his comment against your question.
Add a link from you existing page to the new id driven page with a label 'bookmark this page to return'. Not ideal, but very simple.
Add some JavaScript in your existing page to update the URL after loading to include the id, therefore making it appear as if it was the other. See this answer Modify the URL without reloading the page for details.
Instead of using the page you have now, generate a new page (using much of what you have already written) that returns a location redirect header with a URL that has a random id in it.
OK,so I have headech from searching everywhere how to solve this problem..Im trying to show online users,but not all users,only who is in your friend list..
So I have table named users_online and when user logs-in in my website in that table is automaticly created 1 row with date,ip,name,user_id and friend_array (where all user's friends are kept)
So for example I log in in my website and row is created in users_online table. I want to see only my friends online and these friends are stored in friend_array column (1,5,16,5 (thats friends id number)).. How can I take data from friends_array colum and see which one of these id's are logged at the moment,which means which of these id's are existing in user_online table and display on my profile?
I hope is not confusing question...
Well thats my code..all stores in online.php file:
// Checking wheter the visitor is already marked as being online:
$inDB = mysql_query("SELECT user_id FROM users_online WHERE user_id=".$userid);
if(!mysql_num_rows($inDB))
{
// Selects some data required to insert into users_online table from users table
$DB = mysql_query("SELECT img,fname,friend_array FROM users WHERE user_id=".$userid);
while($row=mysql_fetch_assoc($DB))
{
$img = $row['img'];
$fname = $row['fname'];
$farray = $row['friend_array'];
}
mysql_query(" INSERT INTO users_online (user_id,ip,img,fname,friend_array)
VALUES(".$userid.",'".$intIp."','".$img."','".$fname."','".$farray."')");
}
else
{
// If the visitor is already online, just update the dt value of the row:
mysql_query("UPDATE users_online SET dt=NOW() WHERE user_id=".$userid);
}
// Counting all the online visitors:
// Thats where i need to work out with friend array..
// I need to display all online friends only
list($totalOnline) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM users_online"));
// Outputting the number as plain text:
echo $totalOnline;
<?php
$friends = array(1,5,16); // Array of friends
$friendIDs = implode(',', $friends); // Turns array into string for SQL select statement
// Gets only friends info from DB
$sql = "
SELECT date, ip, name, user_id
FROM users_online
WHERE user_id IN (".$friendIDs.")";
?>
Sorted out guys! Thanks for your help!
//Selecting an array from db
$DB = mysql_query("SELECT friend_array FROM users_online WHERE user_id=".$userid);
while($row=mysql_fetch_assoc($DB))
{
$friend_array = $row['friend_array'];
$friends = array($friend_array); // Array of friends
$friendIDs = implode(',', $friends);
}
// Counting all the online friends:
list($totalOnline) = mysql_fetch_array(mysql_query("
SELECT COUNT(*)
FROM users_online
WHERE user_id IN (".$friendIDs.")"));
// Outputting the number as plain text:
echo $totalOnline;
Output was 1 user online as i was loged in with 2 browsers and in users_online table was created 2 rows with id 1 and 2..And id 1 had 3 friends in array (2,5,16), and user with id 2 had (1,3)..So in each of the browsers output was 1..Uray! I hope this question helps someone..Btw Im using update function on msql table and if user logs out,i just delete row in users_online table :)
You should consider changing the database schema. Here's an example:
USER table:
id | name | current_session_id
USER_FRIEND_USER table (contains friends that user has added):
user_id | friend_user_id
SESSION table:
id | user_id | created_at | expires_at
SQL Query to get list of friends for user with id '?':
SELECT u.id, u.name FROM USER u
INNER JOIN USER_FRIEND_USER ufu ON (ufu.friend_user_id = u.id)
INNER JOIN SESSION s ON (s.id = u.current_session_id)
WHERE ufu.user_id = ? AND s.expires_at >= NOW();
Here's SQL Fiddle link: http://sqlfiddle.com/#!2/34f83/1/0