2014-10-31 80 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

相關問題