Home Backend Development PHP Tutorial PHP脚本数据库功能详解(上)

PHP脚本数据库功能详解(上)

Jun 01, 2016 pm 02:30 PM

在当前互联网发展迅速、电子商务网站层出不穷的形势下,对网站开发的效率和质量提出了越来越高的要求。

  对于大型和结构复杂、内容繁多的网站,都要实现网站的动态化和方便的管理。数据管理离不开数据库系统的支持。而衡量一种CGI语言的重要标志,就是它对后台数据库的访问能力、效率等。

  而目前流行的php脚本语言,它的新特性给我们带来了新的感觉。它支持以面向对象的方式进行设计开发。同时,为了满足网页独特的需要,用模板、xml支持等带来了网站开发的新方法。在语言结构上,PHP具有类似于C++语言的结构,并引入了类的概念,简化了开发。

  PHP还具有强大的数据库支持能力。我们这里就通过实例,首先介绍PHP访问数据库的一般流程,然后通过文件的数据库存储介绍PHP访问数据库的一种高级应用。最后通过数据库类的使用实例,介绍真正实用高效的数据库开发方法。


  图1

  PHP数据库功能简介
  PHP提供对10余种常见数据库的支持,如Oracle、dBase、Informix、SQL Server、Sysbase、MySQL等。正是由于广泛的数据库支持,才拓展了PHP的应用范围, 使得各种应用都可以利用PHP进行开发。

  在各种数据库中,MySQL由于其免费、跨平台、使用方便、访问效率较高,获得了很大的应用。很多中心型网站都使用PHP+MySQL这一最佳搭档。

  Oracle是典型的大型数据库应用系统。如果你设计的网站数据量大,性能、效率要求高的话,Oracle是个不错的选择。

  在Win32平台上,SQL Server占有较大的市场。PHP可以访问SQL Server。

  PHP对各种数据库的访问方法进行封装,针对不同数据库系统的函数也很相似,增加了使用的方便性。

  下面,我们将以一个简单的人才信息交流中心(见图1)为例子,编程实现个人简历的在线提交、浏览等功能,讲述PHP数据库操作的全过程。数据库采用最常用的MySQL数据库。

  PHP数据库操作基本步骤
  我们将在本地机器创建名为ResumeDB的数据库,数据库中有名为Resume的表。表中存储个人简历的编号、人员名称、个人简介,以及Word格式的简历文件等。

  1.数据库的创建

  切换至/usr/local/mysql/bin目录,在命令行,执行以下语句创建数据库:

  ./mysqladmin-u root-p create ResumeDB

  Enter password:

  在提示后输入密码。如果数据库是第一次使用,默认的密码为空,直接回车即可。

  然后创建保存个人简历的表。

  创建文本文件Resume.sql,内容如下:

   use ResumeDB;

  CREATE TABLE Resume (

   ID tinyint(4) NOT NULL auto_increment,

   Name varchar(10) NOT NULL,

   Intro varchar(255),

   ResuFile longblob,

   PRIMARY KEY (ID),

   KEY ID (ID)

  );

  将其放到My的可执行目录/usr/local/mysql/bin下,执行如下命令:

  ./mysql-u root-p〈 Resume.sql

   Enter password:

  输入数据库密码后,表Resume自动创建成功。其中,ResuFile字段为longbolb型,用来存储二进制的Word文档。

  2.数据库访问流程

  PHP对数据库的访问一般包括下列步骤:连接数据库系统→选择数据库→执行SQL语句→关闭结果集→关闭数据库连接→结束。

  (1) 连接数据库

  连接数据库是建立用户程序到数据库系统的对话通道的过程。连接MySQL数据库的语句如下:

  〈?

  $LinkID=@mysql_connect("localhost", "root" , "") or die("不能连接到数据库服务器!可能是数据库服务器没有启动,或者用户名密码有误!");

  ?〉

  其中,函数mysql_connect()用于与数据库服务器建立连接。三个参数分别为:数据库服务器的主机名(也可以是ip)、数据库用户名和用户密码。函数返回值用于表示这个数据库连接。

  从这个命令可以看到,我们可以指定并非本机的机器名作为数据库服务器。这样,就为数据的异地存放、数据库的安全隔离提供了可能。外界用户往往具有WWW服务器的直接访问权限,如果数据库系统直接放置在WWW服务器上,就可能会带来安全隐患。而如果将数据库系统放置于一台防火墙后面的计算机上,PHP可以通过局域网访问数据库,而局域网内部的计算机对外部是不可见的。这样,就保证了数据库不受外来攻击的可能。

  函数前面的“@”符号,用于限制这个命令的出错信息的显示。如果函数调用出错,将执行or后面的语句。die( )函数表示向用户输出引号中的内容后,程序终止执行。这样做是为了防止数据库连接出错时,用户看到一堆莫名其妙的专业名词,而是提示定制的出错信息。不过在调试的时候,我们还是可以不要屏蔽出错信息,免得出错后,难以找到到底哪里有问题。

  (2) 数据库选择

  一个数据库系统可以包含多个数据库。在建立了和数据库服务器的连接后,我们就要告诉系统,我们将要用到的数据库是哪个。选择数据库的命令如下:

  〈?

  @mysql_select_db("ResumeDB",$LinkID) or die("选择数据库出错,可能是您指定的数据库不存在!");

  ?〉

  选择数据库时,要提供的参数是数据库的名称、和服务器连接号。

  当我们只使用一台数据库服务器时,$LinkID可以省略,系统自动查找最近的一个数据库连接然后使用它。但是,当你要实现大型站点的时候,必不可少的要遇到多主机、多数据库系统的情况。这时,数据库连接参数就不能省略了。

  (3) 数据库访问

  好了,我们已经建立了到数据库的连接,选定了数据库,接下了来的一切就是执行SQL语句了。SQL语句的易用而强大的功能,将完成我们绝大部分的数据库操作动作。

  我们可以首先向数据库里写入一条个人信息记录,然后把它显示出来。

  〈?

  $Name= "OpenBall"; //实际操作中,$Name、$Intro为从浏览器表单传来的值

  $Intro = "OpenBall的个人简介……";

  $query = "insert into Resume(Name,Intro) values('$Name', '$Intro')"; //生成SQL语句

  $result = @mysql_query("$query",$LinkID); //执行

  if(! $result)

   echo "数据插入失败!";

  $query= "select ID,Name,Intro from Resume"; //生成SQL语句

  $result = mysql_query($query,$LinkID); //执行,结果集保存到变量$result中

  $num= mysql_num_rows($result); //取得查询返回的记录行数

  if($num == 0)

  {

   echo "没有找到任何记录";

   exit();

  }

  while($row=mysql_fetch_array($result)) //取结果集的下一行数据到数组$row中

  {

   echo $row["ID"]." ".$row["Name"]." ".$row["Intro"]."〈br〉";

  //以字段名为索引访问数组变量的值

  }

  ?〉

  上面的操作,共执行了两次数据库操作。第一次为插入操作,第二次为查询操作。程序首先插入当前用户的一天记录,然后,显示所有数据库中的个人情况。

  (4)资源释放

  操作的最后,是释放结果集,释放结果集和数据库连接资源。

  〈?

  @mysql_free_result($result);

  @mysql_close($LinkID);

  ?〉

  如果在多个网页中都要频繁进行数据库访问,则可以建立与数据库服务器的持续连接来提高效率。因为每次与数据库服务器的连接需要较长的时间和较大的资源开销,持续的连接相对来说会更有效。

  建立持续连接的方法,就是在数据库连接的时候,调用函数mysql_pconnect()代替mysql_connect() 。建立的持续连接在本程序结束时,不需要调用mysql_close()来关闭。下次程序在此执行mysql_pconnect()时,系统自动直接返回已经建立的持续连接的ID号,而不再去真的连接数据库。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles