2015-04-23 50 views
0

我想要使用Slim框架獲取json文件。我想下面的代碼苗條的框架沒有輸出顯示

$app->get('/forum/:id', function ($id) { 
$user_name = "abc"; 
$password = "123"; 
$database = "test"; 
$server = "localhost"; 

$db_handle = mysqli_connect($server, $user_name, $password); 
mysqli_set_charset($db_handle, "utf8"); 
mysqli_select_db($db_handle, $database); 

$arr = array(); 
    $SQL = "Select y123_forum.post_id, y123_forum.posttext FROM y123_forum INNER JOIN y123_users ON y123_forum.user_id = y123_users.id WHERE type = 1 AND y123_users.email = 'id'"; 

$result = mysqli_query($db_handle, $SQL); 
while ($row = mysqli_fetch_assoc($result)) 
    { 
     array_push($arr, $row); 
    } 
mysqli_close($db_handle); 
echo json_encode($arr); 
}); 

提到在瀏覽器上顯示的輸出是[]

當我試圖不通過參數上面的代碼,即

$app->get('/faqs/', function() { 
$user_name = "abc"; 
$password = "123"; 
$database = "test"; 
$server = "localhost"; 

$db_handle = mysqli_connect($server, $user_name, $password); 
mysqli_set_charset($db_handle, "utf8"); 
mysqli_select_db($db_handle, $database); 


$arr = array(); 
$SQL = Select y123_forum.post_id, y123_forum.posttext FROM y123_forum INNER JOIN y123_users ON y123_forum.user_id = y123_users.id WHERE type = 1 AND y123_users.email = '[email protected]'" 

$result = mysqli_query($db_handle, $SQL); 
while ($row = mysqli_fetch_assoc($result)) 
    { 
     array_push($arr, $row); 
    } 
mysqli_close($db_handle); 
echo json_encode($arr); 

}); 

那麼它的工作原理罰款

我該如何解決這個問題,我需要得到這個工作,通過從數據庫中傳遞任何電子郵件ID來獲得json文件

回答

1

你忘記參數中的$,它認爲你正在尋找'id'的電子郵件地址,而不是$ id的內容。

SELECT * FROM y123_forum WHERE email = '$id'; 

請注意,這是一個可怕的,不好的,不安全的方式來傳遞參數到SQL查詢。正確的方法是參數化查詢和執行是這樣的:

$SQL = 'SELECT * FROM y123_forum WHERE email = ?'; 
$stmt = mysqli_stmt_init($db_handle); 
if (mysqli_stmt_prepare($stmt, $sql)) { 
    mysqli_stmt_bind_param($stmt, 's', $id); 

    mysqli_stmt_execute($stmt); 
    $result = mysqli_stmt_get_result($stmt); 
    while ($row = mysqli_fetch_assoc($result)) 
    { 
     array_push($arr, $row); 
    } 
} 

的「s」在mysql_stmt_bind_param告訴你的$ id變量應該被視爲一個字符串的驅動程序,並適當地逃脫了。

+0

感謝邁克......現在正在工作......我忘記了$符號:) – dexter

+0

我已對系統上的代碼進行了更改,並且它工作的很棒,我不知道mysqli_stmt_bind_param,我將開始使用它 :) – dexter