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 = 'loca1lhost';
$db_user = 'root';
$db_pwd = 'yeoman';
//1.PHP连接MySQL服务器
$link = @mysql_connect($db_host, $db_user, $db_pwd); //@用于屏蔽系统错误
//如果连接失败,则输出错误信息,并中止程序运行
if(!$link){
echo "PHP连接MySQL失败!".mysql_error();
exit(); //中止程序继续向下运行
}
?>
Otherfunctionsand symbols
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: @
include file errors, but cannot be used in function definitions or class definitions Before.
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,
TRUEwill be returned. If database selection fails, FALSE is returned.
Operation
Warning: mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Unknown MySQL server host 'local1host' (0) in /Applications/MAMP/htdocs/php_test/php_mysql.php on line 17
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 = 'yeoman92';
//2.选择当前数据库
if(!mysql_select_db($db_name, $link)){
echo "选择数据库{$db_name}失败!".mysql_error();
exit();
}
?>
4. Execute the MySQL statement
##mysql_query()
Syntax
Description: Send a MySQL query.
Syntax: resource mysql_query (string $query [, resource $link])Parameters:
-
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:指要发送的SQL语句。
$link:可选项。指上一次打开的活动连接。
返回值:
结果集也是一个资源标识符,是到MySQL数据的一个引用地址。
如果执行SELECT、SHOW、DESCRIBE命令,成功时返回结果集,失败时返回FALSE。
如果执行其它的SQL语句,执行成功返回TRUE,执行失败返回FALSE。
举例:
$result = mysql_query(“SELECT * FROM news WHERE id
$result = mysql_query(“DELETE * FROM news WHERE id=100”)
- Query record: $query = "SELECT * FROM news WHERE id
操作
//4.执行SQL查询:向MySQL服务器发出查询的请求$ sql = 'SELECT * FROM 007_news WHERE id<100'; $result = mysql_query($sql, $link);
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 "";
执行结果
Array( [0] => 17 [1] => 1 [2] => cctv中学生信息化教学实验基地共建工程在京启动 [3] => admin [4] => 中小学课外辅导网 [5] => [6] => [7] => 50 [8] => [9] => 52 [10] => 1339340691)
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 = 'localhost'; $db_user = 'root'; $db_pwd = 'yeoman'; $db_name = 'yeoman92'; //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 = 'SELECT * FROM 007_news WHERE id<100'; $result = mysql_query($sql, $link); //5.取出一条记录作为枚举数组返回 $arr = mysql_fetch_row($result); echo "<pre class="brush:php;toolbar:false">"; print_r($arr); echo ""; ?>
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!

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
