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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动