How do I do two MYSQLI queries in one page, what is the best method

天大地大妈咪最大 提交于 2019-12-24 12:19:20

问题


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

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);

回答1:


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

Alternatively, you said

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

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.



来源:https://stackoverflow.com/questions/18048093/how-do-i-do-two-mysqli-queries-in-one-page-what-is-the-best-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!