search
HomeBackend DevelopmentPHP TutorialDetailed explanation of operating MySQL database with PHP (1)


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(); //中止程序继续向下运行
}

?>
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
    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();
}

?>
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
    • $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”)

操作

//4.执行SQL查询:向MySQL服务器发出查询的请求$
sql = &#39;SELECT * FROM 007_news WHERE id<100&#39;;
$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 = &#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 "
"; ?>

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
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

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

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

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

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

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.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

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

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

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

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

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.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

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

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

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

See all articles

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

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

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

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool