从PHP连接MySQL的最佳有效方法? [英] The best efficient method to connect MySQL from PHP?

查看:61
本文介绍了从PHP连接MySQL的最佳有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP连接MySQL非常普遍.最常见的方法是这样的:

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

我认为这是连接MySQL最快的直接方法.但是在项目中,php脚本中的MySQL连接过多,我们应该在每个php脚本中使用"mysql_connect("localhost","user","pw")代码连接MySQL.因此,您想在文件中构建一个MySQL类或函数来连接MySQL:

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

,然后使用include()连接到您的项目中.

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

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

好的,这样,代码看起来更好.但是使用include()函数会使PHP读取并执行其他php脚本文件,再次对硬盘执行I/O操作,这也会降低性能.

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.

如果网页的速度为100PV/s,则php将以第一种方法读取并执行一个php脚本100次/秒,但以这种方法读取并执行php脚本以200次/秒!

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.

有没有人有其他更好的方法来使MySQL连接更轻松,更高效?

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

推荐答案

您实际上不需要打开那么多连接.您只需在脚本的开头打开1个连接(例如,在生成<body>之前),然后在脚本的末尾关闭它(在生成</body>之后).剩下的只有1个连接.在这两者之间,您可以根据需要执行任意数量的查询.

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.

这篇关于从PHP连接MySQL的最佳有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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