多个PHP查询的指导

时间:2012-06-20 12:52:24

标签: php mysql database

我正在尝试在3个相邻的<div>容器中显示3个单独查询的结果。这三个查询如下:

$query="SELECT * FROM students WHERE WeekOne='employer'";
$query="SELECT * FROM students WHERE WeekTwo='employer'";
$query="SELECT * FROM students WHERE WeekThree='employer'";

期望的输出:

  

每周一周-----每周两次-----每周三次

     

结果1 ----------结果1 -----------结果1

     

结果2 ----------结果2 -----------结果2   (等...)

有人可以帮我这个吗?我在PHP手册上看过multi_query,但不知道如何实现它。非常感谢。

@Emmanuel G

<?

$user = "xx";
$user_password = "xx";
$db_name = "xx";
$db = new mysqli ("xx", $user, $user_password, $db_name);

$queries = array(
    "SELECT * FROM students WHERE WeekOne='$Name'",
    "SELECT * FROM students WHERE WeekTwo='$Name'",
    "SELECT * FROM students WHERE WeekThree='$Name'"
);

// iterate through the queries and their results
foreach($queries as $query){
    $result = $mysqli->query($query);
    echo '<div>'; // open that div up
    while($row    = $result->fetch_assoc()){       // gives u an array hoorah!
        echo '<pre>'.print_r($row, true).'</pre>'; // just to look at it
        echo "<p>{$row['FirstName']}</p>";              // just an example
    }
    echo '</div>'; // close it up
}

?>

4 个答案:

答案 0 :(得分:0)

最简单的方法是将查询更改为:

$query="SELECT * FROM students WHERE WeekOne='employer' OR WeekTwo='employer' OR WeekThree='employer'";

然后相应地格式化输出。

答案 1 :(得分:0)

是的,更改您的查询以将您的所有结果都放在一个查询请求中,然后您从数据结果中进行操作,多次点击服务器的简单答案不是最佳做法,因为您的查询非常简单。

但是对于你的问题

multi_query($query)  //you can use this

看看http://suite101.com/article/how-tor-run-multiple-mysql-queries-with-php-a105672

答案 2 :(得分:0)

要显示它,只需迭代每个单独的结果并将其放入div中。为了使它们相邻,你可以在你的div中添加一些css来浮动它们,因为div本身就是块元素,如果没有一些帮助就不会水平排列。

假设您已经设置了数据库连接,并且应该使用mysqli,那么您可以像这样生成标记:

// u should try to make this one query but that's irrelevant to the question 
// so I'll leave that to you to do later
$queries = array(
    "SELECT * FROM students WHERE WeekOne='employer'",
    "SELECT * FROM students WHERE WeekTwo='employer'",
    "SELECT * FROM students WHERE WeekThree='employer'"
);

// iterate through the queries and their results
foreach($queries as $query){
    if($result = $mysqli->query($query)){// only do stuff if you get a result
        echo '<div>';                                  // open that div up
        while($row = $result->fetch_assoc()){          // gives u an array hoorah!
            echo '<pre>'.print_r($row, true).'</pre>'; // just to look at it
            echo "<p>{$row['data']}</p>";              // just an example
        }
        echo '</div>';                                 // close it up

        // mysqli free the result to prep for the next one
        $result->free();
    } else {
        echo "Query failed to return results:\n$query\n";
    }
}

答案 3 :(得分:-1)

我猜你正在通过雇主作为网址参数,所以无论哪种方式,你也可以传递你要比较的week,让我们说

$week = $_GET['weekOne'];
$employer = $_GET['employer'];

$query="SELECT * FROM students WHERE $week= $employer";

在执行查询之前确保escape您的数据,以避免sql注入

我希望它会对你有所帮助。感谢