插入字符串的MySQL数据到JSON数组

时间:2016-05-04 05:30:58

标签: php mysql json

这是我的代码,但它只适用于mySQLResultsetToJSON()中的for循环。

<?php    
$servername = "127.0.0.1";
$username = "root";
$password = "123456";
$table = "ticketing";
$link = new mysqli($servername, $username, $password, $table);
if ($link->connect_error) {
    die("Connection failed: " . $link->connect_error);
}
    echo "Connected successfully";    

$result = $link->query("SELECT * from Ticket");

print_r($result);
$final_result = mySQLResultsetToJSON($result);
print_r($final_result);    
$link->close();    

function mySQLResultsetToJSON($resultSet)
{
        for($i = 0; sizeof($resultSet); $i++)
        {
            $rows = array();
            while($r = mysqli_fetch_assoc($resultSet[$i])) {
                $rows[] = $r;
            }
            $jsonResult[$i] = json_encode(array('Results' => $rows));
        }    
        print_r($jsonResult);    
        return $jsonResult;
    }    
?>

谢谢!

托马斯

2 个答案:

答案 0 :(得分:1)

echo "mysql data<br />";
$result = $link->query("SELECT * from users");
print_r($result->fetch_object());

echo "<br />";

echo "in json<br />";
$res = ['Results' => $result->fetch_object() ];
echo json_encode($res);
$link->close();

答案 1 :(得分:0)

用户喜欢

$result = $link->query("SELECT * from Ticket");
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}
print "<pre>";
print_r(json_encode(array('Results' =>$rows)));    
$link->close();