chatAJAX.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. define("CHATDB", "chat.db");
  3. if (!file_exists(CHATDB)) {
  4. try{
  5. $db = new PDO('sqlite:'.CHATDB);
  6. $sql ="
  7. CREATE TABLE IF NOT EXISTS MESSAGES
  8. (ID INTEGER PRIMARY KEY AUTOINCREMENT,
  9. USER TEXT NOT NULL,
  10. EMAIL TEXT NOT NULL,
  11. MESSAGE TEXT NOT NULL,
  12. TIME TIMESTAMP NOT NULL DEFAULT((julianday('now') - 2440587.5)*86400.0))";
  13. $ret = $db->exec($sql);
  14. sleep(0.5);
  15. $ret = $db->exec('PRAGMA journal_mode = wal;');
  16. sleep(0.5);
  17. header("Refresh:0");
  18. }
  19. catch(PDOException $e){
  20. die('Failed to execute query:'. $e->getMessage());
  21. }
  22. $db=null;
  23. }elseif(file_exists(CHATDB)) {
  24. try{
  25. $db = new PDO('sqlite:'.CHATDB);
  26. }
  27. catch(PDOException $e){
  28. die('Failed to connect:'. $e->getMessage());
  29. }
  30. }
  31. //check to see if the ajax call was to update db
  32. if (isset($_POST['text'])){
  33. $msg=$_POST['text'];
  34. $us=$_POST['user'];
  35. $email=$_POST['email'];
  36. $sql ="INSERT INTO MESSAGES (USER,MESSAGE,EMAIL) VALUES(?, ?, ?)";
  37. try{
  38. $ret = $db->prepare($sql);
  39. $ret->execute([$us,$msg, $email]);
  40. }
  41. catch(PDOException $e){
  42. console.log('Failed to update db:'. $e->getMessage());
  43. }
  44. }else{
  45. //the script will run for 20 seconds after the initial ajax call
  46. $time=time()+20;
  47. while(time()<$time){
  48. if ($_POST['time']){
  49. $prevtime=$_POST['time'];
  50. }
  51. else {
  52. $prevtime=0;
  53. }
  54. //query to see if there are new messages
  55. $sql ="SELECT TIME,USER,MESSAGE,EMAIL FROM MESSAGES WHERE TIME>? ORDER BY TIME ASC";
  56. try{
  57. $ret = $db->prepare($sql);
  58. $ret->execute([$prevtime]);
  59. $resarr = $ret->fetchAll(PDO::FETCH_ASSOC);
  60. //if there are no new messages in the db, sleep for half a second and then run loop again
  61. if (!$resarr)
  62. sleep(0.5);
  63. else{
  64. echo json_encode($resarr);
  65. break;
  66. }
  67. }
  68. catch(PDOException $e){
  69. console.log('Failed to get messages:'. $e->getMessage());
  70. }
  71. }
  72. }
  73. $db=null;
  74. ?>