0

here is php code to connect to database

<?php    
$host = "localhost";
$user = "admin";
$password = "";
$dbname = "test";

$con = new mysqli($host, $user, $password, $dbname) or die ('Could not connect to the database server' . mysqli_connect_error());
?>

And here is where i want to insert database data into JavaScript array

<script type="text/javascript">
var array = [<?php
$sql = mysqli_query($conn, "SELECT name FROM users");
while ($row = $sql->fetch_assoc()) {
    unset($name);
    $name = $row['name'];
    echo '<p>'.$name.'</p>';
}
?>];
document.write(array);
</script>
Dharman
  • 30,962
  • 25
  • 85
  • 135

4 Answers4

1

First save the data to another array and use JSON type to pass it to JS

try this code,

<?php
while ($row = $sql->fetch_assoc()) {
    $array2js[] = $row['name'];
}
?>

<script type="text/javascript">
    var array = JSON.parse("<?=json_encode($array2js)?>");
    console.log(array);
</script>

good day~

Java Mon
  • 51
  • 4
1

You should use json_encode():

json_encode — Returns the JSON representation of a value

<?php
$sql = mysqli_query($conn, "SELECT name FROM users");

$json = array();
while ($row = $sql->fetch_assoc()) {
    $json[] = $row['name'];
}
?>

Then in your javascript

<script type="text/javascript">
    var array = <?= json_encode($json) ?>;
</script>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

Your array in the JS code is displaying [0] => '<p>name</p>'. You are not building the array correctly, so you need to remove the p element, and make it space separated.


EDIT

As suggested, [json_encode][1] would be a better solution, look at this example:

<?php
// get results from db
$name = $row['name'];
$age = $row['age'];
$phone = $row['phone'];
// create array
$array = array($name, $age, $phone);
// encode array
$json = json_encode($array);
?>

<script>
    var array = <?php echo $json; ?>;
    document.write(array);
</script>

This will output:

name,age,phone
Community
  • 1
  • 1
Sam
  • 2,856
  • 3
  • 18
  • 29
0

It is common to use Ajax and JSON response to populate javascript variable with DB data. But please try following

<script type="text/javascript">
      var array = [
      <?php
      $result = array();
      $sql = mysqli_query($conn, "SELECT name FROM users");
      while ($row = $sql->fetch_assoc()) {
            unset($name);
            $name = $row['name'];
            $result[] = "'$name'";
      }
      echo impode(",", $result);
      ?>
      ];
      for(var i =0; i < array.length; i++)
      {
        document.write("<p>" + array[i] + "</p>");
      }

</script>
songxunzhao
  • 3,149
  • 1
  • 11
  • 13