search
HomeBackend DevelopmentPHP TutorialChapter 16 PHP Operation MySQL_PHP Tutorial

Learning points:
1. Connect PHP to MySQL
2. Add, delete, modify and query
3. Other commonly used functions

If you already have extensive experience using PHP, SQL and MySQL, you can now
combine all these technologies together. The solid integration between PHP and MySQL is just one reason why many programmers have adopted it, and another reason is that it is so simple and convenient.

1. PHP connect to MySQL

Here, we fully use UTF-8 encoding.

Set the encoding of Zend Stduio: Window -> Preferences -> Workspace

Header settings to keep Firefox and IE encoding consistent:

<?<span php
</span><span header</span>('Content-Type:text/html; charset=utf-8'<span );
</span>?>

Connect to MySQL

<?<span php
</span><span $conn</span> = @<span mysql_connect</span>(DB_HOST,DB_USER,<span DB_PASSWORD) or
</span><span die</span>('数据库连接失败!错误信息:'.<span mysql_error</span><span ());
</span>?>

Database connection parameters can be stored as constants, so they cannot be modified and are safer.

<?<span php
</span><span define</span>('DB_USER','root'<span );
</span><span define</span>('DB_PASSWORD','yangfan'<span );
</span><span define</span>('DB_HOST','localhost'<span );
</span><span define</span>('DB_NAME' ,'school'<span );
</span>?>

Select the database you need

<?<span php
@</span><span mysql_select_db</span>(DB_NAME) or <span die</span>('数据库找不到!错误信息:'.<span mysql_error</span><span ());
</span>?>

Set the character set. If it is GBK, just set SET NAMES GBK directly

<?<span php
@</span><span mysql_query</span>('SET NAMES UTF8') or <span die</span>('字符集设置错误'<span );
</span>?>

Get record set

<?<span php
</span><span $query</span> = "SELECT * FROM grade"<span ;
</span><span $result</span> = @<span mysql_query</span>(<span $query</span>) or <span die</span>('<span SQL 语句有误!错误信息:
</span>'.<span mysql_error</span><span ());
</span>?>

Output a record

<?<span php
</span><span print_r</span>(<span mysql_fetch_array</span>(<span $result</span>,<span MYSQL_ASSOC));
</span>?>

Release result set resources

<?<span php
</span><span mysql_free_result</span>(<span $result</span><span );
</span>?>

Close database

<?<span php
</span><span mysql_close</span>(<span $conn</span><span );
</span>?>

2. Add, delete, modify and check

New data

<?<span php
</span><span $query</span> = "<span INSERT INTO grade (name,email,point,regdate) VALUE
('李炎恢','yc60.com@gmail.com',,NOW())</span>"<span ;
@</span><span mysql_query</span>(<span $query</span>) or <span die</span>('添加数据出错:'.<span mysql_error</span><span ());
</span>?>
Modify data

<?<span php
</span><span $query</span> = "UPDATE grade SET name='小可爱' WHERE id=6"<span ;
@</span><span mysql_query</span>(<span $query</span>) or <span die</span>('修改出错:'.<span mysql_error</span><span ());
</span>?>
Delete data

<?<span php
</span><span $query</span> = "DELETE FROM grade WHERE id=6"<span ;
@</span><span mysql_query</span>(<span $query</span>) or <span die</span>('删除错误:'.<span mysql_error</span><span ());
</span>?>
Show data

<?<span php
</span><span $query</span> = "SELECT id,name,email,point FROM grade"<span ;
</span><span $result</span> = @<span mysql_query</span>(<span $query</span>) or <span die</span>('查询语句出错:'.<span mysql_error</span><span ());
</span><span while</span> (!!<span $row</span> = <span mysql_fetch_array</span>(<span $result</span><span )) {
    </span><span echo</span> <span $row</span>['id'].'----'.<span $row</span>['name'].'----'.<span $row</span>['email'].'----'.<span $row</span>['point'<span ];
    </span><span echo</span> '<br />'<span ;
}
</span>?>

3. Other commonly used functions

mysql_fetch_row(): Get a row from the result set as an enumeration array

mysql_fetch_assoc(): Get a row from the result set as an associative array
mysql_fetch_array(): Get a row from the result set as an associative array, or numeric array , or both
mysql_fetch_lengths (): Get the length of each output in the result set
mysql_field_name(): Get the field name of the specified field in the result
mysql_num_rows(): Get the number of rows in the result set
mysql_num_fields(): Get the number of fields in the result set
mysql_get_client_info(): Get the MySQL client information
mysql_get_host_info(): Get the MySQL host information
mysql_get_proto_info(): Get the MySQL protocol information
mysql_get_server_info (): Get MySQL server information

Note: The article comes from Li Yanhui’s PHP video tutorial. This article is for communication only and may not be used for commercial purposes, otherwise you will be responsible for the consequences.

http://www.bkjia.com/PHPjc/759623.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/759623.htmlTechArticleLearning points: 1. PHP connects to MySQL 2. Add, delete, modify and check 3. Other common functions if you already have them Extensive experience with PHP, SQL and MySQL, now able to combine all these technologies...
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
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

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 Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft