MySQL查询未执行:;警告:mysql_fetch_assoc()要求参数1为resource;


MySQL queries not executing: "warning: mysql_fetch_assoc() expects parameter 1 to be resource"

我想使用单个脚本一次执行两个查询。我的代码只执行第一个查询,第二个查询显示错误。

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>

您的第二个查询失败,因为您在第一个查询之后调用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_output1

$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