PHP->JSON 编码不起作用

标签 php mysql

我知道这个问题现在已经被问过一百万次了。

我尝试了在这里找到的几种解决方案,但仍然对我不起作用。

我想要做的是从简单的 MySQL 表中SELECT值。

我编写的程序每五分钟插入一次值。

我捕获选定文件夹中的所有 mp3 文件并将其 ID3 标签插入到表 tb_song 中。

然后应使用 PHP 脚本选择这些文件,并且 Android 应用程序应使用其 URL 播放这些文件。

数据库和 PHP 代码有效。

如果我只是回显所有选定的值,它就可以正常工作。 但是转换并打印出编码的数组只会引发空白屏幕。

难道 JSON 对象有大小限制吗?

我在 tb_song 中有大约 500 个条目。

这是我的代码。

<?php
require_once('config.php');
$connection=new mysqli($server,$user,$password,$database);

$songs=array();
$sql=("SELECT Title,Artist,Album FROM tb_song");
$result=$connection->query($sql);

while($row=$result->fetch_assoc())
{
$temp=array();

$temp['Title']=$row['Title'];
$temp['Artist']=$row['Artist'];
$temp['Album']=$row['Album'];

array_push($songs,$temp);

}
json_encode($songs);
echo(json_encode($songs));//just for testing purposes
  $connection->close();
?>

最佳答案

您可以将代码简化为这样。另外添加一些错误检查!

<?php
/* add next 2 lines while testing, 
   especially if you are using a live hosting site
   where error reportinf will be turned off
*/
error_reporting(E_ALL); 
ini_set('display_errors', 1);

require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);

// Check connection is good
if ($connection->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $connection->connect_error);
}

$songs=array();

$sql = 'SELECT Title,Artist,Album FROM tb_song';
$result = $connection->query($sql);

if ( ! $result ) {
    echo $connection->error;
    exit;
}

while($row=$result->fetch_assoc()) {
    $songs[] = $row;
}

$jstring = json_encode($songs);
if ( json_last_error() > 0 ) {
    file_put_contents('json-output.txt', json_last_error_msg());
}
echo $jstring;

//add this line for testing
file_put_contents('json-output.txt', $jstring);
exit;
?>

关于PHP->JSON 编码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35024094/

相关文章:

mysql - 为什么Mysql匹配 bool 模式找不到 "Knows"

mysql - 如何解决 Hibernate 中连接过多的错误

javascript - 使用 Javascript 和 PHP 将 JSON 存储为 CSV

PHP 密码哈希 - PHPass

php - FullCalendar 使用数据库和谷歌日历

php - 使用 PDO 连接进行 SQL 更新

MySQL 错误代码 : 1064 Stored Procedure Syntax Error near END END

PHP函数滥用?

php - 如何通过 FormBuilder 的字段传递 Twig 参数

MySQL 对重音字符太聪明了