Home php教程 php手册 PHP操作mysql函数详解,mysql和php交互函数

PHP操作mysql函数详解,mysql和php交互函数

Jun 13, 2016 pm 12:10 PM
connect mysql php interaction closure function and Establish operate Detailed explanation connect

1. 建立和关闭连接
1) mysql_connect()
resource mysql_connect([string hostname [:port][:/path/to/socket][,string username] [,string password]])
所有参数都是可选的
举例:
@mysql_connect(“localhost”, “user”, “password”)
or die(“Could not connect to mysql server!”);
注意,@符号表示禁止失败尝试导致的任何错误信息,用户将看到的是die()中指定的错误信息.
注意,当与多个mysql进行连接时,必须指定每个连接的链接ID,如下:
$link1 = @mysql_connect(“server1″, “user”, “password”)
or die(“Could not connect to mysql server!”);
$link2 = @mysql_connect(“server2″, “user”, “password”)
or die(“Could not connect to mysql server!”);
2) mysql_pconnect()
resource mysql_pconnect([string hostname [:port][:/path/to/socket][,string username] [,string password]])
与mysql_connect()不同的是:会首先查找现有链接,不存在时才创建.
注意,不需要显示关闭连接(mysql_close()),因为连接将放在池中,所以叫持久连接.
3) mysql_close()
boolean mysql_close([resource link_id])
关闭连接不是必须的,因为可以由mysql的垃圾回收来处理.
如果没有指定link_id,则关闭最近的链接.
2. 选择数据库
mysql_select_db()
boolean mysql_select_db(string db_name [, resource link_id])
3. 查询MySql
1) mysql_query()
resource mysql_query(string query [,resource link_id])
负责执行query.
2) mysql_db_query()
resource mysql_db_query(string database, string query [, resource link_id])
等价于mysql_select_db() + mysql_query(),从参数中就可以清楚的看出来.
4. 获取和显示数据
1) mysql_result()
mixed mysql_result(resource result_set, int row [,mixed field])
从result_set 的指定row 中获取一个field 的数据. 简单但是效率低.
举例:

复制代码 代码如下:


$link1 = @mysql_connect(“server1″, “webuser”, “password”)
or die(“Could not connect to mysql server!”);
@mysql_select_db(“company”) or die(“Could not select database!”);
$query = “select id, name from product order by name”;
$result = mysql_query($query);
$id = mysql_result($result, 0, “id”);
$name = mysql_result($result, 0, “name”);
mysql_close();


注意,上述代码只是输出结果集中的第一条数据的字段值,如果要输出所有记录,需要循环处理.

复制代码 代码如下:



for ($i = 0; $i {
$id = mysql_result($result, 0, “id”);
$name = mysql_result($result, 0, “name”);
echo “Product: $name ($id)”;
}


注意,如果查询字段名是别名,则mysql_result中就使用别名.
2) mysql_fetch_row()
array mysql_fetch_row(resource result_set)
从result_set中获取整行,把数据放入数组中.
举例(注意和list 的巧妙配合):

复制代码 代码如下:



$query = “select id, name from product order by name”;
$result = mysql_query($query);
while(list($id, $name) = mysql_fetch_row($result)) {
echo “Product: $name ($id)”;
}


3) mysql_fetch_array()
array mysql_fetch_array(resource result_set [,int result_type])
mysql_fetch_row()的增强版.
将result_set的每一行获取为一个关联数组或/和数值索引数组.
默认获取两种数组,result_type可以设置:
MYSQL_ASSOC:返回关联数组,字段名=>字段值
MYSQL_NUM:返回数值索引数组.
MYSQL_BOTH:获取两种数组.因此每个字段可以按索引偏移引用,也可以按字段名引用.
举例:

复制代码 代码如下:



$query = “select id, name from product order by name”;
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_BOTH)) {
$name = $row['name'];//或者 $name = $row[1];
$name = $row['id'];//或者 $name = $row[0];
echo “Product: $name ($id)”;
}


4) mysql_fetch_assoc()
array mysql_fetch_assoc(resource result_set)
相当于 mysql_fetch_array($result, MYSQL_ASSOC)
5) mysql_fetch_object()
object mysql_fetch_object(resource result_set)
和mysql_fetch_array()功能一样,不过返回的不是数组,而是一个对象.
举例:

复制代码 代码如下:



$query = “select id, name from product order by name”;
$result = mysql_query($query);
while($row = mysql_fetch_object($result)) {
$name = $row->name;
$name = $row->id;
echo “Product: $name ($id)”;
}


5. 所选择的记录和受影响的记录
1) mysql_num_rows()
int mysql_num_rows(resource result_set)
返回result_set中的行数.
注意,mysql_num_rows()只在确定select语句查询获得的记录数有效,如果要获取insert/updata/delete查询影响的记录数,需要使用mysql_affected_rows().
2) mysql_affected_rows()
int mysql_affected_rows([resource link_id])
获取insert/updata/delete查询影响的记录数
注意,不需要输入参数,默认使用最近建立的数据库连接的最近结果.可以使用可选参数link_id来选择数据库连接.
6. 获取数据库和表的信息
1) mysql_list_dbs()
resource mysql_list_dbs([resource link_id])
获取服务器上所有数据库名称.
举例:

复制代码 代码如下:


mysql_connect(“localhost”, “name”,”pwd”);
$dbs = mysql_list_dbs();
while (list($db) = mysql_fetch_row(dbs)) {
echo “$db
”;
}


注意,输出结果与使用的用户权限相关.
2) mysql_db_name()
string mysql_db_name(resource result_set, interger index)
获取在mysql_list_dbs()返回的result_set中位置为index的数据库名.
3) mysql_list_tables()
resource mysql_list_tables(string database [,resource link_id])
获取database中的所有表名.
4) mysql_tablename()
string mysql_tablename(resource result_set, interger index)
获取mysql_list_tables()返回的result_set中位置为index的表名.
在学习PHP的COM 和 .Net(Windows)函数的时候,发现了一个通过COM操作SQL SERVER的例子,查找了相关的资料,于是就有了这篇PHP连接ACCESS的文章,相信网上已经很多了,还是贴在这里吧。
我的机器环境:WIN2000,APACHE2,PHP Version 5.1.0RC1

复制代码 代码如下:


$conn = new COM(“ADODB.Connection”) or die(“Cannot start ADODB.Connection”);
$conn->Open(“Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\php5\\netBook.mdb”);
$rs = $conn->Execute(“select * from manage”); // 记录集
$num_columns = $rs->Fields->Count();
echo $num_columns . “
\n”;
for ($i=0; $i $fld[$i] = $rs->Fields($i);
}
$rowcount = 0;
while (!$rs->EOF) {
for ($i=0; $i {
echo htmlspecialchars($fld[$i]->value) . “\t”;
}
echo “
\n”;
$rowcount++; // rowcount 自增
$rs->MoveNext();
}
$rs->Close(); //关闭数据集
$conn->Close();
?>

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months 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)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

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.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

See all articles