简体   繁体   中英

php's mysqli_multi_query not working

I've been trying to execute a multiple query, so I've searched for a better approach on how to do this and I've read this mysqli_multi_query in php.

I tried it on my own to see the results, but it keeps on giving me error. Here's the code:

$studid = $_GET['stud_id'];
$classcode = $_GET['class'];

$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');     

$sql = "SELECT * FROM tbl_students WHERE stud_id = '".$studid."'";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'";

if (mysqli_multi_query($conn, $sql)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($conn)) {
            while ($row = mysqli_fetch_row($result)) {
                $studname = $row[3].", ".$row[1];

            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($conn)) {
            printf("-----------------\n");
            $studname = $row['fname'];
        }
    } while (mysqli_more_results($conn));
}else{ echo "error";}

$conn->close();

With the code above, it will just print error from the else statement I set. I also tried changing the second query to $sql .= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'"; and also tried putting semicolon after the first query to tell the SQL that I'm done with the first query since I'm putting 2 strings together, but still no luck.

try this

$studid = $_GET['stud_id'];
$classcode = $_GET['class'];

$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');     

$sql = "SELECT * FROM tbl_students WHERE stud_id = '$studid';";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '$classcode'";

if ($conn->multi_query($sql)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($conn)) {
            while ($row = mysqli_fetch_row($result)) {
                $studname = $row[3].", ".$row[1];

            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($conn)) {
            printf("-----------------\n");
            $studname = $row['fname'];
        }
    } while (mysqli_more_results($conn));
}else{ echo "error";}

$conn->close();

Make one query instead of two :

"SELECT ts.*, tc.* 
FROM tbl_students as ts, tbl_classes as tc 
WHERE ts.stud_id = '$studid' 
AND tc.class_code = '$classcode'"

Note : If you get redundant data then use group by.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM