php- cant从mysql获取结果(mysqli)

时间:2013-10-18 21:49:18

标签: php mysql

我正在尝试为应用项目设置API。

我有一个名为'users'的mysql表,我已经添加了一行。

使用代码:

// Create connection
$mysqli = new mysqli("localhost","user", "pass", "db");

// Check connection
if($mysqli->connect_errno){

    $result = "Failed to connect to MySQL: " . mysqli_connect_error();
    print_r( json_encode($result) );    
    return false;

}

$row = $mysqli->query("SELECT * FROM users");
print_r( json_encode($row) );

我得到一个空洞的结果,怎么样? (连接不会引发错误)

确切地说,我得到了:

{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}

修改

得到了原始问题的答案,谢谢!

所以现在使用代码:

$row = $mysqli->query("SELECT * FROM users WHERE email = '".$email."'");
$result = $row->fetch_array();
print_r( json_encode($result) );

我得到了结果:

{"0":"test","username":"test","1":"test@test.com","email":"test@test.com","2":"test","password":"test","3":"2013-10-18 22:22:53","date_registered":"2013-10-18 22:22:53","4":"1","id":"1"}

我想要的是:

{"username":"test","password":"test","email":"test@test.com", ...etc }

我怎么做到的?

2 个答案:

答案 0 :(得分:2)

试试这个:

$result = $mysqli->query("SELECT * FROM users");
$row = $result->fetch_array(MYSQLI_ASSOC);
print json_encode($row);   // json_encode returns a string...

尝试使用关联数组:

while($row = $result->fetch_array(MYSQLI_ASSOC))
{
   $rows[] = $row;
}
print json_encode($rows);

或者您可以尝试... $rows = $result->fetch_all(MYSQLI_ASSOC);

答案 1 :(得分:1)

mysqli_query()将返回mysqli_result,您需要先fetch (as an array in this case)行,然后再对其进行操作。添加了一行:

// Create connection
$mysqli = new mysqli("localhost","user", "pass", "db");

// Check connection
if($mysqli->connect_errno){

    $result = "Failed to connect to MySQL: " . mysqli_connect_error();
    print_r( json_encode($result) );    
    return false;

}

// Get a mysql_result
$row = $mysqli->query("SELECT * FROM users");

// Get it into an array without numeric indexes
$result = $row->fetch_assoc();

// Display the row
print_r( json_encode($result) );