我如何在PHP中执行第二个查询

时间:2016-03-10 22:04:25

标签: php mysql mysqli

我使用此代码运行非常好,但问题是如何执行第二个查询:

$query .= "SELECT * FROM `course` where id = 201102887;"; 

来自另一个表。第一个查询工作正常。你能帮助我或建议我采用另一种方式来运行许多查询。

<?php
$link = mysqli_connect("localhost", "root", "", "uoh");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * FROM `student_record` where id = 201102887;";
$query .= "SELECT * FROM `course` where id = 201102887;"; 

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
                printf("%s\n", $row[1]);

            }
            mysqli_free_result($result);
        }

        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}


/* close connection */
mysqli_close($link);
?>

1 个答案:

答案 0 :(得分:-1)

尝试使用UNION

<?php
$link = mysqli_connect("localhost", "root", "", "uoh");
$query = "SELECT * FROM `student_record` where id = 201102887 UNION SELECT * FROM `course` where id = 201102887";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_row($result))
{
    print_r($row);
}
?>

这应该打印两个数组(每行一个),一个来自student_record表(假设id是唯一的),一个来自course表假设id是独一无二的。