Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have created a table(test) in database. now i have fetched array in php like this.

 $sql="SELECT * FROM test;";
  $result=mysqli_query($con,$sql) or die("invalid query ".mysqli_error($con));
  while($row=mysqli_fetch_array($result))
  {
    echo $row['name'];
  }

now i want to pass this array into javascript array.

var images=["$row[0]","$row[1]","$row[2]"];// Is that coreect way to pass php array into js array?

if not what is correct way to pass php array to javascript array.

share|improve this question
2  
What makes you think that it's the wrong way? Do you get an error? – Till Helge Mar 20 at 7:41

4 Answers

up vote 0 down vote accepted
<?php
$mysqli = new mysqli("localhost", "username", "password", "database_name");

$query = "SELECT * FROM test;";
$result = $mysqli->query($query);

while($row = $result->fetch_array())
{
    $rows[] = $row;
}
?>

<script>
    var images = [<?=implode(',', $rows);?>];
</script>
share|improve this answer
$sql="SELECT * FROM test;";
$result=mysqli_query($con,$sql) or die("invalid query ".mysqli_error($con));
print 'var images=[';
$tmp = array();
while($row=mysqli_fetch_array($result))
{
   $tmp[] = '"'.$row['name'].'"';
}
print implode(',', $tmp);
print '];';
share|improve this answer
But what about working with JSON? php.net/manual/en/function.json-encode.php – Mohammad Ali Akbari Mar 20 at 7:47

this way:

var images=["<?php echo $row[0]; ?>", "<?php echo $row[1]; ?>" ... and so on]
share|improve this answer

You will need to echo your variables in the javascript, something like:

<?php
     $sql="SELECT * FROM test;";
     $result=mysqli_query($con,$sql) or die("invalid query ".mysqli_error($con));
     $counter = 0;
?>

<script>
var images=new Array();
<?php
    while($row=mysqli_fetch_array($result))
    {
         echo 'images['.$counter.']="'.$row['name'].'";'
         $counter++;
    }
?>
</script>

Use a counter to keep track of the position where you want to add the new item.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.