简体   繁体   中英

how to use the values from mysql database from php in javascript function

In php, i have used an sql query to fetch the data like :-

$sql="Select * from xyz";

$result = $conn->query($sql);
    // output data of each row
    while($row = $result->fetch_assoc()) {
       error_log( "id" . $row["id"]);

    }

Now i want to use all the values attained using $row["id"] in javascipt function and use it in a variable (var j , lets say). How to do this?

Try something like this:

<?php

$sql="Select * from xyz";
$errorsData = array();
$result = $conn->query($sql);
    // output data of each row
    while($row = $result->fetch_assoc()) {
       error_log( "id" . $row["id"]);
       $errorData[]=$row["id"]
    }
$errorJson = json_encode($errorsData);

?>

<script>

   var errorJson = <?= $errorJson ?> ;

   console.log(errorJson);

<script>

Good luck!!

in jquery I would have done like this,

php

$sql="Select * from xyz";
$arr_json = array();
$result = $conn->query($sql);
    // output data of each row
    while($row = $result->fetch_assoc()) {
       error_log( "id" . $row["id"]);
       $arr_json[] = $row['id'];
    }

echo json_encode($arr_json);

jquery

$.get(
  <THAT CALLED URL>,
  function(ret_data){
     console.log(ret_data);
     /* you can use the ret_data as ret_data.<INDEX> */
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM