2014-10-31 34 views
0

我想通过使用单个脚本一次执行两个查询。我的代码只执行第一个查询,而第二个查询显示一个错误。MySQL查询不执行:“警告:mysql_fetch_assoc()期望参数1是资源”

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\hms\getpatient.php on line 29 Notice: Undefined variable: json_output in C:\xampp\htdocs\hms\getpatient.php on line 32

任何一个可以请大家帮忙,为什么这两个查询不执行,但他们分别将执行。

PHP

<html> 
    <head> 
    <title>Paging Using PHP</title> 
    </head> 
    <body> 

    <?php 

     mysql_connect("localhost","root",""); 
     mysql_select_db("hms"); 
    ?> 
     <?php 
     $q1=mysql_query("SELECT * FROM initial_master"); 



     while($row1=mysql_fetch_assoc($q1)) 
       $json_output1[]=$row1; 

     print(json_encode($json_output1)); 

     mysql_close(); 
     ?> 
     <?php 


     $q=mysql_query("SELECT * FROM patient_main_category"); 

     while($row=mysql_fetch_assoc($q)) 
       $json_output[]=$row; 

     print(json_encode($json_output)); 

     mysql_close(); 
      ?> 

    </body> 
    </html> 
+0

正确的表名 – user 2014-10-31 08:26:01

+0

声明'$ json_output1 = array();'在你使用它去除你正在获取的通知之前。 – 2014-10-31 08:27:05

+2

在第二次查询之前,您有一个'mysql_close();'。 – djidi 2014-10-31 08:27:49

回答

0

你的第二个查询失败,因为你是第一个查询后调用mysql_close()。简单地删除它应该能解决你的问题。

<html> 
    <head> 
    <title>Paging Using PHP</title> 
    </head> 
    <body> 

    <?php 

     mysql_connect("localhost","root",""); 
     mysql_select_db("hms"); 
    ?> 
     <?php 
     $q1=mysql_query("SELECT * FROM initial_master"); 

     $json_output1 = array(); // fixes Undefined variable 

     while($row1=mysql_fetch_assoc($q1)) 
       $json_output1[]=$row1; 

     print(json_encode($json_output1)); 

     //mysql_close(); 
     ?> 
     <?php 


     $q=mysql_query("SELECT * FROM patient_main_category"); 

     while($row=mysql_fetch_assoc($q)) 
       $json_output[]=$row; 

     print(json_encode($json_output)); 

     mysql_close(); 
      ?> 

    </body> 
    </html> 

修复Undefined variable通知使用它

$json_output = array(); 

你也应该做一些错误检查,以防止今后

$q = mysql_query('SELECT ...'); 
if (!$q) { 
    // handle error, for example: 
    die('Database errror'); 
} 

最后,你应该考虑使用这样的问题之前宣布一个更安全,更强大的数据库库,可以捕捉到这样的错误。

<?php 
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password'); 

try { 
    //connect as appropriate as above 
    $result = $db->query('SELECT * FROM ...'); 
} catch(PDOException $ex) { 
    echo "An Error occured!"; //user friendly message 
    some_logging_function($ex->getMessage()); 
} 

参见如何使用PDO库,而不是mysql_*功能本指南。 http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

+0

非常感谢你 – user 2014-10-31 08:33:10

+0

不客气。如果它解决了你的问题,请接受这个答案。 – mak 2014-10-31 08:37:20

相关问题