如何在一页中执行两个MYSQLI查询,什么是最好的方法 [英] How do I do two MYSQLI queries in one page, what is the best method

查看:51
本文介绍了如何在一页中执行两个MYSQLI查询,什么是最好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的.我正在学习mysqli API.我有两个文件.一种连接到我的数据库,另一种运行查询.一切正常.但是,我想在一个页面中运行两个查询.我怎样才能做到这一点?有什么好的方法可以做到这一点?最好的方法是一次包含我的数据库连接,然后运行两个查询,然后一次结束所有与我数据库的连接吗?那是大多数人的做法吗?

All right. I'm learning about the mysqli API. I've got two files. One that connects to my database, and one that runs the query. Everything works. However, I want to run two queries in a single page. How can I do this? What is a good method to do this? Would the best way be to include my db connect once, then run both queries, and then close my connection to my db once ending it all together? Is that how most people do it?

db.php

$mysqli = new mysqli("..", "..", "..", "..");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

query.php

query.php

include 'db.php';

$sql = "SELECT id, row1 FROM test ORDER by id DESC";

$query = $mysqli->query($sql) or die(mysqli_error());
$row_cnt = mysqli_num_rows($query);

if ($row_cnt  > 0) {

    while ($row = $query->fetch_assoc()) {
        echo $row["id"] . $row["row1"];
    }

    $result->free();
}

$mysqli->close($mysqli);

推荐答案

http: //php.net/manual/en/mysqli.multi-query.php 是一个选项,取决于您要实现的目标

http://php.net/manual/en/mysqli.multi-query.php Is an option depending on what you want to achieve

或者,你说

第二个查询来自同一张表,但是它将使用*来获取所有行.

The second query is from the same table but it'll use a * to get all rows.

如果您的代码只是一个示例,请忽略我,但是经常不需要从同一表中进行两个连续的选择查询,那么您将从*中获得"id"和"row1".因此,您可能会有一个查询首先得到*.

Ignore me if your code is just an example, but two consecutive select queries from the same table is 'often' not needed, you're getting "id" and "row1" from the *. So you could have one query that gets * in the first place.

这篇关于如何在一页中执行两个MYSQLI查询,什么是最好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆