2013-10-18 127 views
0

我試圖爲應用程序項目設置API。php-無法從mysql獲取結果(mysqli)

我有一個名爲'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} 

編輯:

得到了答案,原來YM的問題,謝謝!

所以現在使用的代碼:

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

我得到的結果是:

{"0":"test","username":"test","1":"[email protected]","email":"[email protected]","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":"[email protected]", ...etc } 

如何獲得的?

+0

如果您以前使用過'mysql_ *',您可以通過運行mysql_query()來獲得結果嗎?我不這麼認爲。從查詢中獲取數組 –

+2

您是否需要從$ row中獲取結果? –

+0

編輯我的答案。您需要使用[mysqli_fetch_assoc()](http://www.php.net/manual/en/mysqli-result.fetch-assoc.php)以避免使用數字索引重複結果。 –

回答

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)); 
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);