2016-04-17 46 views
0

我試圖使用MySQLi查詢獲取數據。 請檢查我的SQL查詢,我收到If條件的錯誤。 我添加誤差,其旁請檢查MySQL查詢

如果條件

當得到顯示到控制檯

<?php 
    $id = $_GET['id']; 
    include("../include/connection_string.php"); 


    $sql = mysqli_query($db, "SELECT pages, main_id FROM dhms_index_table where main_id='"+$id+"'"); 

    if(mysqli_num_rows($sql)){ // Showing error here " Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result" 
     $data = array(); 
     while($row = mysqli_fetch_array($sql)){ 
      $data[] = array(
       'pages' => $row['pages'], 
       'main_ID' => $row['main_id'] 
      ); 
     } 
     header('Content-type: application/json'); 
     echo json_encode($data); 
    } 
    ?> 

connections_string.php

$server = 'localhost'; 
$username ="root"; 
$passwd =''; 
$Dbase = 'og_dhms'; 
$db = @mysqli_connect($server,$username,$passwd) 
     or die("Could not connect database"); 
@mysqli_select_db($db, $Dbase) 
     or die("Could not select database"); 
+1

add'echo mysqli_error();'if if –

+0

我猜測查詢失敗或連接不正確。向我們顯示'connection_string。php' – RiggsFolly

+0

也看看你的php錯誤日誌,並告訴我們完整的錯誤信息 – RiggsFolly

回答

5

此行

main_id='"+$id+"' 

正在使用+符號而不是點連接。這是JS/C方法來做到這一點。也許你是來自這種類型的背景,並認爲你可以在PHP中使用它; 你不能

所以......

main_id='".$id."' 

還要確保您有$id = $_GET['id'];值。

錯誤報告會告訴你它是否是。

如果GET數組是一個整數(我相當肯定它是一個整數),那麼最好使用(int)

$id = (int)$_GET['id']; 

並檢查它是否設置/不爲空。

即:

if(isset($_GET['id'])){ 

    $id = (int)$_GET['id']; 

} 

if(!empty($_GET['id'])){ 

    $id = (int)$_GET['id']; 

} 
+0

衛生署:剛擦洗我的眼鏡....現在倒飲料放進去,烤麪包你 – RiggsFolly

+0

@RiggsFolly *乾杯*的話,會是件; - ) –

0

你的問題很可能是由查詢語法錯誤在這裏造成的:

main_id='"+$id+"' 

改變,爲了這個,要解決這個問題:

main_id='".$id."' 

但是你不應該在sql語句中使用純粹的未經過濾的用戶輸入。 我會做這樣的事情:

<?php 
$id = $_GET['id']; 
include("../include/connection_string.php"); 

if($stmt = mysqli_prepare($db, "SELECT pages, main_id FROM dhms_index_table WHERE main_id = ?")) { 

    mysqli_stmt_bind_param($stmt, 'i', $id); 
    mysqli_stmt_execute($stmt); 
    mysqli_stmt_store_result($stmt); 

    if(mysqli_stmt_num_rows($stmt) > 0) { 
     mysqli_stmt_bind_result($stmt, $pages, $main_id); 
     $data = array(); 
     while(mysqli_stmt_fetch($stmt)) { 
      $data[] = array(
       'pages' => $pages, 
       'main_ID' => $main_id 
      ); 
     } 
     header('Content-type: application/json'); 
     echo json_encode($data); 
    } 
    mysqli_stmt_free_result($stmt); 
    mysqli_stmt_close($stmt); 
} 
?> 

始終確保使用預處理語句時,你包括髮言用戶輸入,以避免SQL注入。

瞭解更多關於在這裏:​​http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

我希望它幫助。