Hi, I have created real time script for my website. I wanted to ask u is it good or bad script? Here is my script:

My php page:servr.php

<?php
set_time_limit(0);
$con = mysqli_connect('localhost','root','') or die ("Could not connect to the Database");
mysqli_select_db($con,"msg") or die("Cannot find the database");
$last_id=null;

while(1) {
    $last_ajax_call = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : null;
    $date = new DateTime();
    clearstatcache();
    $last_change_in_data_file = $date->getTimestamp();
    $last_change_in_data_file;
    if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {
        $lastid=mysqli_query($con,"SELECT * FROM massg ORDER BY id DESC LIMIT 1") or die("no work");
        while($row=mysqli_fetch_assoc($lastid))
        {
            $current_last_id=$row['id'];
        }

        if($current_last_id > $last_id && $current_last_id !=$last_id){
            $msgs=mysqli_query($con, "SELECT * FROM massg WHERE id=$current_last_id") or die(mysqli_error($con));

            while($row=mysqli_fetch_assoc($msgs)){
                $messg=$row['messg'];
                $reciver_id=$row['reciver'];
                $sender_id=$row['sender'];
            }

            $result = array(
            'data_from_file' => $messg,
            'timestamp' => $last_change_in_data_file,
            'msg_id'=>$current_last_id,
            'reciver_id'=>$reciver_id,
            'sender_id'=>$sender_id
            );
            $json = json_encode($result);
            echo $json; 
            $last_id=$current_last_id;
        }
        //break;
    } else {
        sleep(1);
        continue;
    }

}

and this is test.php page

<div id="buffers"></div>
<script>
var timestamp=null;
var msg_lst_id = null;
var msg_crnt_id = null;
function waitForMsg(){
$.ajax({
        type: "GET",
        url: "servr.php",
        async: true,
        success: function(data){
            var json=eval('('+data+ ')');
            msg_crnt_id=json['msg_id'];
            if(msg_crnt_id != msg_lst_id){

                $("#windows").append(json['data_from_file']);

                msg_lst_id =msg_crnt_id;
            }
            timestamp =json["timestamp"];

            setTimeout("waitForMsg()",1500);
        },
        error: function(XMLHttpRequest,textStatus,errorThrown) {
            setTimeout("waitForMsg()",15000);
        }
      });
    }

      waitForMsg();
</script>

but there is a little problem...

Member Avatar for diafol

I have no idea what you're trying to achieve. Any chance you could write a paragraph or two stating what you're trying to acheive?

and

but there is a little problem...

does not help in any way, shape or form. If there's a problem, tell us what it is for goodness sake!

i have write script for real time webpage. i wanted to ask that how is it ? is there any bad use of php or ajax ?

Member Avatar for diafol

Will you explain what you're trying to do? Without context, it's impossible to tell you the best way to do something. Why won't you explain?

I told i m created that script for real time chat. To send msg to users to users..(client to client whatever).. and i am just asking did i use bad php language ?

Hello phoenix254 the few line of code that you presented have nothing to do with what you are wrote that you are trying to develop , a real time chat system. More over it is' just an AJAX call, client side and just a bare GET in server side.

You ask if that few lines of code are “bad PHP” , I could make some comments about those , but would that help you ? Would that motivate you read and test more? (e.g. you get the results of a statement with SQL “LIMIT 0,1” with while , why ? Will not be maximum 1 ? ).

Next example (since you asked) what would be different if you didn't had this code ?

else 
{
    sleep(1);
    continue;
}

Is there any reason for putting PHP to sleep ? And why do you use the continue ? (You don't have any code after it).

@see http://php.net/manual/en/control-structures.continue.php

Why is this part inside in a while(1) -> while(true) block ?

I just realized what maybe you think you are doing (it helped me that you mentioned that you think you are creating a chat application).

In my point of view you must take a decision. If you just want a chat room for your site as a user you can search and find something ready made to apply it in your site.

If you want to create one (or even understand what you are doing) , it is a whole different story that you should begin by learning the basics of programming. First understand what is internet what are protocols what are programming languages , what is PHP (in this case), JavaScript. Not to master those , but to understand at first step what are.

The second step is to start programming. That doesn't mean just to copy paste. Even if you do so you should take the time to understand what this code that you copy paste does.

After that you can start to understand what are WebSockets or other techniques like Node.js. I am pro WebSockets with PHP , there are some frameworks already that empower the use of WebSockets with PHP , you can Google it. I participate a team that we will release this year our own framework that make (among others) the use of WebSockets with PHP really easier and safer , but even that will refer to programmers and not final users , none will be able to use it if he doesn't understand what is “while” “break” or “continue” in PHP.

So if you want to develop your own chat system , start learning else search to find something ready made.

is ur framework for chat ? client to client ?

It surprise me that from all that I wrote this is what you kept. Yes , it has a WebSocket layer (we hadn't published it yet) , but as I mentioned there are other PHP frameworks out there with WebSocket support , Google it . But read what I wrote because you can't write anything if you don't know even the basics.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.