Do I need to open a Mysql connection for each PHP query?

Asked

Viewed 299 times

3

I need to get several variables based on my bank to mount a full Dashboard. For example, I need the number of lines, the average value of a given field and the same average value only per FU.

The strategy that has worked with me is to ask for access through the function msqli_connect() and right after the request answered I close with msqli_close(). With this I’m only getting one action, IE, only the average, or only the list of all users, or just the sum. I couldn’t, for example, get the average and the sum within the same request. Is that right? how can I request more data in the same request?

The code I’ve been using is:

// Para conseguir a média
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT AVG(q1) AS avg FROM nome_da_tabela";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            echo $row["avg"];
        }
    } else {
        echo "0 results";
    }


    mysqli_close($conn);

    // agora para conseguir a soma: 

    $conn = mysqli_connect($servername, $username, $password, $dbname);
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT SUM(q1) AS soma FROM nome_da_tabela";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            echo $row["soma"];
        }
    } else {
        echo "0 results";
    }


    mysqli_close($conn);
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

2 answers

4

No, preferably you should not do this, in PHP it is even easy to control it because in almost 100% of the cases it is only running one script ephemeral, so the limit is basically the duration of it, may have some exception, but almost always this is the appropriate.

It is not the end of the world to do differently, if you do it right, which complicates more, but it has no advantage, even if it were good and would not need to require opening and closing, every query would open and close the connection on its own. The case shown in the question is clearly wrong, even if it works.

On the other hand the question has another important issue which is the abuse of consultations when only one resolves. This yes causes quite a problem because it contacts the server twice and has almost repeated processing to do the same thing. This is a case that should not only have a connection but a single query. She asks for two things on the same table under the same conditions, so she does it all at once:

SELECT AVG(q1) AS avg, SUM(q1) AS soma FROM nome_da_tabela

I put in the Github for future reference.

Then take the two returned fields in the same processing. This whole code can be reduced to just over half a dozen lines, which is much simpler.

-1

Hi, Pedro, all right?

You can create a file to contain the connection to Mysql and embed it within it. This way, the connection to the database will already be open and you can make your queries. Finish with mysqli_close($Conn) only when you have completed all queries.

Ex:

Arquivo: connection.php
.
$servername = "";
$username= "";
$password = "";
$dbname= "";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

With this, you can make a include of this file on any page and make the queries, with a single connection. ;)

I hope I’ve helped.

  • 2

    Personally I think it’s wrong to open connections unnecessarily, put a header with msqli_connect to open connections deliberately is the same as consuming something until you don’t need it, not every page will have queries to run, soon keeping an open connection would consume more of the bank server. I even had a similar problem, I always exceeded 150 connections in the bank, which made either the bank slow or fall, when I changed the approach, only connect if you run a query or more, dropped the number of connections to between 1 and 15 per minute, and the bank never dropped.

  • 1

    @Guilhermenascimento, I see your point. But the idea is not to call the connection on all pages but on all of which will actually make the requests. Basically I’m just separating the connection file and calling when necessary. I have developed and followed several projects that use this way and have never seen problems with excess connections, because it is always closed right after the consultation. Maybe this is not really the best way to use, but with me it always worked. rs

  • Still this there has no control, it would make more sense to put the connection in Static in a hypothetical function called function query($query) { static $conn; if (!$conn) { $conn = mysqli_connect(HOST, ....); } return mysqli_query($query); }, pq ai sim would have greater guarantee to connect only when a query is actually used. I’ve discussed this a lot here on the site and in the chat site, because most people don’t understand the bottlenecks that can suffer from database and usually don’t know what they’re doing.

  • 1

    @Clebertfigueiredo without entering the discussion if it is right, but taking the point "I have participated in projects that do so" is a recurring fact in our industry. Almost nobody knows how to do it right, almost everyone "learns" by reproducing what someone else does, who has learned the same way and in general always catch someone who did not know what they were doing, so everyone learns wrong and thinks they are doing

  • 2

    @Guilhermenascimento, really seems a more applied way to use. Thank you for the explanation and for teaching me something new. rs

  • @Maniero, this is true. It turns out that people use something that worked and simply so they stop there and take it for the rest of their lives.

  • You can do variables, manners, this one is just an example ;)

  • My doubt was a little along those lines, too. I tried to make several demands with one connection only, putting for example $sql, then $sql2, $result, then $result2, and then closing the connection. But for some reason it doesn’t work. Only when I close the connection and open a new one. I can make multiple requests within the same connection?

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.