0v3k Shi3ld3r 0v3k Shi3ld3r - 5 months ago 21
MySQL Question

Concatenate Avatar to a Chat Message

I would like to concatenate a users avatar to a message they send in a chat system . At the moment I have progressed to the point where I have the image name.jpg for each user showing up in the chat (MEANING: I have an ID for each user to INDEX).

enter image description here

I need to be able now have it so that it display as avatar in the chat with the following code

<?php echo "<img width='100' height='100' src='avatars/".$row2['imagelocation']."' alt='Profile Pic'>"; ?>


I want to display the avatar here wrapped in the span to $new_str which is the message to be sent

<div id="chat_data">

<span style ="color:orange; font-size:10px;"><?php echo "<a href=http://localhost/db/view_member.php?id=".$row['username'].">My Profile </a>"?><span style ="color:o; font-size:24px;"><?php echo " |".$row['username']." says :"; ?></span></span>

**//LINE I WANT TO ADD THE AVATAR TO**
<span style ="color:white; font-size:20px;"><?php echo $new_str ;?></span>

<span style ="float:right; color:brown;" ><?php echo $row['date']; ?></span>

//THIS LINE DISPLAYS THE IMAGE BUT ON ALL LINES IN THE CHAT
<span style ="float:right; color:brown;" ><?php echo $row['imagelocation']; ?></span>


</div>


The 3rd span tag above displays the users avatar but on all messages My query is selecting everything from the table so that all users can see the messages, How can I make my query to show and avatar for each user on each line of a message they send (Im using ID as an INDEX for each user) but I'm stuck trying to display the avatar on each line of a message for that user

If I include a WHERE CLAUSE below to index the ID for the user the chat wont display everything to all other users in the chat.

$query = "SELECT * FROM chat ORDER BY id DESC";
$run = $con->query($query);
while($row = $run->fetch_array()):
$new_str = str_replace($row['msg']);



?>


My TABLE STRUCTURE AVID IS THE USERS ID

enter image description here

Thanks in advance

Answer

I know this is a different way from yours but it still gives the same results and in an easier way.

You can create a function which you can call from anywhere as long as you have the users unique id. Like this:

function get_user($user, $field) {
    // run your db connection here with $con as your db variable, remember we are using `mysqli` and not `mysql`
    $query = mysqli_query ($con, "SELECT $field FROM users_table WHERE id='$user'");
    $sql = mysqli_fetch_array($query);
    $value = $sql[$field];
    return $value;
}

This way you cannot only get the users images but also every value of the user in the users table as long as you have the id, so you can say:

$image = get_user($user_id, 'imagelocation');
$name = get_user($user_id, 'username');

And so on and forth. What I normally do I run this function in an external page which I always include in all my pages.

Hope this helps