Reputation: 101
What I'm trying to do is a User -> Admin || Admin -> User) chat system. What I've come up with so far looks really messed up, I tried JOIN
on the select via SQLfiddle and it didn't work out so good.
Hopefully someone has a better idea and knows how to solve this problem.
My live chat PHP code -> http://pastebin.com/6z9ajCMW
And for my database structure for the live_chat
and live_chat_admin
it's here -> http://sqlfiddle.com/#!2/ae70ec/26
And to get a basic idea of what I'm trying to make.
Upvotes: 0
Views: 281
Reputation: 101
Solved my problem with a bit of help from @Eddy Ella.
I first of deleted live_chat_admin
and moved receiver to live_chat
instead.
And then I used CASE WHEN for switching between id's from user to admin.
Result, exactly as I wanted it.
PHP: http://pastebin.com/GXJEK6u4
SQL: http://sqlfiddle.com/#!2/7081b/5
Result:
Upvotes: 0
Reputation: 11310
Here you go
You just need to align right and left accordingly to the admin and the user that you have in your form as i have like in the below code
i.e.,
echo '<div align="right">';
and ending with
echo '</div>';
Code :
<?php
echo '<div class="live_chat">';
$user = 'root';
$pass = '';
// admin chat
$conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT * FROM live_chat_admin WHERE receiver = :user_id");
$sth->bindValue(':user_id', '2', PDO::PARAM_INT);
$sth->execute();
foreach ($sth as $row) {
// Test message #1
echo '<div align="right">';
echo '<div class="admin_date">'.date('M j <b\\r/> H:i', strtotime($row['message_date'])).'</div>';
echo '<div class="admin_bubble">'.$row['message'].'</div>';
echo '<br /><br />';
echo '</div>';
}
$conn = NULL;
// user chat
#$conn = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
#$conn = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8', root);
$user = 'root';
$pass = '';
$conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT * FROM live_chat WHERE user_id = :user_id");
$sth->bindValue(':user_id', '2', PDO::PARAM_INT);
$sth->execute();
foreach ($sth as $row) {
// Test message #1
echo '<div class="user_date">'.date('M j <b\\r/> H:i', strtotime($row['message_date'])).'</div>';
echo '<div class="user_bubble">'.$row['message'].'</div>';
echo '<br /><br />';
}
$conn = NULL;
echo '</div>';
?>
So your screen will be as you expected
Upvotes: 0
Reputation: 13259
Maybe you should try to create a unique id for each chat so it easier for you to retrive it. Tables will be similar to something like this.
Everytime a user starts a new chat, a new row is inserted in chat_unique. This will prevent other users to join a chat.
However, your page will reload everytime someone sends a new message. The best way would be to use Ajax.
Upvotes: 1