How to display messages from the database on left and right? - php

'I made a simple chat box with php but the problem is i want to display my messages on the right and the other user messages on the left i made two while loops but they didn't work. My table is like this
(Sender - reciever - msg)
I want to display each message ordered by time and on different places right side and left side
if (isset($_POST['user_id'])){
$sender_id = $_POST['user_id'];
$sql = "SELECT * FROM messages_sys WHERE send_id=$sender_id AND reciever_id=$uid";
$sql_query = mysqli_query($conn, $sql);
print_r($sql_query);

you can use 'if' statement inside for loop :
foreach($messages as $message){
if($message->reciever == user_id){
<div class="right">$message</div>
}elseif($meesage->sender == user_id){
<div class="left">$message</div>
}
}
of course you have to open and close php tag before type html code inside

Related

Need to select specific row and a specific column within that row and compare it with a php variable

This is my block of code for doing that. It works fine until it reaches the last if statement. I cannot get it to find the Graphics column using the Department_ID. I am trying to check if the user input is equal to a id within the table. Then check if that id requires graphic work done. To do that, I need to find out that for that specific project graphic is a 1 in the database.
if($graphics_id != Null)
{
$query = mysqli_query($connect,"SELECT * FROM Project_Overview WHERE Project_ID='".$graphics_id."'");
$row = mysqli_fetch_assoc($query);
//echo $row['Project_ID'];
if($graphics_id == $row['Project_ID']) //if the graphics_id matches a project_id in the table
{
$result = mysqli_query($connect, "SELECT Graphics FROM Department WHERE Department_ID ='".$graphics_id."'")
$row = mysqli_fetch_assoc($result);
if($result)
{
echo $row['Department_ID'];
} else {
echo "This Project does not require graphics!"
}
} else {
echo "Project_ID ".$graphics_id." does not exist!";
}
}
A few thoughts:
The second SELECT Statement selects the Graphics column, but later you are echoing $row['Department_ID']; which should be empty as the only key in $row would be Graphics
The last if-Statement is if($result). Don't you mean if($row)? If $result is false (and hence "This Project does not require graphics!" is printed out), this would indicate, that mysqli_query has failed, possibly because of an error in your second SQL statement.
And, as ThomasEllis said, a JOIN would be nicer and SELECT * is not wrong but returns (probably) more than you need.
Depending on where $graphics_id comes from (a user input?) you should consider escaping it for security reasons ($graphics_id_escaped = mysqli_real_escape_string($connect, $graphics_id); - just in case ;)

Multiple MYSQL: PHP loops not working

I've been writing some code that essentially collects information based on schools and the user search input. Once the information is pulled up, I also query a database containing users to show how many are signed up at each school, and then another database containing files showing how many files have been uploaded from each school.
I imagine this would require a three tiered loop? If I query the school database and then the student database in succession it works great (Every school will have the appropriate number of students signed up displayed). However the problem is with the files. If I add in the file query, it will only show the first two results of the schools.
This leads me to believe that the file database query isn't correct and after testing a two tiered loop (this time will files instead of students) it appears to be the case. So, what am I doing wrong with the file database code? I copied it directly from the student database code so I haven't a clue why this one won't work. Here is the code that works:
mysql_select_db($database_geographic, $geographic);
$query_school = "SELECT * FROM geographic.school WHERE countryid='$countryid' AND stateid='$stateid' ORDER BY school_name ASC";
$school = mysql_query($query_school, $geographic) or die(mysql_error());
$totalRows_schools = mysql_num_rows($schools);
while ($row_school = mysql_fetch_assoc($school)) {
echo $row_school['school_name'];
echo $row_school['city_name'];
echo $row_school['state_name'];
echo $row_school['schoolid'];
$schoolid = $row_school['schoolid'];
mysql_select_db($database_user_information, $user_information);
$query_users = "SELECT COUNT(*) AS studentcount FROM users WHERE school_name= '$schoolid'";
$users = mysql_query($query_users, $user_information) or die(mysql_error());
while ($row_users = mysql_fetch_assoc($users)) {
echo $row_users['studentcount']; }
But if I throw in this third files loop statement it will not work.
mysql_select_db($database_files, $files);
$query_files = "SELECT COUNT(*) AS filecount FROM file_data WHERE school_id= '$schoolid'";
$files = mysql_query($query_files, $files) or die(mysql_error());
while ($row_files = mysql_fetch_assoc($files)) {
echo $row_files['filecount']; }
}
If I use the file query in place of the student query it will not work either. The problem must be with the file query but I can't figure it out. Any help would be awesome! Thanks!

Simple PHP chat quirk

I've been working on a quick and simple jQuery/PHP chat to put in my website for the visitors to communicate. I've extimated peaks of 200 simultaneous website users (connected users) with at most 10-20 people actually chatting.
Here's the quirk:
As I experienced already twice (thought it seems to be rather an unlikely event more than something happening after you perform something specific) the chat happens to load multiple messages which have already been red and display them.
Trying to keep the chat system as simple as possibile I came up with this code:
HTML CODE:
<div class="chat">
<ul class="chat">
<li class="chat" >
<h5 class="chat">Date</h5>
<h6 class="chat">Time</h6>
<h4 class="chat">User</h4>
<br/>
<q class="chat">Message</q>
</li>
</ul>
<input class="chat" placeholder="write something..."/>
</div>
As you can see I put a placeholder li element for the jQuery to take and use as a snippet to create new li elements with the actual messages and prepend them inside the ul element.
jQuery CODE:
Sending messages:
$(document).ready(function(){
chatSnippet = $('ul.chat').html(); // here chatSnippet is a global variable
$('ul.chat').html('');
$('input.chat').change(function(event){// Send your message
message = $(this).attr('value');
// first thing I perform an asynchronous POST to the receiving php script
$.post(
'php/chatRec.php',
{
user : currentUser,
message: message,
}
);
// meanwhile I add a new li element to the chat html with the content just submitted
date.setTime(event.timeStamp);
hours = ''+date.getHours();
if(hours.length < 2) hours = '0'+hours;
minutes = ''+date.getMinutes();
if(minutes.length < 2) minutes = '0'+minutes;
day = ''+date.getDate();
if(day.length < 2) day = '0'+day;
newChatMessage = chatSnippet.replace('Date', ''+day+' '+months[date.getMonth()]);
// here months is an array with the months names (in italian)
newChatMessage = newChatMessage.replace('Time', ''+hours+':'+minutes);
newChatMessage = newChatMessage.replace('User', connectedUser);
newChatMessage = newChatMessage.replace('Message', message);
$mess = $(newChatMessage);
$mess.hide().prependTo('ul.chat').fadeIn(500);
$(this).attr('value','');
});
refreshChat(''); // this function retrives new messages from the DB
// Here I perform a void refreshChat call so I'll get all the messages in the DB regardless from the currentUser (at page refresh)
});
Receiving messages:
// This code is placed outside (before) the .ready function
function refreshChat(user){// Receiving messages
$.post(
'php/chatInv.php',
{
user : user,
token: lastMessage // this variable contains the token of the last red message
},
function(data){
receivedMessages = jQuery.parseJSON(data);
for(message in receivedMessages){
message = receivedMessages[message].Message;
date = receivedMessages[message].Day.split('-');
time = receivedMessages[message].Time.split(':');
newChatMessage = chatSnippet.replace('Date', ''+date[2]+' '+months[parseInt(date[1])-1]);
newChatMessage = newChatMessage.replace('Time', ''+time[0]+':'+time[1]);
newChatMessage = newChatMessage.replace('User', receivedMessages[message].Sender);
newChatMessage = newChatMessage.replace('Message', message);
$mess = $(newChatMessage);
$mess.hide().prependTo('ul.chat').fadeIn(500);
lastMessage = receivedMessages[messages].token;
}
nextRefresh = setTimeout("refreshChat('"+currentUser+"')",2000);
// When I'm done I set a timeout of 2 secs and then perform another refresh
}
);
}
PHP CODE:
Receive a new message (I think the issue is in here):
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("chat") or die(mysql_error());
$characters = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$token = $characters[rand(0,61)].$characters[rand(0,61)].$characters[rand(0,61)].$characters[rand(0,61)].$characters[rand(0,61)];
$all_Msgs = mysql_query("SELECT * FROM Messages ORDER BY ID");
$prev_Msg = array('ID' => 1 , 'Sender' => $_POST['user'], 'Message' => $_POST['message'], 'Day' => date("Y-m-d"), 'Time' => date("H:i:s"), 'token' => $token);
while($Msg = mysql_fetch_array($all_Msgs)){
$update_success = mysql_query("UPDATE Messages SET Sender='".$prev_Msg['Sender']."', Message='".$prev_Msg['Message']."', Day='".$prev_Msg['Day']."', Time='".$prev_Msg['Time']."', token = '".$prev_Msg['token']."' WHERE ID=".$Msg['ID']);
$prev_Msg = $Msg;
}
Basically what I do here is receive the new post message, generate a token and an array element (which is itself an array) containing the new entered datas, done this I perform a seuqence of UPDATE statements on a fixed size SQL table overriding the new datas on the first record and then overriding each record with the previous one (so that the last record will be finally lost).
Sending messages:
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("chat") or die(mysql_error());
$receiver = $_POST['user'];
$token = $_POST['token'];
$all_Msgs = mysql_query("SELECT * FROM Messages ORDER BY ID");
$newMessages = array();
while($Msg = mysql_fetch_array($all_Msgs)){
if($Msg['token'] == $token) break;
if($Msg['Sender'] != $receiver) array_unshift($newMessages,$Msg);
}
echo json_encode($newMessages);
So I send the client the JSON encode of an array of all the records in the DB inserted after the last known message and whose author was not the querying client.
My suspects:
I came to the conclusion that when the message reception (server side) is being performed there is a time span when each message is taken from the DB, if a refresh is being performed in the meanwhile the message is not found and if that message was the one we were looking for as the last red message then the server will just select all the messages in the table and send them back.
The result is you see a bunch of messages you already red without your messages in between (cuz they were added to the view client side and the server script doesn't send you back your own messages)
Stated that:
I don't care if the messages aren't exactly in the actual insertion order: let's say A and B are chatting, the actual real messages order is BAB, but A may se the order ABB for his view is immediatly updated at input time (this helps me keep a 'fast-realtime' feel)
I don't care if some message is lost (like if it falls over the fixed DB table edge before someone can read it)
At this time I don't care much about actual efficency, speed and optimization
I know I should probalby handle the message insertion differently adding the new record and then updating the IDs only and delete the last record out. But if possible I'd like to keep this UPDATE-only fashion.
do you think my interpretation of the problem is right?
If not: what would then be the cause? / how can I fix that?
If yes: how can I fix that easily?
If the actual fix is rather complex: how actually likely to happen would be this quirk in a 10-20 users chat?
Thanks
I noticed this when I worked on a chat code too, the solution is to store the last message ID (set as an Auto Increment field in MySQL) in a session and search the database for messages where the ID is higher than that, rather than use the time() function.
if (!$_SESSION['message_id']]) {
// if there isn't a message_id, select the last seven entries in the message list
$sql = "SELECT messages.message_id, messages.message, users.username FROM (SELECT * FROM messages, users user.user_id = messages.user_id ORDER BY message_id DESC LIMIT 7) as new_tbl ORDER BY message_id ASC";
} else {
// if there is a message_id, select the messages sent since the last entry
$sql = sprintf("SELECT messages.message_id, messages.message, users.username FROM messages, users WHERE user.user_id = messages.user_id message_id > '%d'", $_SESSION['message_id']);
}
$data = array();
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
// build the data array from the mysql result and set the message_id session to the id of the last message
$data[$i] = array('user' => $row['username'], 'message' => $row['message']);
$_SESSION['message_id'] = $row['message_id'] > $_SESSION['message_id'] ? $row['message_id'] : $_SESSION['message_id'];
$i++;
}
Obviously you'd need to escape the session!
If there isn't a message_id session, it loads the last 7 messages from the table (ordered descending, then orders those messages in ascending order). If there is a message_id session, it loads new messages.
In the while loop, it builds a data array (I send it to my script as JSON) and sets the message_id session as the message_id row, with a failsafe check to make sure the message_id session doesn't end up being lowered.
The SQL implies that you have a table of users with the user_id and username, and a table of messages with a user_id, message_id and message.

comment like facebook script

I already have an script where it will allow a user whom is logged in to comment on other users. One field for the usercommenting "men_id" and another field for the user being commented on commented_men_id. Well I save it in a comment table and to pull it I make a while I make a select to get the comment of men_id while getting the comment I do another while loop inside the while loop to get the user name and id to return it in the comment. Now the next step is to let other user to comment on top of the comment that is already there. I was wondering if I have to make another table or just create another table to get the comments on another comments. I was also wondering in terms of the php script will I have to create another while loop inside the second while loop to pull the subcomments?
So far I have the next structure
$sql1 = "SELECT id, mem_id, commented_id, comment
FROM comments
WHERE commented_id = '$id'";
while($row=msql_fetch_array($sql)) {
$id_coment = $row['id'];
$mem_id = $row['mem_id'];
$comment = $row['comment'];
$sql_member_data = msql_query("SELECT id, member_name FROM users WHERE id ='$id_coment'");
while($row2=msql_fetchj_array($sql_member_data)) {
$user_id =$row2['id'];
$user_name =$row2['member_name'];
echo '<div>'.$user_name.'</div>';
echo '<div>'.$comment.'</div>';
}
}
I advise might not be the best code but it is posting the comment, Now how can I get a comment within the comment generated by this script.
Thank you guys.
If you truly want a something like Facebook's commenting system, you are going to have to do a lot more than that. I made my own little system and it's nicely styled with some really awesome jQuery effects.
Here's what you are going to need
Section to get all your comments (which you have -- check for syntax errors)
Form and script to post your comments
And you will probally need to use jQuery and AJAX for the commenting and some more jQuery to auto-refresh like facebook does.
That's my take on it. No one else hate on me for this, just trying to give some input on it.
<?php
// Connect to database here
// Search and start loop to get all comments
$sql_comments = mysql_query("SELECT * FROM comments WHERE type='main'");
while($rows_comment=mysql_fetch_array($sql_comments)){
// Get comment information
$main_comment_id = "".$rows_comment['id']."";
$main_comment_mem_id = "".$rows_comment['mem_id']."";
$main_commented_id = "".$rows_comment['commented_id']."";
$main_comment = "".$rows_comment['comment']."";
// Get user information
$sql_member_data = msql_query("SELECT * FROM users WHERE id ='$main_comment_mem_id'");
while($row2=msql_fetchj_array($sql_member_data)) {
$user_id = "".$row2['id']."";
$user_name = "".$row2['member_name']."";
}
// Display comment
echo "<b>$user_name</b><br>$main_comment";
// Search for any sub-comments
$sql_subcomments = "SELECT * FROM comments WHERE sub_commented_id='$main_comment_id' AND type='sub'";
while($row_subcomment=msql_fetchj_array($sql_subcomments)) {
// Get sub comment information
$subcomment_id = "".$row_subcomment['id']."";
$sucomment_mem_id = "".$row_subcomment['mem_id']."";
$subcomment_comment = "".$row_subcomment['comment']."";
// Get sub commenter information
$sql_member_data_sub = msql_query("SELECT * FROM users WHERE id ='$subcomment_mem_id'");
while($row2_sub=msql_fetchj_array($sql_member_data_sub)) {
$user_id_sub = "".$row2_sub['id']."";
$user_name_sub = "".$row2_sub['member_name']."";
}
// Echo sub comment
echo "<div style='margin-left: 20px;'><b>$user_name_sub</b><br>$subcomment_comment</div>";
}
}
?>

Variable out of scope when entering a while loop in php

I have a problem when trying to populate an array in php. It seems that once I enter a while loop with a mysql_fetch_assoc method I cannot populate my array. I've included the code below.
$params = $_REQUEST['params'];
$arr["status"]="ok";
$projects=array();
$files=array();
$titles=array();
$query = 'SELECT p.id as pid, f.fname as name, f.title FROM proj p INNER JOIN pic f ON f.projid=p.id WHERE p.catid=\'' . $params['category'] . '\' ORDER BY p.ordr, f.ordr';
require("../php/connect.php");
//select all projects from chosen category and pics from selected projects
$proj_result = mysql_query($query) or die ("Select failed");
//populate from rows
while($row = mysql_fetch_assoc($proj_result)){
$projects[]=$row["pid"];
$files[]=$row["name"];
$titles[]=$row["title"];
}
$arr["projects"]=$projects;
$arr["files"]=$files;
$arr["titles"]=$titles;
echo json_encode($arr);
The result: {"status":"ok","projects":[],"files":[],"titles":[]}
Thank You.
A while loop doesn't create a new scope, as you can see here: http://codepad.org/H1U3wXZD
About the code itself, here's a few suggestions:
0) I would consider having a database abstraction layer (PDO would be good enough).
1) Learn how to use JOIN's. It looks like you could fetch all the necessary information with a single query, something like:
SELECT p.id, p.proj, c.id, c.fname, c.title
FROM proj p
INNER JOIN pic c ON c.projid=p.id
WHERE catid='<your category>'
ORDER BY p.ordr, c.ordr
2) You should separate the code that gets data from the db from the code that constructs the HTML (?). Perhaps you could put that in another method. Something like:
if ($cmd == 'catSelect') {
$data = getData($params['category']);
foreach ($data as $value) {
// process data here
}
}
3) I take it you are using the generated JSON to send it via AJAX to a client. In that case, I would totally cut the fat (eg: generated markup) and send only essentials (picture id, title, fname and whatever else is essential) and generate the code on the client side. This will make your page load faster and save you and your visitors bandwidth.
my jquery/ajax client side script was not sending in category properly and therefore was no selecting any rows.
The above code will work.
Within the loop try something like this :
while($row = mysql_fetch_assoc($proj_result)){
$projects[]=$row["pid"];
$files[]=$row["name"];
$titles[]=$row["title"];
echo $row["pid"]." -- ".$row["name"]." -- ".$row["title"]."\n";
}
Do you get anything? Once you have tried it we will take it from there. My guess is that you aren't getting any data from MySQL.

Categories