J
J
Junior2018-09-18 14:53:33
PHP
Junior, 2018-09-18 14:53:33

How to overcome the error?

There is a code:

main.php

<?php
if(isset($_POST['getNewId'])){
  loadNewPosts();
}
function loadNewPosts(){
  include 'db-config.php';
  $new = $_POST['getNewId'];
  $newId = mysql_fetch_array(mysql_query("SELECT * FROM posts ORDER BY id DESC"));
  if($newId>$new){
  if($new==0){
    $post1 = mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 10");
  }else{
    $post1 = mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT $new , $newId");
  }
  $post = mysql_fetch_array($post1);
    do{
      print(json_encode(array('post'=>'<div class="area"><div class="pad-5">'.$post['content'].'</div></div>','id'=>$newId)));
    }while($post=mysql_fetch_array($post1));
  }else{
    print(json_encode(array('id'=>$new)));
  }
}


main.js
setInterval(loadNewPosts,5000);
var newId = 0;
function loadNewPosts(){
$.ajax({
  url:SiteURL+'assets/includes/functions/main.php',
  type:'POST',
  data:{'getNewId':newId},
  success:function(text){
    text = JSON.parse(text);
    if(text!=''){
    $('.postContainer').prepend(text.post);
    newId = text.id;
  }else{
    alert(text);
  }
  }
});
}


After executing the code, an error is entered in the JavaScript console:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse()


And here is the json response from php:
<!--error--><br />
<b>Warning</b>:  mysql_fetch_array() expects parameter 1 to be resource, boolean given in <b>Z:\home\mind\www\assets\includes\functions\main.php</b> on line <b>17</b><br />
<script language=JavaScript src='/denwer/errors/phperror_js.php'></script>{"post":"<div class=\"area\"><div class=\"pad-5\"><\/div><\/div>","id":{"0":"48","id":"48","1":"8","poster_id":"8","2":"\u041a\u0430\u043a \u0443 \u0432\u0430\u0441 \u0434\u0435\u043b\u0430?","content":"\u041a\u0430\u043a \u0443 \u0432\u0430\u0441 \u0434\u0435\u043b\u0430?"}}<!--error--><br />
<b>Warning</b>:  mysql_fetch_array() expects parameter 1 to be resource, boolean given in <b>Z:\home\mind\www\assets\includes\functions\main.php</b> on line <b>20</b><br />
<script language=JavaScript src='/denwer/errors/phperror_js.php'></script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Yumashev, 2018-09-24
@skazkin

1. Don't use deprecated mysql_* functions.
php.net/mysqli_fetch_array
2. You do not have a connection to the database - not a resource is passed to the function, but false. First check if you have a connection to the database. Did the correct response come back after mysqli_query.
3. Don't forget to escape incoming data - at least mysqli_real_escape_string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question