Home php教程 php手册 php开发中常用到的数据库操作方法函数

php开发中常用到的数据库操作方法函数

Jun 13, 2016 am 10:08 AM
php function develop operate Tutorial database method of

今天把在php教程开发中常用到的数据库教程操作方法函数总结分析一下了,希望有兴趣的朋友可以参考一下。
一、数据库操作
1. 连接MYSQL数据
mysql教程_connect()

提示和注释
注释:脚本一结束,到服务器的连接就被关闭,除非之前已经明确调用 mysql_close() 关闭了。
提示:要创建一个持久连接,请使用 mysql_pconnect() 函数。
例子

$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// 一些代码...

mysql_close($con);
?>

e.g.

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die(‘ www.zhutiai.com Unable to connect, please check connection paremeters’);


 2. 选择数据库
mysql_select_db()
连接上数据库后,PHP默认选择的数据库未必是我们后面操作中需要的数据库,为确保数据库选择正确,一般在数据库连接语句后面还要加上数据库选择语句。

mysql_select_db() 函数设置活动的 MySQL 数据库。
如果成功,则该函数返回 true。如果失败,则返回 false。
语法
mysql_select_db(database,connection)
参数 描述
database 必需。规定要选择的数据库。
connection 可选。规定 MySQL 连接。如果未指定,则使用上一个连接。

e.g.
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
3. 执行SQL语句
mysql_query()
该函数将SQL语句发送到当前活动的数据库并执行语句,返回结果。

定义和用法
mysql_query() 函数执行一条 MySQL 查询。
语法
mysql_query(query,connection)
参数 描述
query 必需。规定要发送的 SQL 查询。注释:查询字符串不应以分号结束。
connection 可选。规定 SQL 连接标识符。如果未规定,则使用上一个打开的连接。
说明
如果没有打开的连接,本函数会尝试无参数调用 mysql_connect() 函数来建立一个连接并使用之。
返回值
mysql_query() 仅对 SELECT,SHOW,EXPLAIN 或 DESCRIBE 语句返回一个资源标识符,如果查询执行不正确则返回 FALSE。
对于其它类型的 SQL 语句,mysql_query() 在执行成功时返回 TRUE,出错时返回 FALSE。
非 FALSE 的返回值意味着查询是合法的并能够被服务器执行。这并不说明任何有关影响到的或返回的行数。很有可能一条查询执行成功了但并未影响到或并未返回任何行。

e.g.

$query = “SELECT * FROM $table”
$result = mysql_query($query, $db) or die(mysql_error($db));


4. 关闭数据库
mysql_close()
该函数用于关闭不需要继续活跃的数据库,但该方法不是必须的,一般PHP会自动关闭不继续活跃的数据库。
e.g.
mysql_close($db);
5. 释放SQL结果
mysql_free_result()
该函数用于释放mysql_query()执行结果占用的内存,该函数很少被调用,除非result很大,占用太多内存;一般在PHP脚本执行结束之后很自动释放占用的内存。
e.g
ysql_free_result() 函数释放结果内存。
如果成功,则返回 true,如果失败,则返回 false。
语法
mysql_free_result(data)
参数 描述
data 必需。要释放的结果标识符。该结果标识符是从 mysql_query() 返回的结果。
提示和注释
注释:mysql_free_result() 仅需要在考虑到返回很大的结果集时会占用多少内存时调用。在脚本结束后所有关联的内存都会被自动释放。
例子

$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("test_db",$con);

$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_row($result));

// 释放内存

 

mysql_free_result($result);

$sql = "SELECT * from Customers";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_row($result));

mysql_close($con);
?>

二、SQL执行结果操作
1. 返回执行结果中的一行
mysql_fetch_row()
返回执行结果的当前行的数值数组,执行这个函数后,结果指向下一行。
e.g.
$row = mysql_fetch_row($result);
处理执行结果一般放在while循环中,遍历每一行
e.g.
while($row = mysql_fetch_row($result))
{……}
2. mysql_fetch_row()的替代方法
mysql_fetch_array()
mysql_fetch_assoc()
mysql_fetch_array()返回键值对数组,键为查询的table的列名;
mysql_fetch_assoc()返回结果时可以先排序(如果为可选参数赋值),相当于mysql_fetch_array()+MYSQL_ASSOC
3. 执行结果的字段(列)属性
mysql_fetch_field()
eg.
mysql_fetch_field() 函数从结果集中取得列信息并作为对象返回。
mysql_fetch_field() 可以用来从查询结果中取得字段的信息。如果没有指定字段偏移量,则提取下一个尚未被 mysql_fetch_field() 取得的字段。
该函数返回一个包含字段信息的对象。
被返回的对象的属性为:
name - 列名
table - 该列所在的表名
max_length - 该列最大长度
not_null - 1,如果该列不能为 NULL
primary_key - 1,如果该列是 primary key
unique_key - 1,如果该列是 unique key
multiple_key - 1,如果该列是 non-unique key
numeric - 1,如果该列是 numeric
blob - 1,如果该列是 BLOB
type - 该列的类型
unsigned - 1,如果该列是无符号数
zerofill - 1,如果该列是 zero-filled
语法
mysql_fetch_field(data,field_offset)
参数 描述
data 必需。要使用的数据指针。该数据指针是从 mysql_query() 返回的结果。
field_offset 必需。规定从哪个字段开始。0 指示第一个字段。如果未设置,则取回下一个字段。
提示和注释
注释:本函数返回的字段名是区分大小写的。
例子

$con = mysql_connect("localhost", "hello", "321");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("test_db",$con);

$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);

while ($property = mysql_fetch_field($result))
  {
  echo "Field name: " . $property->name . "
";
  echo "Table name: " . $property->table . "
";
  echo "Default value: " . $property->def . "
";
  echo "Max length: " . $property->max_length . "
";
  echo "Not NULL: " . $property->not_null . "
";
  echo "Primary Key: " . $property->primary_key . "
";
  echo "Unique Key: " . $property->unique_key . "
";
  echo "Mutliple Key: " . $property->multiple_key . "
";
  echo "Numeric Field: " . $property->numeric . "
";
  echo "BLOB: " . $property->blob . "
";
  echo "Field Type: " . $property->type . "
";
  echo "Unsigned: " . $property->unsigned . "
";
  echo "Zero-filled: " . $property->zerofill . "

";
  }

mysql_close($con);
?>

4. 查询数据库中的表名
我们要显示所有的表就会用到mysql_list_tables用法语法来操作,
mysql_list_tables 语法

mysql_list_tables()
e.g.
$db_name = MYSQL_DB;
$result = mysql_list_tables($db_name);
echo “数据库中包含如下表:”;
while ($row = mysql_fetch_row($result))
{
echo $row[0];
}


5. 查询数据库的列名(字段名)

esource mysql_list_fields ( string database_name, string table_name [, resource link_identifier] )

mysql_list_fields() 取得给定表名的信息。参数是数据库名和表名。返回一个结果指针,可以用于 mysql_field_flags(),mysql_field_len(),mysql_field_name() 和 mysql_field_ty

mysql_list_fields()
e.g.
$fields = mysql_list_fields($db_name,$table);
$columns = mysql_num_fields($fields);
for ($i = 0; $i echo  mysql_field_name($fields, $i);


三、其他函数
1. mysql_num_rows()

mysql_num_rows() 函数返回结果集中行的数目。
语法
mysql_num_rows(data)
参数 描述
data 必需。结果集。该结果集从 mysql_query() 的调用中得到。
说明
mysql_num_rows() 返回结果集中行的数目。此命令仅对 SELECT 语句有效。要取得被 INSERT,UPDATE 或者 DELETE 查询所影响到的行的数目,用 mysql_affected_rows()。
返回执行结果的行数。
e.g.

$num = mysql_num_rows($result);


2. mysql_num_fields()
返回执行结果的列数(字段数)。
e.g. $num = mysql_num_fields($result);
3.mysql_set_charset()
设置执行结果的编码,防止在网页中显示中文时乱码。
e.g.

$query = “select * from $table_name”;
mysql_query(‘set names utf8′);
$result = mysql_query($query, $db) or die(mysql_error($db));


注:
1. 文中大写代码为预定义的内容,如define(MYSQL_HOST,  ‘localhost’);

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles