Question:

Querying a database in ajax using php?

by  |  earlier

0 LIKES UnLike

<code>

<?php

$link = mysql_connect("localhost", "root", "");

mysql_select_db("jive", $link) or die("Problems Selecting DB");

$user = $_SESSION['username'];

$message = "SELECT *

FROM `messages`

WHERE `to` = '$user'

AND `read` = 'no'";

$result = mysql_query("$message", $link) or die("Query Error $message");

$num_rows = mysql_num_rows($result);

print "Inbox ($num_rows)";

</code>

I want to make that happen real time ie not just when the page refreshes - is this possible?

 Tags:

   Report

1 ANSWERS


  1. You&#039;ll need to know a bit of javascript to get this done but it&#039;s fairly easy. You&#039;ll need to use the XMLHttpRequest object (there&#039;s a good tutorial on how to use it on the W3C website: http://www.w3schools.com/Ajax/ajax_examp...

    Basically what you&#039;ll do is execute your PHP file from javascript code (using the XMLHttpRequest method) and you&#039;ll receive whatever&#039;s printed in the PHP file as a string in javascript.

    For example, if your PHP script prints the string &quot;Inbox (1)&quot; then the string you receive in javascript in the &quot;xmlHttp.responseText&quot; variable will also be &quot;Inbox (1)&quot; (don&#039;t worry that&#039;ll all make sense once you&#039;ve read the W3C tutorial!). After you&#039;ve got that string you can simply do something like this:

    document.getElementById(&#039;inboxHeader&#039;)

    .innerHTML = xmlHttp.responseText;

    (should be all on one line but YA cuts long lines off)

    Best of luck!

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.