将mysqli结果作为PHP中json_encode()的数组获取

时间:2013-12-31 10:44:49

标签: php mysql sql mysqli prepared-statement

我终于说服自己在升级旧的PHP版本后从PHP mysql切换到mysqli。但是,我没有设法实现与以前相同的方法:

这是旧方法:

$sth = mysql_query("select * from .....");

$rows = array();

while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}

print json_encode($rows);

这是我的mysqli方法:

$prename = "Peter";

$rows = array();

$mysqli = new mysqli($server, $user, $pass, $dbase);

if ($stmt = $mysqli->prepare("select lastname where prename = ? order by prename asc")) {

    /* bind parameters for markers */
    $stmt -> bind_param("s", $prename);

    /* execute query */
    $stmt -> execute();

    /* bind result variables */
    $stmt -> bind_result($lastname);

    /* fetch value */
    $stmt->fetch();

    echo $lastname;

    /* close statement */
    $stmt -> close();
}

/* close connection */
$mysqli -> close();

print json_encode($rows);

如何将查询结果添加到$rows[]数组?返回值必须是一个json字符串,将由我的webapplication解析。我尝试了几个$stmt -> fetch_array的解决方案,但没有一个解决方案。

非常感谢你的帮助。

6 个答案:

答案 0 :(得分:4)

您可以在php.net mysqli bind_result页面找到问题的解决方案:

http://www.php.net/manual/en/mysqli-stmt.bind-result.php

查看nieprzeklinaj在gmail dot com上发表的评论

他/她提供了一个函数fetch(),它将作为一个fetch all用于准备好的mysqli语句(在数组中返回完整的结果集)。它将与动态数量的选定字段一起使用。

您可以将fetch()函数添加到您的PHP代码中(当然您可以随意调用它)。

然后在上面提供的代码中使用它,你会做类似的事情:

$prename = "Peter";

$rows = array();

$mysqli = new mysqli($server, $user, $pass, $dbase);

if ($stmt = $mysqli->prepare("select lastname where prename = ? order by prename asc")) {

     /* bind parameters for markers */
     $stmt -> bind_param("s", $prename);

     /* execute query */
     $stmt -> execute();

     /* call the fetch() function provided by (nieprzeklinaj at gmail dot com) */
     $rows = fetch($stmt);
}

/* close connection */
$mysqli -> close();

print json_encode($rows);

<强>已更新

展开

我创建了一个名为“comment”的测试表,并为其提供了一个“prename”字段和一些其他随机字段,仅用于演示目的:

<?php
//fetch function from php.net (nieprzeklinaj at gmail dot com)
function fetch($result)
{    
    $array = array();

    if($result instanceof mysqli_stmt)
    {
        $result->store_result();

        $variables = array();
        $data = array();
        $meta = $result->result_metadata();

        while($field = $meta->fetch_field())
            $variables[] = &$data[$field->name]; // pass by reference

        call_user_func_array(array($result, 'bind_result'), $variables);

        $i=0;
        while($result->fetch())
        {
            $array[$i] = array();
            foreach($data as $k=>$v)
                $array[$i][$k] = $v;
            $i++;

            // don't know why, but when I tried $array[] = $data, I got the same one result in all rows
        }
    }
    elseif($result instanceof mysqli_result)
    {
        while($row = $result->fetch_assoc())
            $array[] = $row;
    }

    return $array;
}


$prename = "Peter";

$rows = array();

$server = 'localhost';
$user = 'user';
$pass = 'pass';
$dbase = 'mydatabase';

$mysqli = new mysqli($server, $user, $pass, $dbase);

$prename = "Peter";

$rows = array();

if ($stmt = $mysqli->prepare("select * from comment where prename = ? order by prename asc")) {

     /* bind parameters for markers */
     $stmt -> bind_param("s", $prename);

     /* execute query */
     $stmt -> execute();

     /* call the fetch() function provided by (nieprzeklinaj at gmail dot com) */
     $rows = fetch($stmt);
}
else{
    //print error message
    echo $mysqli->error;
}


/* close connection */
$mysqli -> close();

print json_encode($rows);

输出是:

  

[{“prename”:“Peter”,“comment_id”:1,“fullname”:“Peter 1”,“email”:“some”   电子邮件 “},{” 女士prename “:” 彼得 “ ”COMMENT_ID“:2, ”全名“:” 彼得   2" , “电子邮件”:“一些   电子邮件 “},{” 女士prename “:” 彼得 “ ”COMMENT_ID“:3 ”全称“:” 彼得   3“,”电子邮件“:”某些电子邮件“}]

数据库表信息(所以你可以检查输出):

mysql> describe comment;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| prename    | varchar(100) | YES  |     | NULL    |       |
| comment_id | int(11)      | YES  |     | NULL    |       |
| fullname   | varchar(150) | YES  |     | NULL    |       |
| email      | varchar(150) | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+

mysql> select * from comment;
+---------+------------+----------+------------+
| prename | comment_id | fullname | email      |
+---------+------------+----------+------------+
| Peter   |          1 | Peter 1  | some email |
| Peter   |          2 | Peter 2  | some email |
| Peter   |          3 | Peter 3  | some email |
+---------+------------+----------+------------+

答案 1 :(得分:1)

您可以像这样填充数组

/* bind result variables */
$stmt -> bind_result($lastname);

/* fetch value */
while ($stmt->fetch()) {
    array_push($row, $lastname);
}

答案 2 :(得分:1)

我最终使用PDO,因为它似乎比mysqli容易得多:

$stmt = $db->prepare("select * from .....");
$stmt->execute(array($lastname));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
print json_encode($rows);

答案 3 :(得分:0)

说服自己使用PDO

$stm = $db->prepare("select lastname where prename = ? order by prename asc");
$stm->execute([$prename]);
echo json_encode($stm->fetchAll());

答案 4 :(得分:0)

我需要使用mysqli查询中的数字数组获取JSON而不使用预处理语句。

<?php 
  header('Content-Type: application/json');
  $conn = include_once("dbopen.php");
  $result = mysqli_query($conn, "CALL sp_readtable");
  $data = array();
  while ($row = mysqli_fetch_row($result)){
      $data[] = $row;
  }
  echo json_encode($data, JSON_NUMERIC_CHECK);
?>

结果是一个没有键开销的二维真实数组,如下所示:

[
  ["row1fieldvalue1","row1fieldvalue2"],
  ["row2fieldvalue1","row2fieldvalue2"],
  ...
]

答案 5 :(得分:-1)

    //index.html (jQuery)
                $.ajax({
                    type : "POST",
                    url : "getResults.php",
                    data : "ID=" + "160",
                    datatype : "json",
                    success : function(result) {
                        console.log(result);
                    },
                        error : function(msg) {
                            console.log("error",msg);
                        }
                });

    //getResults.php
<?php
    try {
        include ('config.php');

        $db = connect();

        $stmt = $db -> prepare('SELECT * FROM test where test2_id = ? group by test4_id,test5_id');

        $p1 = "151";

        $stmt -> bind_param('s', $p1);  //$_POST['ID']);

        $stmt -> execute();

        $result = $stmt -> get_result();

        $returnVAR = array();

        //MYSQLI_NUM = Array items will use a numerical index key.
        //MYSQLI_ASSOC = Array items will use the column name as an index key.
        //MYSQLI_BOTH = [default] Array items will be duplicated, with one having a numerical index key and one having the column name as an index key.
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $returnVAR[] = $row;
        }

        //unicode
        header("Content-Type: application/json", true);

        echo json_encode($returnVAR);

    } catch (exception $e) {
        echo json_encode(null);
    }
?>

    //config.php
    <?php

    function connect() {
        $mysql_hostname = "localhost"; 
        $mysql_user = "coin";
        $mysql_password = "P8";
        $mysql_database = "c3in";

        //setup a connection with mySQL
        $mysqli = new mysqli($mysql_hostname, $mysql_user, $mysql_password,$mysql_database);

        /* check connection */
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }

        //enable utf8!
        $mysqli -> query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");

        return $mysqli;
    }

    ?>