简体   繁体   中英

How to Store MYSQL column as array

Actually im 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 im 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 ];

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).

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); ?>;

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