T
T
Tweak_stack2015-10-31 09:41:37
PHP
Tweak_stack, 2015-10-31 09:41:37

Database -> php -> JSON -> JS -> Object JS/ HOW?

<?php 

    // определяем начальные данные
    $db_host = 'localhost';
    $db_name = 'index';
    $db_username = 'root';
    #$db_password = '';
    $db_table_to_show = 'people';

    // соединяемся с сервером базы данных
    $connect_to_db = mysql_connect($db_host, $db_username, $db_password)
    or die("Could not connect: " . mysql_error());

    // подключаемся к базе данных
    mysql_select_db($db_name, $connect_to_db)
    or die("Could not select DB: " . mysql_error());
    
    // выбираем все значения из таблицы "people"
    $qr_result = mysql_query("select * from " . $db_table_to_show)
    or die(mysql_error()); 
  
   // выводим все данные клиентов из таблицы MySQL 
  while($data[] = mysql_fetch_assoc($qr_result)){ 
      $js_database = json_encode($data);
     
  }

  
    // закрываем соединение с сервером  базы данных
    mysql_close($connect_to_db);


?>

<script>

    //преобразуем данные полученые из бызы данных преобразованные в формат JSON в объект JS
    var jsonObject = JSON.parse('<?php echo $js_database ?>');
    console.log(data);    
    
    
</script>

1. In this part of the code... How to return only the last value of the array (or add the values ​​of all received arrays from the database to transfer the last array from the database or the sum of all arrays to the $data array)?
// output all customer data from MySQL table
while($data[] = mysql_fetch_assoc($qr_result)){ 
      $js_database = json_encode($data);
  }

2. how to parse the resulting array into js type objects:
obj= {
 propery: "",
 property:''
}
???

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arman, 2015-10-31
@Arik

And if:

<?php
for($data = []; $assoc = mysql_fetch_assoc($qr_result); $data[] = $assoc);
?>
...
var jsonObject = <?php echo json_encode ($data) ?>;
console.log(jsonObject);

So we return everything that the request returned.
And for the last record, it's probably better to make a request so that it sorts and returns the first last record (order by id desc)? limit 1

T
Tweak_stack, 2015-10-31
@Tweak_stack

Thank you. php returned.
in JS returned JSON with the last array.
JSON -> JS returns an array of 3 objects in this format:

0: Object
    first_name: "Josh"
    __proto__: object
1: Object
    first_name: "Josh"
    __proto__: object
2: Object
    first_name: "Josh"
    __proto__: object

etc. how to return object property 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question