dongqiulei6805 2017-10-14 11:13
浏览 141
已采纳

将SQL查询的结果从PHP传递给Javascript数组

I am used to update a javaScript variable manually each day this way

<script>
    var data = [
            ['Austria','IBM','8284927','UF93NV', '10'],
            ['Spain','Dell','1098193','MN87QA', '4'],
            ...
          ];
    //rest of my code
<script>

I want to pass the values to this variable from an SQL query result using PHP so that I don't need to type several lines each day. I have created this PHP file where I am connecting to my database and storing the result of the query in an array.

 <?php   
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$ser="*******";
$db="*******"; 
$user="*******"; 
$pass="*******";

$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*******;Database=*******;Port=1456", $user, $pass);

$sth = $dbDB->prepare("SELECT top 2 [Country],[Customer Name],[Purchase Number],[Part Number],[Qty] FROM *******");
$sth->execute();

$result = $sth->fetchAll();

print_r($result);
 ?>  

It's working fine as you see below the result enter image description here

Now I want to pass the values in the variable $result to my variable data inside the javaScript tag using jason_encode. I added the following code in the same PHP file

<script type="text/javascript">
    var data = <?php echo json_encode($result); ?>;
    alert(data.toString());
</script>

But when I added the alert to see the value of my variable data I receive this enter image description here

and my variable should be this way

var data = [
['Austria','Tech Data Service GmbH','3508224010','01HV707', '4'],
['Austria','Tech Data Service GmbH','3508314557','40M7578', '1']
];

Any advises please what am I missing ? Thank you.

  • 写回答

1条回答 默认 最新

  • duanbin4847 2017-10-14 11:58
    关注

    The data is already there in your variable. To check how it your objects look like, you could use alert(JSON.stringify(data)).

    The contents of your data variable won't be arrays in JavaScript as associative arrays in PHP are objects in JSON.

    To get the result you want, the simplest solution would be to use $result = $sth->fetchAll(PDO::FETCH_NUM);.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下