dqz13288 2013-01-25 09:51
浏览 35
已采纳

json不能与pdo一起使用,但它适用于mysql_函数

This code works 100% but when I try to use JSON it does not display any data.

The problem is that I am trying to change all my codes to PDO since I was told that mysql_* function's are depreciated.

<?php
$con = new PDO('mysql:host=localhost;dbname=adnan;charset=UTF-8','root','');
$sql= $con->query('select *  from adnan_user');
while($row =$sql->fetch()){
    echo $row['user_id'],"
";
}
?>

Here is the code which I call in json : its also works when I use mysql_ function But with pdo it does not work .

<?php 
$con = new PDO('mysql:host=localhost;dbname=adnan;charset=UTF-8','root','');
$sql= $con->query('select *  from adnan_user');
while($row =$sql->fetch()){
    $name = $row['name'];
    $user= $row['user']; 
}
// The JSON standard MIME header.
header('Content-type: application/json');
$array = array('name'=>$name, 'user'=>$user);
echo  json_encode($array);
?>

The code for json

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script> 
        $(document).ready(function(){
            $.getJSON('json.php', function(data) {
                $('#myJson').html('<table style="color:red"><tr><td>' + data.name + '</td><td>' + data.user + '</td></tr></table>');
            });
        });
        </script>
    </head>
    <body>
        <div id="myJson"></div>
    </body>
</html>
  • 写回答

2条回答 默认 最新

  • dream989898 2013-01-25 10:21
    关注

    Your DSN in new PDO(...) is wrong, because in MySQL the UTF-8 charset is called utf8:

    $con = new PDO('mysql:host=localhost;dbname=adnan;charset=utf8','root','');
    

    See here for more information: http://php.net/manual/en/mysqlinfo.concepts.charset.php

    Also you should catch exceptions, so PDO can tell you what's wrong next time:

    try {
        $con = new PDO(...);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口