Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best efficient method to connect MySQL from PHP?

It is very common that using PHP to connect MySQL. The most common method is like this:

$sqlcon=mysql_connect("localhost","user","pw");
mysql_select_db('database');
$sqlcomm=mysql_query("SELECT id FROM bd");
while($row=mysql_fetch_row($sqlcomm))
{
   //do something
}
mysql_close($sqlcon);

I think this is the fastest direct way to connect MySQL. But in project, there will have too many MySQL connections in php script, we should use "mysql_connect("localhost","user","pw")" code to connect MySQL in every php script. So you will like to build a MySQL class or function in a file to connect MySQL:

function connect( $query )
{
   $sqlcon=mysql_connect("localhost","user","pw");
   mysql_select_db('database');
   $sqlcomm=mysql_query($query);
   while($row=mysql_fetch_row($sqlcomm))
   {
       //do something.
   }
   mysql_close($sqlcon);
}

and then include into your project using include() for connection.

include('connect.php');
$data = connect('SELECT id from db');

OK, in this way, the code is look better. But using include() function will let PHP to read and execute other php script files, a I/O operation on harddisk again, it will also slow down the performance.

If the webpage is 100PV/s, php will read and execute a one php script 100 times/s in first method, but read and execute php script 200 times/s in this method!

I here show a simple example for only one query. Try image a high network multi-query environment.

Dose any one have other better way to make MySQL connection more easier and more efficient?

like image 893
Angolao Avatar asked Oct 11 '22 09:10

Angolao


2 Answers

You don't really need to open that many connections. You just open 1 connection at the start of your script (before <body> gets generated, let's say), and then close it at the end of your script (after </body> is generated, let's say). That leaves you with only 1 connection. In between, you can execute as many queries as you need.

like image 184
Frantisek Avatar answered Oct 18 '22 09:10

Frantisek


Have you looked at using PDO? it does connection pooling and what not andnot limited to mysql...

like image 43
Ian Wood Avatar answered Oct 18 '22 09:10

Ian Wood