dqnqpqv3841 2016-07-01 23:12
浏览 57
已采纳

从PHP MySQL连接获取JSON

There are many examples of this on StackOverflow, but I can't see the error in my code. I followed a few tutorials and copied some code off this forum and it still errors bugs out.

My CREATE TABLE query:

CREATE TABLE `e1_ENGLISH` (
    `entry_id` int(11) NOT NULL AUTO_INCREMENT,
    `words_e1` char(30) NOT NULL,
    `date` date DEFAULT NULL,
    `phonetic_e1` varchar(50) NOT NULL,
    PRIMARY KEY (`entry_id`)
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8mb4 

My PHP code:

<?php
// establish connection
// mysqli contect (host, user, pass, db)
$conn = mysqli_connect("localhost","androidapp","password","myDB");

// check for connection success
if(!$conn) {
  die("Error, could not connect: " . mysqli_connect_error());
}

// build query
$sql = "SELECT * FROM e1_ENGLISH";
$result = mysqli_query($conn, $sql); // fetch data

// convert result to array
$resArray = array();
while ($row = mysqli_fetch_assoc($result)) {
    //$resArray[] = $row;
    $resArray[] = utf8_encode($row);
}

// display result
echo json_encode($resArray);

// close connection
mysqli_close($conn);
?>

The output I get (with utf8_encode):

[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]

I get a blank screen with just $resArray[] = $row;

I am new to PHP, MySQL data, and webservers. Any mistakes you can spot? Additionally, I dont have a script or anything, this is straight PHP.

Thank you in advance!

  • 写回答

3条回答 默认 最新

  • dou29106 2016-07-01 23:25
    关注

    The argument to utf8_encode() has to be a string, you can't call it on an array. You need to loop over $row calling it on each element.

    $resArray = array();
    while ($row = mysqli_fetch_assoc($result)) {
        foreach ($row as &$val) {
            $val = utf8_encode($val);
        }
        $resArray[] = $row;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP