2016-04-17 48 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

我希望它帮助。