0

Actually i m trying to store the result of mysql as array(javascript). so i tried like this.. its working perfectly when i store integer values in Database. but if i store varchar variable in database i m not getting any values. plz someone help me.

var tab_no = [<?PHP  $qry4 = mysql_query("SELECT table_no FROM table_info");
                     $i4 = mysql_num_rows($qry4);

                    while($res4 = mysql_fetch_array($qry4))
                        {
                            $i4--;
                            echo $res4['table_no']; 
                            if($i4!="0"){
                            echo ",";}
                        }
            ?>];

Database Table

 _________________
| id | table_no   |
 ------------------
| 1  |     1A     |
| 2  |     3B     |
| 3  |     4D     |
 ------------------        

now i want is store table_no all values as array in javascript like this

  var  tab_no =  [ 1A,3B,4D ];
user3419304
  • 249
  • 2
  • 4
  • 20
  • 1
    Fetch query results and convert it using `json_encode`. – barell Jun 10 '14 at 20:22
  • 1
    The generated output creates syntax errors as `1A`, etc. aren't valid identifiers and aren't quoted to be treated as strings. See [How to access PHP variables in JavaScript or jQuery rather than ](http://stackoverflow.com/questions/1808108/how-to-access-php-variables-in-javascript-or-jquery-rather-than-php-echo-vari) for a safer way to output values between languages. – Jonathan Lonowski Jun 10 '14 at 20:24

2 Answers2

2

You need to encapsulate the values in " because it's a string.

Example:

  var  tab_no =  [ "1A","3B","4D" ];

(in short, one solutions is to change your PHP like this)

echo $res4['table_no']; 

to

echo '"'.$res4['table_no'].'"'; 

The better solution is to use json_encode (handles problems with special chars and the like, but since it looks like you're just starting with web programming I hope this answer gives you a better understanding of both of the languages).

gernberg
  • 2,587
  • 17
  • 21
2

Put the results in a PHP array, and then use json_encode when you assign it to a JS array:

<?php
$tab_no = array();
while($res4 = mysql_fetch_array($qry4)) {
    $tab_no[] = $res4['table_no'];
}
?>
var tab_no = <?php echo json_encode($tab_no); ?>;
Barmar
  • 741,623
  • 53
  • 500
  • 612