-2

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.

1
  • 2
    What makes you think that it's the wrong way? Do you get an error? Commented Mar 20, 2013 at 7:41

4 Answers 4

2
<?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>
1
$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 '];';
0
0

this way:

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.