简体   繁体   中英

How to send data from mysql in php to javascript array

php:

$servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "mydb";

                $conn = new mysqli($servername, $username, $password, $dbname);
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                        } 
$sql = "SELECT * from inventory_list";
$result=$conn->query($sql);
$row=array();
if ($result->num_rows > 0) {
    // output data of each row
while($row=$result->fetch_assoc())

    {    printf("NAME: %s ID: %s",$row['name'],$row['serialno']);



    }


} else {
    echo "0 results";
}
$conn->close();
}

That was the php part of my code. so i need to save all the rows retrieved from mysql to a javascript global array? How can i do that ?

As others have suggested, you can use JSON. If you're looking for a place to start, you can take a look at php's json_encode() http://php.net/manual/en/function.json-encode.php

You may need to set the correct headers too: header('Content-Type: application/json');

try this, you need a JQuery libraries.

JQuery:

$.ajax({
   url: 'your_php_filename',
   type: 'POST',
   data: {},
   success:function(result) {
      console.log(result)//to check the value of result in array form
   }
})

PHP:

<?php
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "mydb";

  $conn = new mysqli($servername, $username, $password, $dbname);
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  } 
  $sql = "SELECT * from inventory_list";
  $result = $conn->query($sql);
  $row = [];
  if ($result->num_rows > 0) {
    // output data of each row
    while($row=$result->fetch_assoc()) {    
       $row = "NAME: ".$row['name']."ID: ".$row['serialno'];
    }
  } else {
     echo "0 results";
  }
  $conn->close();
}
?>

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