Message history with PHP, MYSQL and AJAX

2

I'm creating a kind of Imbox, a chat so to speak but with the difference is that I do not want it to be a general chat, where all users write and it appears to all, so I made the system reserved between two users similar to facebook, it works when they are chatting in real time, one appears below the other, and I put them in a table, and I put them in some fields of the table so that the system knows that they are the ones who speak and not other users , this works correctly, everyone has their own chat and no other user can see what they are chatting, what I am looking for, the problem is in the History, when I reload the page, the history appears but they are sorted by lists, for example :

Pedro chat with Juan: in real time, Write Pedro and Juan and you see the conversation one below the other, like Facebook, but when I reload the page, where it should show the history of what they talked about, all the messages appear of Juan and all of Pedro's messages, but all together, that is, if Pedro sent 50 messages, his 50 messages come out first and then those of Juan, when I want to show one below the other.

introducir el código aquí

      //CHAT USER 1
public function dataChat($data_from, $data_to, $from_name, $to_name, $name_session, $foto){      
    try{
    $stm = "SELECT
            *
            FROM
            chat
            WHERE
            id_from = :id_self
            AND
            from_name = :from
            AND
            to_name = :to_name
            AND
            id_to = :id_to                           
            ";
     $data = $this->BBDD->prepare($stm);
     $data->execute(array(
         ":id_self"=>  htmlspecialchars(addslashes($data_from)),
         ":from"=>  htmlspecialchars(addslashes($from_name)),
         ":to_name"=>  htmlspecialchars(addslashes($to_name)),
         ":id_to"=>  htmlspecialchars(addslashes($data_to))
     ));
     $count = $data->rowCount();
     $performance = $data->fetchAll(PDO::FETCH_OBJ);
    foreach($performance as $value){
        if($count!=0){
            $_SESSION["chat_data"] = $this->chat_with($data_to);
            if($name_session === $value->from_name && $_SESSION["chat_data"] && $value->to_name === $to_name){
            echo '<div class="row">';
                     echo   '<div class="col-lg-12">';
                     echo       '<div class="media">';
                     echo           '<a class="pull-left" href="#">';
                     echo               '<img class="media-object img-circle" width="50px" src='."avatar/$foto".' alt="">';
                                echo '</a>';
                                echo '<div class="media-body">';
                                echo    '<h4 class="media-heading">'.$value->from_name;
                                echo       ' <span class="small pull-right">'.$value->time.'</span>';
                                echo    '</h4>';
                                echo    $value->message;
                                echo  '</div>';
                                echo '</div>';
                        echo '</div>';
                    echo '</div>';
                    echo '<hr>';

            }else{
                header("location:dashboard.php");
            }

        }

    }

     //print_r($performance);        
    }catch(PDOException $ex){
        die("Error al leer este chat" . $ex->getLine() . PHP_EOL . $ex->getCode() . " " . PHP_EOL. $ex->getMessage());
    }finally{
       // $this->BBDD = NULL;
    } 

}
//VERIFICAR CONVERSACION
private function chat_with($id_to){        
    try{
          $stm = "SELECT
                  *
                  FROM
                  imbox
                  WHERE
                  id = :name
                  ";
          $data_session = $this->BBDD->prepare($stm);
          $data_session->execute(array(":name"=>  htmlspecialchars(addslashes($id_to))));
          $count = $data_session->rowCount();
          if($count!=0){
              return TRUE;
          }else{
              return FALSE;
          }
          $this->BBDD = NULL;
    } catch (Exception $ex) {
        die("Error al leer este chat" . $ex->getLine() . PHP_EOL . $ex->getCode() . " " . PHP_EOL. $ex->getMessage());
    }                         
}
//CHAT USER2 // Recibe la respuesta del CHAT 1
public function imbox($from_name, $id_data, $to_name){
    try{
        $stm = "SELECT
                *
                FROM
                imbox
                WHERE
                nick_usuario = :nick
                AND
                id = :id_usuario
                AND
                de_name = :to
                ";
        $data = $this->BBDD->prepare($stm);
        $data->execute(array(
            ":nick"=>  htmlspecialchars(addslashes($to_name)),
            ":id_usuario"=>  htmlspecialchars(addslashes($id_data)),
            ":to"=>  htmlspecialchars(addslashes($from_name))
        ));

        $data_table = $data->rowCount();
        //print_r($data_table);
        if($data_table!=0){
            $avatar = "SELECT
                       foto
                       FROM
                       datos_profesionales
                       WHERE
                       nick_usuario = ?
                       ";
         $data_from = $this->BBDD->prepare($avatar);
         $data_from->execute(array(htmlspecialchars(addslashes($from_name))));
         //$fotoLog = $data_from->rowCount();
         //print_r($fotoLog);
         $fotoLog = $data_from->fetchAll(PDO::FETCH_OBJ);
         foreach($fotoLog as $foto){                                
         } 
         $data_chat = $data->fetchAll(PDO::FETCH_OBJ);
         foreach($data_chat as $data_key){ 
             echo '<div id="chatLastData">';
             echo '<div class="row">';
                     echo   '<div class="col-lg-12">';
                     echo       '<div class="media">';
                     echo           '<a class="pull-left" href="#">';
                     echo               '<img class="media-object img-circle" width="50px" src='."avatar/$foto->foto".' alt="">';
                                echo '</a>';
                                echo '<div class="media-body">';
                                echo    '<h4 class="media-heading">'.$data_key->de_name;
                                echo       ' <span class="small pull-right">'.$data_key->hora.'</span>';
                                echo    '</h4>';
                                echo    $data_key->mailbox;
                                echo  '</div>';
                                echo '</div>';
                        echo '</div>';
                    echo '</div>';
                    echo '</div>';
                    echo '<hr>';
         }
         $this->BDDD = NULL;
        }
        //$this->BBDD = NULL;
    } catch (PDOException $ex) {

        die("Error al leer este chat" . $ex->getLine() . PHP_EOL . $ex->getCode() . " " . PHP_EOL. $ex->getMessage());

<div class="portlet-footer">
                        <form id="chat_message" role="form" action="wp-admin/message.php" method="POST" accept-charset="">
                            <input type="hidden" name="id_from" value="<?php echo $_GET["id_from"] ?>">
                            <input type="hidden" name="name_from" value="<?php echo $_GET["from"] ?>">
                            <input type="hidden" name="id_to" value="<?php echo $data->id ?>">
                            <input type="hidden" name="name_to" value="<?php echo $_GET["to"] ?>">
                            <input type="hidden" name="time" value="<?php echo $date?>">
                            <input type="hidden" name="photo" value="<?php echo $photo->foto ?>">
                            <div class="form-group">
                                <input class="form-control" type="text" name="chat_data" value="" placeholder="Enter message..."></input>
                            </div>
                            <div class="form-group">
                                <button type="submit" class="btn btn-default pull-right">Send</button>
                                <div class="clearfix"></div>
                            </div>
                        </form>
                        <script>
                        jQuery("#chat_message").submit(
                                function(event){                                    
                                    jQuery.ajax({                                     
                                      url: "wp-admin/message.php",
                                      type: "POST",
                                      cache: false,                                     
                                      data: jQuery("#chat_message").serialize(),
                                      success: function(ajaxResponse){
                                          jQuery("#chats").append(ajaxResponse).scrollTop(jQuery("#chats").prop("scrollHeight"));
                                          jQuery("#chat_message")[0].reset();
                                      },
                                      error: function(ajaxResponse){
                                          console.log(ajaxResponse);
                                      }
                                    });
                                   return false;                               
                                });                                                             
                        </script>                     
                    </div>
    
asked by Carlos Estarita 18.02.2017 в 18:33
source

2 answers

2

Try to sort the messages by their date and time of creation, your table should have a column with the date and time of creation of each message:

SELECT * 
  FROM imbox 
 WHERE nick_usuario = :nick
   AND id = :id_usuario
   AND de_name = :to
 ORDER BY mi_columna   --Para ordenarlos

link

    
answered by 19.02.2017 / 03:04
source
0

Boys, the way to solve it was catastrophic but I managed to do it, partly the error was in because to maintain the security that only two people can see what they chat, the information that was put in my chat table, the overturned in another turn that was called imbox, obviously to recover the data I was going to return both tables, the way to solve it was to migrate the two tables in one, and with some judgments to evaluate if they are chatting those two users or not, the way to solve it was this:

 $stm ="SELECT *,
        (
             CASE 
     WHEN id_from = :data_from && id_to = :data_to THEN 'true'
     WHEN from_name = :from && to_name = :to_name THEN 'true'        
     WHEN id_from = :data_from2 && id_to = :data_to2 THEN 'true'
     WHEN from_name = :from2 && to_name = :to_name2 THEN 'true'       
    ELSE 'FALSE'
    END) AS conversation 
    FROM chat  
    ORDER BY hora";   

With the True and the false that it returns, I can manipulate the security of the system

    
answered by 19.02.2017 в 20:06