PHP和Mysql多查询结果多次运行

时间:2017-11-22 04:21:22

标签: php mysql mysqli mysqli-multi-query php-mysqlidb

我是php和mysql的新手,尝试使用mysql 多查询功能 ,但它运行了很多次。我无法找到需要帮助的逻辑。

上面的mysql查询是示例。像这样我有很多"选择sum()" 语句,条件不同。所以我无法将mysql更改为单个查询。

<html>
<title>MYsql</title>
<body>
<?php
require 'connection.php';

$query = "select count(first_name) as fName from employees;"; /* This is the sample mysql query (separate query with different condition) */
$query .= "select count(last_name) as lName from employees;"; 
$query .= "select count(title) as title from titles;"; 
$query .= "select count(first_name) as Name from employees"; 

/* Execute queries */

if (mysqli_multi_query($conn, $query)) {
do {
    /* store first result set */
    if ($result = mysqli_store_result($conn)) {
        while ($row = mysqli_fetch_array($result)) 

/* print your results */    
{ ?>
    <div class="table" style="width: 50%; float:left; padding-top: 105px">
            <table style="width: 70%"> <tr> <th colspan="2"> Lead Status </th> </tr>
            <tr>
                <td>First Name</td>
                <td><?php echo $row[0]?></td>
            </tr>
            <tr>
                <td>Last Name</td>
                <td><?php echo $row[0]?></td>
            </tr>
            <tr>
                <td>Title</td>
                <td><?php echo $row[0]?></td>
            </tr>
            <tr>
                <td>Total Counts</td>
                <td><?php echo $row[0]?></td>
            </tr>
            </table> </div>
            <?php
}
mysqli_free_result($result);
}   
} while (mysqli_next_result($conn));
}
?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我认为您的查询是问题所在,您可以优化查询:

$query = "select count(first_name) as fName, count(last_name) as lName from employees;"; /* This is the sample mysql query (separate query with different condition) */
$query .= "select count(title) as title from titles;";  

并且不需要这个,

$query .= "select count(first_name) as Name from employees"

因为您已从第一个查询中选择了first_name