Table of Contents
1. PHP connects to MySQL server" >1. PHP connects to MySQL server
mysql_connect()" >mysql_connect()
Basic syntax" >Basic syntax
is not good. Use the @" > characters are not added, a system error will be reported. You can see the error message below, which contains a lot of user information. Security is not good. Use the @
Description: Output a prompt message and stop the script from continuing to run. " > Description: Output a prompt message and stop the script from continuing to run.
" >Syntax: void exit([$msg])
" >Syntax: mysql_error()
" >include file errors, but cannot be used in function definitions or class definitions Before.
Syntax" >Syntax
Description: Select the database currently to be operated" >Description: Select the database currently to be operated
Parameters: " >Parameters:
Character set" > Send a request to the MySQL server or return the data of the request result Character set
" >Syntax
. " >Description: Send a MySQL query.
Parameters: " >Syntax: resource mysql_query (string $query [, resource $link])Parameters:
操作" >操作
5. 从结果集中取出一行数据" >5. 从结果集中取出一行数据
1. mysql_fetch_row()" >1. mysql_fetch_row()
语法" >语法
执行结果" >执行结果
2. mysql_fetch_array()" >2. mysql_fetch_array()
3. mysql_fetch_assoc()" >3. mysql_fetch_assoc()
附:完整PHP代码" >附:完整PHP代码
Home Backend Development PHP Tutorial Detailed explanation of operating MySQL database with PHP (1)

Detailed explanation of operating MySQL database with PHP (1)

Mar 25, 2017 am 09:41 AM


1. PHP connects to MySQL server

mysql_connect()

Basic syntax

  • Description: PHP connects to MySQL server

  • Syntax: resource $link = mysql_connect($hostname, $username, $password)

  • Parameters:

    • $hostname: It is the domain name or IP address of the MySQL server, and you can also add the port number (3306). For example: localhost:3306

    • #$username: is the username of the MySQL server. For example: root

    • #$password: is the user password of the MySQL server.

  • Return value: If the execution is successful, a resource identifier is returned. If the execution fails, return FALSE If the

  • @

characters are not added, a system error will be reported. You can see the error message below, which contains a lot of user information. Security is not good. Use the @

character to block this system error and improve security.

<?php

ini_set(display_errors, 1); //设置错误为:显示

//0.数据库配置信息
$db_host = &#39;loca1lhost&#39;;
$db_user = &#39;root&#39;;
$db_pwd = &#39;yeoman&#39;;

//1.PHP连接MySQL服务器
$link = @mysql_connect($db_host, $db_user, $db_pwd); //@用于屏蔽系统错误

//如果连接失败,则输出错误信息,并中止程序运行
if(!$link){
    echo "PHP连接MySQL失败!".mysql_error();
    exit(); //中止程序继续向下运行
}

?>
Copy after login
Otherfunctionsand symbols

##exit()

Description: Output a prompt message and stop the script from continuing to run.

Syntax: void exit([$msg])

Parameters: $msg is optional. If omitted, only the script is aborted.
  • Example: exit("PHP connection error")
  • ##mysql_error()
  • Description: Returns the text error message when the last MySQL execution failed.

Syntax: mysql_error()

##Shielding system errors@
  • Description:

    @
Can shield various function call errors, or

include file errors, but cannot be used in function definitions or class definitions Before.

  • 2. Select MySQL database

    mysql_select_db

    ()

Syntax

Description: Select the database currently to be operated

Syntax: bool mysql_select_db ( string $database_name [, resource $link ] )

Parameters:

  • $database_name: Specify the name of the database to be selected.
  • $link: Optional. Specifies the currently active connection. If omitted, the
  • last


    open active connection will be used.

    • Return value: If the database selection is successful,

    • TRUE
    • will be returned. If database selection fails, FALSE is returned.

  • Operation

    Warning: mysql_connect() [<a href=&#39;function.mysql-connect&#39;>function.mysql-connect</a>]: 
    Unknown MySQL server host &#39;local1host&#39; (0) in /Applications/MAMP/htdocs/php_test/php_mysql.php on line 17
    Copy after login
    3. Set the data character set returned by MySQL

Send a request to the MySQL server or return the data of the request result Character set

.

<?php

//0.数据库配置信息
$db_name = &#39;yeoman92&#39;;

//2.选择当前数据库
if(!mysql_select_db($db_name, $link)){
    echo "选择数据库{$db_name}失败!".mysql_error();
    exit();
}

?>
Copy after login
4. Execute the MySQL statement

##mysql_query()

Syntax

Description: Send a MySQL query.

  • Add records: $query = "INSERT INTO news(title,content) VALUES('title', 'content')"

  • Delete records: $query = “DELETE FROM news WHERE id=10”

  • Modify record: $query = “UPDATE news SET title = ‘New title’, content = ‘New content’ WHERE id= 80"

    • Query record: $query = "SELECT * FROM news WHERE id<100"
    • $query:指要发送的SQL语句。

    • $link:可选项。指上一次打开的活动连接。

  • 返回值:

    • 结果集也是一个资源标识符,是到MySQL数据的一个引用地址

    • 如果执行SELECT、SHOW、DESCRIBE命令,成功时返回结果集,失败时返回FALSE。

    • 如果执行其它的SQL语句,执行成功返回TRUE,执行失败返回FALSE。

  • 举例:

    • $result = mysql_query(“SELECT * FROM news WHERE id<100”)

    • $result = mysql_query(“DELETE * FROM news WHERE id=100”)

操作

//4.执行SQL查询:向MySQL服务器发出查询的请求$
sql = &#39;SELECT * FROM 007_news WHERE id<100&#39;;
$result = mysql_query($sql, $link);
Copy after login

5. 从结果集中取出一行数据

1. mysql_fetch_row()

语法

  • 描述:从结果集中取得一行作为枚举数组。

  • 语法:array mysql_fetch_row ( resource $result )

  • 参数:$result是结果集变量。

  • 返回值:返回一个枚举数组,也就是从0开始的正整数下标。这里的下标,是与表的字段下标是对应的。

  • 举例:$arr = mysql_fetch_row($result)

操作

//5.取出一条记录作为枚举数组返回
$arr = mysql_fetch_row($result);echo "<pre class="brush:php;toolbar:false">";
print_r($arr);echo "
";
Copy after login

执行结果

Array(
    [0] => 17
    [1] => 1
    [2] => cctv中学生信息化教学实验基地共建工程在京启动
    [3] => admin
    [4] => 中小学课外辅导网
    [5] => 
    [6] => 
    [7] => 50
    [8] => 
    [9] => 52
    [10] => 1339340691)
Copy after login

2. mysql_fetch_array()

  • 描述:从结果集中取出一行,作为混合数组返回。

  • 语法:array mysql_fetch_array ( resource $result [, int $result_type ] )

  • 参数:

    • MYSQL_BOTH:默认的。也就是两种下标都存在。

    • MYSQL_ASSOC:只有字符下标的数组。相当于mysql_fetch_assoc()的功能。

    • MYSQL_NUM:只有整数下标的数组。相当于mysql_fetch_row()的功能。

    • 以上三个参数是常量,系统常量必须全大写。

    • $result:是指结果集变量。

    • $result_type:是指返回的数组的类型。取值:MYSQL_BOTH、MYSQL_ASSOC、MYSQL_NUM

  • 返回值:返回一个数组,至于是什么数组,取决于第二个参数。

  • 举例:

    • $arr = mysql_fetch_array($result) //混合数组

    • $arr = mysql_fetch_array($result , MYSQL_ASSOC ) //关联数组

    • $arr = mysql_fetch_array($result , MYSQL_NUM) //枚举数组

3. mysql_fetch_assoc()

  • 描述:从结果集中取一行,以关联数组返回。

  • 语法:array mysql_fetch_assoc(resource $result)

  • 举例:$arr = mysql_fetch_assoc($result)

附:完整PHP代码

<?php

ini_set(display_errors, 1); //设置错误为:显示

//0.数据库配置信息
$db_host = &#39;localhost&#39;;
$db_user = &#39;root&#39;;
$db_pwd = &#39;yeoman&#39;;
$db_name = &#39;yeoman92&#39;;

//1.PHP连接MySQL服务器
$link = @mysql_connect($db_host, $db_user, $db_pwd); //@用于屏蔽系统错误

//如果连接失败,则输出错误信息,并中止程序运行
if(!$link){
    echo "PHP连接MySQL失败!".mysql_error();
    exit(); //中止程序继续向下运行
}

//2.选择当前数据库
if(!mysql_select_db($db_name, $link)){
    echo "选择数据库{$db_name}失败!".mysql_error();
    exit();
}

//3.设置MySQL返回的数据字符集
mysql_query("set names utf8");

//4.执行SQL查询:向MySQL服务器发出查询的请求
$sql = &#39;SELECT * FROM 007_news WHERE id<100&#39;;
$result = mysql_query($sql, $link);

//5.取出一条记录作为枚举数组返回
$arr = mysql_fetch_row($result);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr);
echo "
"; ?>
Copy after login

The above is the detailed content of Detailed explanation of operating MySQL database with PHP (1). For more information, please follow other related articles on the PHP Chinese website!

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)

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.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles