Home php教程 php手册 PHP连接数据库的方法(1)

PHP连接数据库的方法(1)

Jun 21, 2016 am 09:02 AM
echo mysql php

 

导读    

 
相信大家对PHP已经很熟悉了。PHP内置了几乎对世界上所有的数据库的支持,而不再需要重新扩充。所以有人说:不会用PHP调用数据库,等于没学PHP。下面是笔者根据本人的操作经验和大侠们的意见而得出的总结,希望能给初学者提供一些益处。  

 
相信大家对PHP已经很熟悉了。PHP内置了几乎对世界上所有的数据库的支持,而不再需要重新扩充。所以有人说:不会用PHP调用数据库,等于没学PHP。下面是笔者根据本人的操作经验和大侠们的意见而得出的总结,希望能给初学者提供一些益处。

 PHP
调用三种数据库的方法

 
本文比较详细的介绍PHP调用MySQLODBC以及ORACLE数据库。

 MySQL
是一个小巧灵珑的数据库服务器软件,对于中、小型应用系统是非常理想的。除了支持标准的ANSI SQL语句外,最重要的是,它还支持多种平台,而在Unix/Linux系统上,MySQL支持多线程运行方式,从而能获得相当好的性能。它和PHPApache一样,是属于开放源代码软件。其官方网站是:http://www.mysql.com,上面提供Windows,Linux,Unix版本的源代码的下载。

注意,MySQL访问函数都需要有相应的权限才能运行。常用的相关函数介绍如下:

(1)integer mysql_connect(
主机,用户名,口令);

此函数开始一个对指定主机上的MySQL数据库的连接。若该数据库位于一个不同地端口,则在主机名后加上冒号和端口号。所有参数均为可选的,缺省情况下分别对应为本地主机、用户正在执行的脚本名和空。主机可以是IP地址或域名。

在脚本执行结束时,连接被自动关闭,也可以用mysql_close提前关闭。

(2)boolean mysql_create_db(
数据库名);

创建一个数据库。注意必须用一个带有创建数据库许可权的帐号打开连接。

(3)boolean mysql_select_db(
数据库名,连接号);

选择缺省数据库。

(4)integer mysql_query(SQL
语句,连接号);

对指定数据库进行查询。如果SQL语句是select,则返回一个结果号,否则返回的值可以不理会。如果失败,返回false.

(5)array mysql_fetch_array(
结果号);

取出下一行,返回一个数组.可以用数字下标访问(第一个字段是下标 0),也可以用字符串下标访问(即使用各字段名)。如已取了最后一行,返回 false.

(6)mysql_fetch_row(
结果号);

返回一个矩阵代表结果集中一行的所有域。每次调用都会产生下一行,直到没有行剩下时返回false。每个域值都由一个从零开始的偏移量索引。这是从查询中获取结果的最快方法。

(7)integer mysql_num_rows(
结果号);

返回结果集中行的数目

(8)integer mysql_num_fields(
结果号);

返回结果集中域的数目。

(9)integer mysql_list_dbs();

向服务器查询数据库列表。它返回一个结果指针,该指针可用于mysql_fetch_row函数及类似函数。

(10)mysql_list_tables(
数据库名);

获取一个指向指定数据库的表单列表的结果指针。该结果指针可用于任何从结果集中获取行的函数。

(11)mysql_close(
连接号);

关闭对数据库的连接。连接必须是由mysql_connect打开的。该函数的使用不是严格必需的,因为在脚本结束时,所有非永久链路都会被自动关闭。

(12)mysql_pconnect(
主机,用户名,口令);

mysql_connect完全相似,但建立一个"永久连接",该连接一经建立永不关闭,即使使用mysql_close函数或程序执行完毕也不关闭.下一次试图建立永久连接时,系统如发现已存在一个永久连接,则直接返回该连接号而不重新创建。

下面是一个调用MYSQL数据库并分页显示的例子。



$pagesize = 5; //
每页显示5条记录

$host="localhost";

$user="user";

$password="psw";

$dbname="book"; //
所查询的库表名;

//
连接MySQL数据库

mysql_connect("$host","$user","$password") or die("
无法连接MySQL数据库服务器!");

$db = mysql_select_db("$dbname") or die("
无法连接数据库!");

$sql = "select count(*) as total from pagetest";//
生成查询记录数的SQL语句

$rst = mysql_query($sql) or die("
无法执行SQL语句:$sql "); //查询记录数

$row = mysql_fetch_array($rst) or die("
没有更多的记录!"); /取出一条记录

$rowcount = $row["total"];//
取出记录数

mysql_free_result($rst) or die("
无法释放result资源!"); //释放result资源

$pagecount = bcdiv($rowcount+$pagesize-1,$pagesize,0);//
算出总共有几页

if(!isset($pageno)) {

$pageno = 1; //
在没有设置pageno时,缺省为显示第1

}

if($pageno
$pageno = 1; //
pageno1小,则把它设置为1

}

if($pageno>$pagecount) {

$pageno = $pagecount; //
pageno比总共的页数大,则把它设置为最后一页

}

if($pageno>0) {

$href = eregi_replace("%2f","/",urlencode($PHP_SELF));//
$PHP_SELF转换为可以在URL上使用的字符串,这样的话就可以处理中文目录或中文文件名

if($pageno>1){//
显示上一页的裢接

echo "href
="" . $href . "?pageno=" . ($pageno-1) . "">上一页 ";

}

else{

echo "
上一页";

}

for($i=1;$ipageno;$i
++){

echo "href="" . $href . "?pageno=" . $i . "">" . $i . " ";

}

echo $pageno . " ";

for($i++;$ipagecount;$i++){

echo "href="" . $href . "?pageno=" . $i . "">" . $i . " ";

}

if($pagenopagecount){//显示下一页的裢接

echo "href
="" . $href . "?pageno=" . ($pageno+1) . "">下一页 ";

}

else{

echo "
下一页 ";

}

$offset = ($pageno-1) * $pagesize;//
算出本页第一条记录在整个表中的位置(第一条记录为0)

$sql = "select * from pagetest LIMIT $offset,$pagesize";//
生成查询本页数据的SQL语句

$rst = mysql_query($sql);//
查询本页数据

$num_fields = mysql_num_fields($rst);//
取得字段总数

$i = 0;

while($inum_fields
){//取得所有字段的名字

$fields[$i] = mysql_field_name($rst,$i);//
取得第i+1个字段的名字

$i++;

}

echo "

cellspacing="0" cellpadding="0">";//开始输出表格

echo "tr
>";

reset($fields);

while(list(,$field_name)=each($fields)){//显示字段名称

echo "th
>$field_nameth>";

}

echo "tr>";

while($row=mysql_fetch_array($rst)){//显示本页数据

echo "tr
>";

reset($fields);

while(list(,$field_name)=each($fields)){//显示每个字段的值

$field_value = $row[$field_name];



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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

Navicat cannot connect to MySQL/MariaDB/PostgreSQL and other databases Navicat cannot connect to MySQL/MariaDB/PostgreSQL and other databases Apr 08, 2025 pm 11:00 PM

Common reasons why Navicat cannot connect to the database and its solutions: 1. Check the server's running status; 2. Check the connection information; 3. Adjust the firewall settings; 4. Configure remote access; 5. Troubleshoot network problems; 6. Check permissions; 7. Ensure version compatibility; 8. Troubleshoot other possibilities.

How to execute sql in navicat How to execute sql in navicat Apr 08, 2025 pm 11:42 PM

Steps to perform SQL in Navicat: Connect to the database. Create a SQL Editor window. Write SQL queries or scripts. Click the Run button to execute a query or script. View the results (if the query is executed).

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

Navicat connects to database error code and solution Navicat connects to database error code and solution Apr 08, 2025 pm 11:06 PM

Common errors and solutions when connecting to databases: Username or password (Error 1045) Firewall blocks connection (Error 2003) Connection timeout (Error 10060) Unable to use socket connection (Error 1042) SSL connection error (Error 10055) Too many connection attempts result in the host being blocked (Error 1129) Database does not exist (Error 1049) No permission to connect to database (Error 1000)

See all articles