Q:

best practise to do many connections mysqli

I received  max_user_connections error this days. and I was wondering if I am doing something wrong.
I have a config.php file with mysqli connection script:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

so pages where I need to get something in mysqli I include config.php. here is an example:
example.php
<?php
     include_once("config.php");

     $stmt = $mysqli->prepare("select...");
     $stmt->execute();
     $stmt->bind_result(...,...);
     while($stmt->fetch()) {
         ...
     }
     $stmt->close();
?>

some html <p> <img>...

<?php
     $stmt = $mysqli->prepare("select...");
     $stmt->execute();
     $stmt->bind_result(...,...);
     while($stmt->fetch()) {
       ...
     }
     $stmt->close();
?>

some html <p> <img>...

<?php
      $stmt = $mysqli->prepare("select...");
      $stmt->execute();
      $stmt->bind_result(...,...);
      while($stmt->fetch()) {
        ...
      }
      $stmt->close();
?>

So, my question is: is it the best practise to do selects like this? should I close mysqli connect after each select and open again? or do selects on the top together without separete than with some html in the middle?

A:

the best practise to do selects like this?

I hate it when people use the term "best practice" it's usually a good indicator they don't know what they are talking about.
The advantage of your approach is that its nice and simple. But as you've discovered, it does not scale well.
In practice its quite hard to measure, but in most applications the MySQL connection is unused for most of the lifecycle of the script. Hence there are usually big wins to be made by delaying the opening of connection and closing it as soon as possible.
The former can be done by decorating the mysqli class, the connect method just stores the credentials while anything which needs to talk to the database should call the wrapped connect method when it needs access to the database. However typically the yeild of this approach is low unless your code creates a lot of database connections which are never used (in which case a cheaper solution would be to increase the connection limit).
It can take a long time after the last query is run before the connection is closed down. Explicitly closing the connection addresses this, but requires a lot of code changes.
do not open and close a connection for each query. Although it will result in a reduced number of connections to the databasee, the performance will suck
The biggest win usually comes from optimizing your queries - reduced concurrency and a better user experience.

