php做的网站 连接mysql数据库 效率问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php做的网站 连接mysql数据库 效率问题相关的知识,希望对你有一定的参考价值。

新手入门,各位不要见笑。我想问一下,如何处理数据库连接才能做到效率最高呢?
我的思路是:
我现在要在一个db.php中定义连接,包括:
$connect=mysql_connect("localhost:3306","root","root");
mysql_select_db("php",$connect);
然后在每个php文件中都引入这个文件,然后mysql_query执行CRUD,然后再mysql_close($connect).
这样的话,我的每一个用到数据库查询的页面都要重新链接数据库,用完以后关闭连接,我们知道连接数据库的代价是很大的。能不能用类似j2ee连接池的思路?或者其他解决方案??
还请各位高人不吝赐教。。。

你可以把连接的方法写进类里,让它形成方法比如
class something

global $db;
function web_db()
$this->db = $this->database(); //把连接方法存如属性里

function database($server = 'localhost',$root = 'root',$pass = '****')
......//这里写你的连接方法,及其关联表操作

...//其他方法
//class end
在你的页面程序中这样写
require_once "web_common.class.php";//包进你的类文件
$mysql = new something;
在你需要数据查询或写入的时候只要调用 $mysql->db;就好了

如上你可以看出,无论你有多少客户请求数据库,而数据库只在载入页面时连接一次而已,调用 $mysql->db 只是请求程序,请求方法而已,没有请求数据库。第一,数据库连接查询只有一次;第二无形中也加快了页面的载入速度。
记住,你做网页不是给一个人两个人用的,而是很很很多个,为了保证数据库的正常使用,在多请求的情况下依然能很好工作,这是个很好的办法。
最后close是可写可不写的,因为当mysql没有请求时,它会自动关闭。
参考技术A 关注 参考技术B 如果想要优化可以 把数据库查询结果缓存在内存中,可以直接调用

当然使用数据库永久连接mysql_pconnect()不晓得能不能达到你那个目的 呵呵
参考技术C PHP in the database to support the rich, it is also one of the reasons why quickly became popular, it supports the following databases or data files:
Adabas D
DBA
DBase
Dbm
FilePro
Informix
InterBase
MSQL
Microsoft SQL Server
MySQL
Solid
Sybase
ODBC
Oracle 8
Oracle
PostgreSQL
In the Internet, it also supports a significant number of communication protocols (protocol), including relevant e-mail with IMAP, POP3; network management system SNMP; network news NNTP; account shared NIS; global information network and HTTP server Apache; directory LDAP protocol and other network-related functions.
In addition, written in PHP using the Web back-end CGI program can be easily ported to the different operating systems. For example, the first plane to Linux's Web site, the system load is too high, they can quickly move the entire system on SUN workstations, do not have to recompile CGI program. In the face of the rapid development of the Internet, this is the best long-term planning.
Variable type:
PHP There are a variety of variables; these are:
- Digital (integer - example: 32)
- Boolean (boolean - cases: TRUE)
- String (string - case of: 'a string of text')
- NULL
- Resources (resource)
- Array (array - example: arrayname [2])
Syntax:
There are three kinds of grammar:
/ / Comment
/ * Comment * /
# Comment
The basic "Control Structures":
* If ... else
If (condition == true);
* If ... else then
If (condition == true)
Else if (condition2 == true);
A PHP example:
<html>
<head>
<title> First program </ title>
</ Head>
<body>
<? Php
Echo "hello world";
?>
</ Body>
</ Html>
Take a look:
Php official website: www.php.net
Php support for object-oriented
The concept of object-oriented programming:
The argument between the different authors may not be the same, but there must be a OOP language in the following areas:
Abstract data types and information package
Succession
Polymorphism
PHP is in the category to complete the package:
<? Php
Class Something (
/ / OOP in the category, usually the first characters to uppercase
Var $ x;
Function setX ($ v) (
/ / Lower-case approach for the beginning of words, and then use capital letters to separate words, such as getValueOfArea ()
$ This-> x = $ v;
)
Function getX () (
Return $ this-> x;
)
)
Of course, you can define their own preferences, but the best to maintain a standard would be more effective. Members of the data used in the category of "var" to define the statement, addressed to the members of the data prior to the assignment, they are not the type. A member of the data can be a whole number, an array, an array of related (associative array) or an object. In the category method is defined in the form of a function in ways to access the members of the class of variables, you should use $ this-> name, or a method, it is the only local variables.
The use of new operators to create an object:
$ Obj = new Something;
Then you can use a member function through:
$ Obj-> setX (5);
$ See = $ obj-> getX ();
In this case, setX members of the function will be assigned to the target of 5 members of the variable x (not the kind of), and then return to getX its value 5. As can be: $ obj-> x = 6 through the categories cited as ways to access data members, this is not a good habit of OOP. I strongly recommend the adoption of methods to access the members of the variables. If you can not be seen as members of the variables to deal with and handle only object to the use of methods, you will be a good OOP programmers. Unfortunately, PHP does not support the statement of the members of the private variable, so bad code in PHP is also permitted. In succession in PHP is easy to achieve, as long as extend the use of keywords.
<? Php
Class Another extends Something (
Var $ y;
Function setY ($ v) (
$ This-> y = $ v;
)
Function getY () (
Return $ this-> y;
)
)
"Another" category of objects now has a parent (Something) of all the members of the data and methods, but also add their own data members and methods.
You can use the
$ Obj2 = new Something;
$ Obj2-> setX (6);
$ Obj2-> setY (7);
PHP is not support multiple inheritance, so you can not two or more types of derivatives to a new category. You can re-definition of derived classes in a way, if we are in the "Another" category in the re-definition of getX, we will not be able to use the "Something" in the getX methods. If you're in a statement in the derived class with a data base to send members of the same name, so when you deal with it, it will "hide" members of the data base class.
You can define your class constructor. Constructor is a category with the name of the method of the same name, when you create a category of object would be called, for example:
<? Php
Class Something (
Var $ x;
Function Something ($ y) (
$ This-> x = $ y;
)
Function setX ($ v) (
$ This-> x = $ v;
)
Function getX () (
Return $ this-> x;
)
)
So you can create an object through:
$ Obj = new Something (6);
Constructor will be automatically assigned to the 6 variable data x. Constructor and methods are common PHP function, so you can use the default parameters.
Function Something ($ x = "3", $ y = "5")
Then:
$ Obj = new Something (); / / x = 3 and y = 5
$ Obj = new Something (8); / / x = 8 and y = 5
$ Obj = new Something (8,9); / / x = 8 and y = 9
Default parameters of the use of C + + way, so you can not ignore the value of Y, and X to a default parameters of the assignment is from left to right, if the incoming parameter is less than the requirements of parameters, will make its The use of default parameters.
When a derived class of object is created, only its constructor is called, the constructor of the class of the father was not called, if you want to call the base class constructor, you must be in the derived class constructor call in show. To do so because the derived class father of all types of methods are available.
<? Php
Function Another () (
$ This-> y = 5;
$ This-> Something ();
/ / Display base class constructor call
)
The OOP is a very good mechanism for the use of abstract categories. Is not an abstract example, can only be made available to a derived class interface. Designers often use the abstract class to force programmers derived from the base class, so as to ensure that the new category includes a number of look forward to. PHP is not in the standard way, but: If you need the characteristics of the base class can be defined, and its constructor add "die" call, so that we can not guarantee that the base is an example of the now In each of the methods (interface) followed by "die" statement, so that if a programmer in the derived class does not cover method will lead to a mistake. And because PHP is not the type, you may need to recognize an object from your base class in the derived class, then added a category-based approach to the real identity of the type of justice (to return to some kind of identification id), and You receive the parameters of an object when the value of the check. Of course, if an evil bad programmers in the derived class in the coverage of this method does not work on, but the general problems found in the lazy programmers, and not on the evil programmer.
Of course, allows programmers to the base class can not see is a very good, as long as the interface to print out their work done on it. PHP is not in the destructor.
Heavy (with a different cover) in PHP does not support. In OOP, you can overload a way to achieve two or more methods with the same name, but a different number or type of parameters (which depends on the language). PHP is a loose type of language, so through the type of heavy-duty work, but through a number of different parameters to heavy also does not work.
OOP in heavy at times in the constructor is very good, so you can create objects in different ways (passing a different number of parameters). In PHP to achieve its techniques are:
<? Php
Class Myclass (
Function Myclass () (
$ Name = "Myclass". Func_num_args ();
$ This-> $ name ();
/ / Note that $ this-> name () are wrong, but here is a $ name will be called the method name
)
Function Myclass1 ($ x) (
Code;
)
Function Myclass2 ($ x, $ y) (
Code;
)
)
By category of additional processing, the use of this category is transparent to the user:
$ obj1 = new Myclass ('1 '); / / will call Myclass1
$ obj2 = new Myclass ('1 ','2'); / / will call Myclass2
This is sometimes very easy to use.

php连接数据库

一、连接数据库

PHP要对数据库进行操作,首先要做的是与数据库建立连接,通常我们使用mysql_connect函数进行数据库连接,该函数需要指定数据库的地址,用户名及密码。

$host = ‘localhost‘;//服务器名称

$user = ‘code1‘;//用户名

$pass = ‘‘;//密码

$link = mysql_connect($host, $user, $pass);

PHP连接数据库的方式类似于直接在命令行下通过进行连接,类似:mysql -hlocalhost -ucode1 -p,当连接成功以后,我们需要选择一个操作的数据库,通过mysql_select_db函数来选择数据库:

mysql_select_db(‘code1‘);

通常我们会先设置一下当前连接使用的字符编码,一般的我们会使用utf8编码,代码如下:

mysql_query("set names ‘utf8‘");

通过上面的步骤,我们就与数据库建立了连接,可以进行数据操作了。

二、执行MySQL查询

在数据库建立连接以后就可以进行查询,采用mysql_query加sql语句的形式向数据库发送查询指令。

$res = mysql_query(‘select * from user limit 1‘);

对于查询类的语句会返回一个资源句柄(resource),可以通过该资源获取查询结果集中的数据。

$row = mysql_fetch_array($res); var_dump($row);

默认的,PHP使用最近的数据库连接执行查询,但如果存在多个连接的情况,则可以通过参数指令从那个连接中进行查询。

$link1 = mysql_connect(‘127.0.0.1‘, ‘code1‘, ‘‘);

$link2 = mysql_connect(‘127.0.0.1‘, ‘code1‘, ‘‘, true); //开启一个新的连接

$res = mysql_query(‘select * from user limit 1‘, $link1); //从第一个连接中查询数据

三、插入数据

使用mysql_query进行数据查询以后,那么类似的,插入数据其实也是通过执行一个sql语句来实现,例如:

$sql = "insert into user(name, age, class) values(‘李四‘, 18, ‘高三一班‘)";

mysql_query($sql); //执行插入语句

通常数据都是存储在变量或者数组中,因此sql语句需要先进行字符串拼接得到。

$name = ‘李四‘;

$age = 18; $class = ‘高三一班‘;

$sql = "insert into user(name, age, class) values(‘$name‘, ‘$age‘, ‘$class‘)";

mysql_query($sql); //执行插入语句

在mysql中,执行插入语句以后,可以得到自增的主键id,通过PHP的mysql_insert_id函数可以获取该id。

$uid = mysql_insert_id();

这个id的作用非常大,通常可以用来判断是否插入成功,或者作为关联ID进行其他的数据操作。

四、获得查询结果

PHP有多个函数可以获取数据集中的一行数据,最常用的是mysql_fetch_array,可以通过设定参数来更改行数据的下标,默认的会包含数字索引的下标以及字段名的关联索引下标。

$sql = "select * from user limit 1";

$result = mysql_query($sql);

$row = mysql_fetch_array($result);

可以通过设定参数MYSQL_NUM只获取数字索引数组,等同于mysql_fetch_row函数,如果设定参数为MYSQL_ASSOC则只获取关联索引数组,等同于mysql_fetch_assoc函数。

$row = mysql_fetch_row($result);

$row = mysql_fetch_array($result, MYSQL_NUM); //这两个方法获取的数据是一样的

$row = mysql_fetch_assoc($result);

$row = mysql_fetch_array($result, MYSQL_ASSOC);

如果要获取数据集中的所有数据,我们通过循环来遍历整个结果集。

五、查询分页数据 

在实际应用中,我们并不希望一次性获取数据表中的所有数据,那样性能会非常的低,因此会使用翻页功能,每页仅显示10条或者20条数据。

通过mysql的limit可以很容易的实现分页,limit m,n表示从m行后取n行数据,在PHP中我们需要构造m与n来实现获取某一页的所有数据。

假定当前页为$page,每页显示$n条数据,那么m为当前页前面所有的数据,既$m = ($page-1) * $n,在知道了翻页原理以后,那么我们很容易通过构造SQL语句在PHP中实现数据翻页。

$page = 2;

$n = 2;

$m = ($page - 1) * $n;

$sql = "select * from user limit $m, $n";

$result = mysql_query($sql); //循环获取当前页的数据

$data = array();

while ($row = mysql_fetch_assoc($result))

{

$data[] = $row;

}

在上面的例子中,我们使用了$m与$n变量来表示偏移量与每页数据条数,但我们推荐使用更有意义的变量名来表示,比如$pagesize, $start, $offset等,这样更容易理解,有助于团队协作开发。

六、更改与删除数据

数据的更新与删除相对比较简单,只需要构建好相应的sql语句,然后调用mysql_query执行就能完成相应的更新与删除操作。

$sql = "update user set name = ‘曹操‘ where id=2 limit 1";

if (mysql_query($sql))

{

echo ‘更新成功‘;

}

同样的删除可以使用类似以下的代码:

$sql = "delete from user where id=2 limit 1";

if (mysql_query($sql))

{

echo ‘删除成功‘;

}

对于删除与更新操作,可以通过mysql_affected_rows函数来获取更新过的数据行数,如果数据没有变化,则结果为0。

$sql = "update user set name = ‘曹操‘ where id=2 limit 1";

if (mysql_query($sql))

{

echo mysql_affected_rows();

}

 七、关闭数据库连接

当数据库操作完成以后,可以使用mysql_close关闭数据库连接,默认的,当PHP执行完毕以后,会自动的关闭数据库连接。

mysql_close();

虽然PHP会自动关闭数据库连接,一般情况下已经满足需求,但是在对性能要求比较高的情况下,可以在进行完数据库操作之后尽快关闭数据库连接,以节省资源,提高性能。

在存在多个数据库连接的情况下,可以设定连接资源参数来关闭指定的数据库连接。

$link = mysql_connect($host, $user, $pass);

mysql_close($link);

 

 

 

 

 

 

 

 

 

 

 

 

以上是关于php做的网站 连接mysql数据库 效率问题的主要内容,如果未能解决你的问题,请参考以下文章

PHP连接远端mysql很慢,要5-10秒,修改了my.cnf配置文件还是没用

远程连接mysql数据库很慢,修改了my.ini配置文件,[mysqld]下加了skip-name-resolve并重启也没有用

php中使用mysqli和pdo扩展,测试连接mysql数据库的效率。

PHP网站怎么连接到数据库?

php使用mysqli和pdo扩展,测试对比mysql数据库的执行效率完整示例

PHP网站连接数据库