首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >MySQLI查询结果(多行)到JSON

MySQLI查询结果(多行)到JSON
EN

Stack Overflow用户
提问于 2018-07-04 02:19:32
回答 3查看 203关注 0票数 -1

我无法使用JSON_encode() php函数查看作为JSON对象返回的mysql查询结果的所有行。下面是我的代码:

代码语言:javascript
复制
$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$ligne = array();
$bilan = array();

while ($rowr = mysqli_fetch_assoc($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID']
    );
    $bilan[$ligne['User']] = $ligne[[
        ['User_ID'][$rowr['User_ID']]
    ]];
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

它返回我:

{"":null,"0":{"User_ID":"1"},"1":{"User_ID":"19"},"2":{"User_ID":"78"},"3":{"User_ID":"79"},"4":{"User_ID":"85"},"5":{"User_ID":"86"},"6":{"User_ID":"87"},"7":{"User_ID":"88"},"8":{"User_ID":"91"},"9":{"User_ID":"92"},"10":{"User_ID":"93"},"11":{"User_ID":"94"},"12":{"User_ID":"95"},"13":{"User_ID":"96"},"14":{"User_ID":"97"},"15":{"User_ID":"98"},"16":{"User_ID":"99"},"17":{"User_ID":"100"},"18":{"User_ID":"101"},"19":{"User_ID":"102"},"20":{"User_ID":"103"},"21":{"User_ID":"104"},"22":{"User_ID":"105"},"23":{"User_ID":"106"},"24":{"User_ID":"107"},"25":{"User_ID":"108"},"26":{"User_ID":"109"},"27":{"User_ID":"110"},"28":{"User_ID":"111"},"29":{"User_ID":"112"},"30":{"User_ID":"113"},"31":{"User_ID":"114"},"32":{"User_ID":"115"},"33":{"User_ID":"116"}}

现在,我尝试在json输出中关联每条记录的其他字段。但是,当将此代码添加到我的代码中时,没有更多的输出。

代码语言:javascript
复制
while ($rowr = mysqli_fetch_assoc($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID'],
        "User_Nom" => $rowr['User_Nom']
    );      
    $bilan[$ligne['User']] = $ligne[[
        ['User_ID'][$rowr['User_ID']]
    ][
        ['User_Nom'][$rowr['User_Nom']]
    ]];
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

好像在数字上可以显示数值而不是字母字符。

请帮助我在相同的输出中混合数字和字母内容。

谢谢阿诺德

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-07-04 14:54:24

你是对的,自从最初的干净计划,因为它不起作用,我做了太多的修改,最终增加了复杂性,没有必要……

我在php文档中发现了了解更多关于在json转换中添加其他字段时产生的错误的可能性。json_last_error()是理解这个问题的关键。所以我补充道:

代码语言:javascript
复制
switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - Aucune erreur';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Profondeur maximale atteinte';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Inadéquation des modes ou underflow';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Erreur lors du contrôle des caractères';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Erreur de syntaxe ; JSON malformé';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Caractères UTF-8 malformés, probablement une erreur d\'encodage';
        break;
        default:
            echo ' - Erreur inconnue';
        break;
    }

所以我修改了我的代码,添加了一些

代码语言:javascript
复制
utf8_encode($rowr['Fieldname'])

第一个有效的解决方案与@PaulH one的非常接近,只是,在我的特定情况下,我必须添加(utf8_encode())语句:

代码语言:javascript
复制
    $Sql_Query = "SELECT * FROM Users";
    $result = mysqli_query($dbc,$Sql_Query);
    $ligne =array();
    $bilan = array();
    while ($rowr = mysqli_fetch_assoc($result)) {
        $ligne = array ("User_ID" => $rowr['User_ID'],  
                        "User_Nom" => utf8_encode($rowr['User_Nom']),
                        "User_Prenom" =>utf8_encode($rowr['User_Prenom']));
        array_push ($bilan, $ligne);
    }
    echo json_encode($bilan, JSON_FORCE_OBJECT); 

现在它显示所有的字段,所有的行。但仍有一些"é“转换为”u00e9“。因此,this post为解决方案提供了最后一块砖。

我修改了:

JSON_FORCED_OBJECT

JSON_UNESCAPED_UNICODE

作为json_encode()参数。

最后,提供我想要的代码如下所示:

代码语言:javascript
复制
$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$bilan = array();
while ($rowr = mysqli_fetch_assoc($result)) {
    $ligne = array ("User_ID" => $rowr['User_ID'],  
                    "User_Nom" => utf8_encode($rowr['User_Nom']),
                    "User_Prenom" =>utf8_encode($rowr['User_Prenom']));
    array_push ($bilan, $ligne);
}
echo json_encode($bilan, JSON_UNESCAPED_UNICODE);
票数 0
EN

Stack Overflow用户

发布于 2018-07-04 02:55:28

$ligne‘’User‘未初始化,您可以尝试执行以下操作:

代码语言:javascript
复制
while ($rowr = mysqli_fetch_assoc($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID'],
        "User_Nom" => $rowr['User_Nom']
    );      
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

我用下面的代码测试了它

代码语言:javascript
复制
$result[] = ['User_ID' => 1, 'User_Nom' => 'Nom1'];
$result[] = ['User_ID' => 2, 'User_Nom' => 'Nom2'];
$result[] = ['User_ID' => 3, 'User_Nom' => 'Nom3'];
$bilan = [];
while ($rowr = array_pop($result)) {
    $ligne = array (
        "User_ID" => $rowr['User_ID'],
        "User_Nom" => $rowr['User_Nom']
    );
    array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);

它提供了以下结果:

{"0":{"User_ID":3,"User_Nom":"Nom3"},"1":{"User_ID":2,"User_Nom":"Nom2"},"2":{"User_ID":1,"User_Nom":"Nom1"}}

注意,结果有一个不同的开始,它不包含

“”:空,

再来一次。这是奇怪的$bilan[undefined] = undefined代码行的结果

票数 0
EN

Stack Overflow用户

发布于 2018-07-04 05:52:57

为清晰起见,已转换为>= 5.5。

我只是在猜测和假设,但我还能做什么呢?我看到的主要问题是,您可能会被数组语法绊倒。您似乎希望通过'User_ID‘重新索引结果,我假设它是在每个表记录中找到的某个字符串标识符。

模块化的,以程序的形式...

代码语言:javascript
复制
/*
    Assuming you are attempting to re-index by the 'User_ID' field
    of each record before encoding as JSON.
*/

function getDb($ip, $user, $password, $database) {
    $db = mysqli_connect($ip, $user, $password, $database);

    //error checking etc ...

    return $db;
}

function selectRecords(mysqli $db, $sql) {
    $result = mysqli_query($db, $sql);

    if (!$result) {
        throw new UnexpectedValueException("Database query (read) was unsuccessful!");
    }

    return $result;
}

function getUserRecords(mysqli $db) {
    $query = 'SELECT * FROM Users';
    return selectRecords($db, $query);
}

function reindexByField($newIndex, $userResults) {
    $reindexed = [];

    while ($row = mysqli_fetch_assoc($userResults)) {
        if (!isset($row[$newInded])) {
            throw new OutofBoundsException("The index '" . $newIndex . "' does not exist in the tested record");
        }

        $redindexed[$row[$newIndex]] = $row;
    }

    return $reindexed;
}

function getJsonFromArray(array $records) {
    $json = json_encode($records, JSON_FORCE_OBJECT);

    if (!$json) {
        throw new UnexpectedValueException("Records were not encoded into a JSON formatted string. Got boolean false, instead.");
    }

    return $json;
}

在程序形式中,然后..。

代码语言:javascript
复制
try {
    $db = getDb($ip, $user, $password, $db); // Just pretend for a moment.
    echo getJsonFromArray(reindexByField('User_ID', getUserRecords($db));
} catch (e) {
    // Your handler code here.
} finally {
    mysqli_close($db);
}

面向对象的方法可以使您的代码更有条理。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51160802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档