D. Krold
D. Krold

Reputation: 25

Dynamic PHP response

I have an html page with a button on it that triggers an ajax request to a php page. So far so good.

I have a database messages which has the columns "id", "receiver", "sender", "message".

Say I have 2 entrys there both the same receiver and sender. The messages are different.

Now upon button click the messages shall be displayed in seperate paragraphs <p>Message 1</p> and <p>Message 2</p>.

My problem is that I don't know how many messages there will be and the button click should display them all. I have tried it with a while loop but can't get it to work properly. Also how would JQuery handle something like this?

My php so far:

$thuser = $_SESSION['username']; //this user
$sql = "SELECT * FROM messages WHERE receiver = '$thuser'";

if ($result = mysqli_query($link, $sql)) {

  while ($row = $result->fetch_row()) {
  ...
  });

}

If possible I would like an array as the response containg all messages {'message1' = > 'Hello', 'message2' => 'What is up?', message n => 'blah'}

Thanks for any help!

Upvotes: 0

Views: 243

Answers (1)

Hemraj Dubey
Hemraj Dubey

Reputation: 71

Use Array in your case :

$message=array();

$thuser = $_SESSION['username']; //this user
$sql = "SELECT * FROM messages WHERE receiver = '$thuser'";

if ($result = mysqli_query($link, $sql)) {
 $i=1;
  while ($row = $result->fetch_row()) {
   $st='Message'.$i;
  $message[$st]=$row['message'];
   $i++;
  });

}
print_r($message);

Upvotes: 1

Related Questions