2017-08-05 83 views
0

我正在嘗試爲我的移動後端與MySQL數據庫交互創建一個php REST API。我已經寫了下面的代碼,試圖從中檢索MySQL查詢數據:php在嘗試獲取MySQL數據時返回空GET陣列

<?php include "FILE WITH DB_INFO"; ?> 
    <html> 
    <body> 
    <h1>Testing page</h1> 
<?php 

$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD); 

if (mysqli_connect_errno()) echo "Failed to connect to MySQL" . mysqli_connect_error(); 


$database = mysqli_select_db($connection, DB_DATABASE); 

if (strlen($username_query)) { 
    doesUsernameExist($connection, $username_query); 
} 

doesUsernameExist($connection, $username_query); 

$username_query = $_GET['usernameToQuery']; 

echo($_GET['usernameToQuery']); 


function doesUsernameExist($connection, $username) { 
    $u = mysqli_real_escape_string($connection, $username); 

    $query = "SELECT username from users WHERE username = ('$u');"; 


if (!mysqli_query($connection, $query)) { 
    $response = array("success" => false, "message" => mysqli_error($connection), "sqlerrno" => mysqli_errno($connection), "sqlstate" => mysqli_sqlstate($connection)); 
    echo json_encode($response); 
} else { 
    $sth = mysqli_query($connection, $query); 
    $rows = array(); 
    while($r = mysqli_fetch_assoc($sth)) { 
     $rows[] = $r; 
    } 
    $response = array("success" => true); 
    echo json_encode($rows); 
} 

} 
?> 

這是實際的請求是什麼樣子:http://my_ec2_instance/DoesUsernameExist.php?usernameToQuery=lmao。 這是通過POSTMAN發送的。

由於我使用的MySQL數據庫包含值爲lmao的用戶名,PHP函數應返回非空數組。但json_encode($rows);行返回空數組[]。我究竟做錯了什麼。

+0

看樣子你調用'doesUsernameExist()'兩次,一次一個'if'語句中,一旦外界將這個你行之後。在這兩種情況下,我都看不到爲「$ username_query」賦值的位置。我對嗎? – JBH

+0

@JBH無論回聲應該輸出的值。 @ Mr.Man檢查你實際發送了一個GET請求,而不是POST。確保您的數據格式良好,等等......您還可以使用'print_r($ _ GET)' – Geoffrey

+0

'$ _Get ['usernameToQuery']'查看整個'$ _GET'數組到'$ username_query'。還是我沒有以正確的方式做到這一點? –

回答

1

看起來你可以撥打doUsernameExiste(),並在strlen之前用變量$username_query。但是你只能在後面定義$username_query

你應該先做你的做作。與mysqli_select_db

$username_query = $_GET['usernameToQuery'];

+0

請注意,設置值後的測試'echo'仍然應該輸出值......這不能回答他的問題。 – Geoffrey

+0

Sheplu,謝謝! –

+0

你是對的,@Geoffrey。我忘記了他將變量值作爲GET傳遞。奇怪的是,我無法刪除這個答案。 – JBH