Home php教程 php手册 PHP操作mysql函数详解,mysql和php交互函数_php入门_脚本之家

PHP操作mysql函数详解,mysql和php交互函数_php入门_脚本之家

Jun 06, 2016 pm 08:37 PM
mysql

PHP操作mysql函数详解,mysql和php交互函数实现代码,需要的朋友可以参考下。

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

See all articles