I do sampling from a DB. The print mysql_num_rows($res); command print mysql_num_rows($res); says that the answer is 3 lines - as it should be. But in json only the very first one is output. What am I doing wrong?

 $query = "SELECT * FROM dialog_".$_POST['login']."_".$_POST['who'].""; $res = mysql_query($query); print mysql_num_rows($res); while($row = mysql_fetch_array($res)) { $dialogs["id"] = $row['id']; $dialogs["from_login"] = $row['from_login']; $dialogs["message_enc_from_key"] = $row['message_enc_from_key']; $dialogs["who_login"] = $row['who_login']; $dialogs["message_enc_who_key"] = $row['message_enc_who_key']; $dialogs["date_time"] = $row['date_time']; } echo json_encode($dialogs); 
  • one
    Only the very first one is output - the latest one should be displayed in your code - splash58

2 answers 2

Every time you rewrite the same array - the same keys

  $query = "SELECT * FROM dialog_".$_POST['login']."_".$_POST['who'].""; $res = mysql_query($query); print mysql_num_rows($res); while($row = mysql_fetch_array($res)) { $dialog = array(); $dialog["id"] = $row['id']; $dialog["from_login"] = $row['from_login']; $dialog["message_enc_from_key"] = $row['message_enc_from_key']; $dialog["who_login"] = $row['who_login']; $dialog["message_enc_who_key"] = $row['message_enc_who_key']; $dialog["date_time"] = $row['date_time']; $dialogs[] = $dialog; } echo json_encode($dialogs); 

    The variable $dialogs , which is assigned only one set at each iteration.
    Take out the creation of a variable outside the loop, create another object in the loop and add it to the total result.

     $query = "SELECT * FROM dialog_".$_POST['login']."_".$_POST['who'].""; $res = mysql_query($query); $dialogs = []; // Создание переменной print mysql_num_rows($res); while($row = mysql_fetch_array($res)) { $tmp = []; // Временная переменная для текущей итерации $tmp["id"] = $row['id']; $tmp["from_login"] = $row['from_login']; $tmp["message_enc_from_key"] = $row['message_enc_from_key']; $tmp["who_login"] = $row['who_login']; $tmp["message_enc_who_key"] = $row['message_enc_who_key']; $tmp["date_time"] = $row['date_time']; $dialogs[] = $tmp; // Заполненную переменную добавляем в общий результат } echo json_encode($dialogs); 
    • @ Alexey Shimansky, made a replacement in Sublime Text , apparently buggy, fixed. - user207618 7:58 pm