Chương 5: Hướng Dẫn Kết Nối PHP với MySQL

Tài liệu nghiên cứu Chapter 5 php and mysql, tổng hợp lý thuyết và thực hành, cung cấp kiến thức chuyên sâu về ., phục vụ nghiên cứu và ứng dụng thực tiễn

Chuyên ngành

Lập Trình Web

Người đăng

Ẩn danh

Thể loại

bài giảng

2020

60
2
0

Phí lưu trữ

30 Point

Mục lục chi tiết

5. CHƯƠNG 5: PHP and MySQL

5.1. Objectives

5.2. Connecting to MySQL with PHP

5.3. Which MySQL Package to Use

5.4. Opening and Closing a Connection

5.5. Reporting MySQL Errors

5.6. Selecting a Database

5.7. Executing SQL Statements

5.8. Sample Code

5.9. Adding, Deleting, and Updating Records

5.10. Retrieving Records into an Indexed Array

5.11. Using the mysqli_affected_rows() Function

5.12. Using the mysqli_info() Function

5.13. Working with Query Results

5.14. Retrieving Records into an Associative Array

5.15. Closing Query Results

5.16. Accessing Query Result Information

5.17. Summary

Tóm tắt

I. Hướng Dẫn Kết Nối PHP với MySQL Đơn Giản và Hiệu Quả

Kết nối PHP với MySQL là một trong những kỹ năng cơ bản mà lập trình viên cần nắm vững. Việc này không chỉ giúp truy cập dữ liệu mà còn cho phép thực hiện các thao tác như thêm, sửa, xóa và truy vấn dữ liệu. Bài viết này sẽ hướng dẫn chi tiết cách thực hiện kết nối này một cách hiệu quả.

1.1. Tổng Quan về Kết Nối PHP với MySQL

Kết nối PHP với MySQL cho phép lập trình viên truy cập và quản lý cơ sở dữ liệu. PHP hỗ trợ nhiều phương thức kết nối, trong đó mysqli là phổ biến nhất.

1.2. Các Gói MySQL Phổ Biến trong PHP

Gói mysqli (MySQL Improved) là lựa chọn tốt nhất cho PHP 5 trở lên. Nó cung cấp nhiều tính năng mới và cải thiện hiệu suất so với gói mysql cũ.

II. Cách Mở và Đóng Kết Nối MySQL trong PHP

Mở và đóng kết nối MySQL là bước quan trọng trong việc quản lý cơ sở dữ liệu. Sử dụng hàm mysqli_connect() để mở kết nối và mysqli_close() để đóng kết nối.

2.1. Cú Pháp Mở Kết Nối MySQL

Cú pháp mở kết nối sử dụng hàm mysqli_connect() với các tham số như host, user, password và database. Điều này giúp xác định thông tin cần thiết để kết nối đến cơ sở dữ liệu.

2.2. Cách Đóng Kết Nối MySQL

Để đóng kết nối, sử dụng hàm mysqli_close(). Việc này giúp giải phóng tài nguyên và đảm bảo an toàn cho dữ liệu.

III. Xử Lý Lỗi Khi Kết Nối MySQL với PHP

Xử lý lỗi là một phần quan trọng trong lập trình. Khi kết nối MySQL, có thể gặp phải nhiều lỗi như sai thông tin đăng nhập hoặc máy chủ không hoạt động.

3.1. Các Lỗi Thường Gặp Khi Kết Nối

Các lỗi phổ biến bao gồm: máy chủ không chạy, quyền truy cập không đủ, và thông tin đăng nhập không chính xác. Cần kiểm tra kỹ lưỡng để khắc phục.

3.2. Cách Sử Dụng Hàm Xử Lý Lỗi

Hàm mysqli_errno() và mysqli_error() giúp lấy mã lỗi và thông báo lỗi từ các thao tác MySQL trước đó, giúp lập trình viên dễ dàng xác định vấn đề.

IV. Thao Tác với Cơ Sở Dữ Liệu MySQL trong PHP

Sau khi kết nối thành công, lập trình viên có thể thực hiện các thao tác như thêm, sửa, xóa và truy vấn dữ liệu trong cơ sở dữ liệu MySQL.

4.1. Cách Thêm Dữ Liệu vào MySQL

Sử dụng câu lệnh INSERT kết hợp với hàm mysqli_query() để thêm dữ liệu vào bảng. Cần đảm bảo cú pháp đúng để tránh lỗi.

4.2. Cách Cập Nhật và Xóa Dữ Liệu

Sử dụng câu lệnh UPDATE để sửa đổi dữ liệu và DELETE để xóa dữ liệu. Cần chú ý đến điều kiện WHERE để tránh xóa nhầm dữ liệu.

V. Truy Vấn Dữ Liệu từ MySQL bằng PHP

Truy vấn dữ liệu là một trong những chức năng quan trọng nhất khi làm việc với cơ sở dữ liệu. PHP cung cấp nhiều hàm để thực hiện việc này.

5.1. Cách Sử Dụng Câu Lệnh SELECT

Câu lệnh SELECT cho phép lấy dữ liệu từ bảng. Sử dụng hàm mysqli_query() để thực hiện truy vấn và lấy kết quả.

5.2. Xử Lý Kết Quả Truy Vấn

Sử dụng các hàm như mysqli_fetch_assoc() để lấy dữ liệu từ kết quả truy vấn. Điều này giúp dễ dàng xử lý và hiển thị dữ liệu.

VI. Kết Luận và Tương Lai của Kết Nối PHP với MySQL

Kết nối PHP với MySQL là một kỹ năng thiết yếu cho lập trình viên web. Với sự phát triển của công nghệ, việc này sẽ ngày càng trở nên quan trọng hơn.

6.1. Tương Lai của Kết Nối Cơ Sở Dữ Liệu

Với sự phát triển của các công nghệ mới, việc kết nối và quản lý cơ sở dữ liệu sẽ ngày càng trở nên dễ dàng và hiệu quả hơn.

6.2. Lời Khuyên cho Lập Trình Viên Mới

Nên nắm vững các khái niệm cơ bản và thực hành thường xuyên để cải thiện kỹ năng kết nối PHP với MySQL.

15/07/2025

Trích đoạn nội dung tài liệu

Chapter 5 PHP and MySQL Lectured by: Nguyễn Hữu Hiếu Objectives In this lesson, you will: • Connect to MySQL from PHP • Work with MySQL databases using PHP • Create, modify, and delete MySQL tables with PHP • Use PHP to manipulate MySQL records • Use PHP to retrieve database records Trường Đại Học Bách Khoa TP.HCM 2 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 2 © 2020 Connecting to MySQL with PHP • PHP has the ability to access and manipulate any database that is ODBC (Open Database Connectivity) compliant • PHP includes functionality that allows you to work directly with different types of databases, without going through ODBC Trường Đại Học Bách Khoa TP.HCM 3 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 3 © 2020 Which MySQL Package to Use • The mysqli (MySQL Improved) package became available with PHP 5 and is designed to work with MySQL version 4.3 and later • Earlier versions must use the mysql package • The mysqli package is the object-oriented equivalent of the mysql package but can also be used procedurally • Mysqli package has improved speed, security and compatibility with libraries. Trường Đại Học Bách Khoa TP.HCM 4 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 4 © 2020 Opening and Closing a Connection • Open a connection to a MySQL database server with the mysqli_connect() function • The mysqli_connect() function returns a positive integer if it connects to the database successfully or FALSE if it does not • Assign the return value from the mysqli_connect() function to a variable that you can use to access the database in your script Trường Đại Học Bách Khoa TP.HCM 5 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 5 © 2020 Opening and Closing a Connection • The syntax for the mysqli_connect() function is: $connection = mysqli_connect("host" [, "user", "password"[,”database”]]); • The host argument specifies the host name where your MySQL database server is installed • The user and password arguments specify a MySQL account name and password • You can optionally select the database when connecting. Trường Đại Học Bách Khoa TP.HCM 6 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 6 © 2020 Opening and Closing a Connection • The database connection is assigned to the $DBConnect variable $DBConnect = mysqli_connect("localhost", "billyeakus ", "hotdog"); • Close a database connection using the mysql_close() function mysqli_close($DBConnect); Trường Đại Học Bách Khoa TP.HCM 7 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 7 © 2020 Opening and Closing a Connection mysqli_get_client_info() Returns the MySQL client library version mysqli_get_client_stats() Returns statistics about client per-process mysqli_get_client_version() Returns the MySQL client library version as an integer mysqli_get_connection_stats() Returns statistics about the client connection mysqli_get_host_info() Returns the MySQL server hostname and the connection type mysqli_get_proto_info() Returns the MySQL protocol version mysqli_get_server_info() Returns the MySQL server version mysqli_get_server_version() Returns the MySQL server version as an integer Trường Đại Học Bách Khoa TP.HCM 8 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 8 © 2020 Opening and Closing a Connection version.php in a Web browser Trường Đại Học Bách Khoa TP.HCM 9 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 9 © 2020 Reporting MySQL Errors • Reasons for not connecting to a database server include: – The database server is not running – Insufficient privileges to access the data source – Invalid username and/or password Trường Đại Học Bách Khoa TP.HCM 10 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 10 © 2020 Reporting MySQL Errors • The mysqli_errno() function returns the error code from the last attempted MySQL function call or 0 if no error occurred • The mysqli_error() — Returns the text of the error message from previous MySQL operation • The mysqli_errno() and mysqli_error() functions return the results of the previous mysqli*() function Trường Đại Học Bách Khoa TP.HCM 11 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 11 © 2020 Selecting a Database • The syntax for the mysqli_select_db() function is: mysqli_select_db(connection, database); • The function returns a value of TRUE if it successfully selects a database or FALSE if it does not • For security purposes, you may choose to use an include file to connect to the MySQL server and select a database Trường Đại Học Bách Khoa TP.HCM 12 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 12 © 2020 Sample Code good $link = mysqli_connect("cs.edu", “demo", “demo"); mysqli_select_db($link, "nonexistentdb”); bad echo mysql_errno($link). "<br>"; mysqli_select_db( $link, “demo"); good mysqli_query($link, bad "SELECT * FROM nonexistenttable"); echo mysqli_errno($link).

"<br>"; Trường Đại Học Bách Khoa TP.HCM 13 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 13 © 2020 Sample Code $host='localhost'; $userName = 'demo'; $password = 'demo'; $database ='demo'; $link = mysqli_connect ($host, $userName, $password) ; if (!$link) { die('Could not connect: '. mysqli_error($link)); } echo 'Connected successfully'; mysqli_close($link); Trường Đại Học Bách Khoa TP.HCM 14 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 14 © 2020 include(‘file.php’); include_once(‘file.php’) require(‘file.php’); require_once(‘file.php <?php include_once(‘config/file.php’); echo “test”; include(‘config/file.php’); ?> config/file.php <?php include(‘file2.php’); ?> Trường Đại Học Bách Khoa TP.HCM Lập Trình Web Khoa Khoa Học và Kỹ Thuật Máy Tính 15 © 2020 Sample Code <?php $link = mysqli_connect('localhost', 'mysql_user', 'mys ql_password'); if (!$link) { die('Not connected : '. mysqli_error($link)); } // make foo the current db $db_selected = mysqli_select_db($link,'foo'); if (!$db_selected) { die ('Can\'t use foo : '. mysqli_error($link)); } ?> Trường Đại Học Bách Khoa TP.HCM 16 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 16 © 2020 Executing SQL Statements • Use the mysqli_query() function to send SQL statements to MySQL • The syntax for the mysqli_query() function is: mysqli_query(connection, query); • The mysqli_query() function returns one of three values: – For SQL statements that do not return results (CREATE DATABASE and CREATE TABLE statements) it returns a value of TRUE if the statement executes successfully Trường Đại Học Bách Khoa TP.HCM 17 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 17 © 2020 Executing SQL Statements – For SQL statements that return results (SELECT and SHOW statements) the mysqli_query() function returns a result pointer that represents the query results •A result pointer is a special type of variable that refers to the currently selected row in a resultset – The mysqli_query() function returns a value of FALSE for any SQL statements that fail, regardless of whether they return results Trường Đại Học Bách Khoa TP.HCM 18 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 18 © 2020 Sample Code <?php // This could be supplied by a user, for example $firstname = 'fred'; $lastname = 'fox'; //never trust user data $firstname= mysql_real_escape_string($firstname); $lastname= mysql_real_escape_string($lastname); // Formulate Query // For more examples, see mysql_real_escape_string() $query = "SELECT firstname, lastname, address, age FROM friends WHERE firstname=‘$firstname ‘ AND lastname= ‘$lastname’”; // Perform Query $result = mysql_query($query); // Check result // This shows the actual query sent to MySQL, and the error.

Useful for debugging. if (!$result) { $message = 'Invalid query: '. $query; die($message); } // Use result // Attempting to print $result won't allow access to information in the resource // One of the mysql result functions must be used // See also mysql_fetch_array(), mysql_fetch_row(), etc. while ($row = mysql_fetch_assoc($result)) { echo $row['firstname']; echo $row['lastname']; echo $row['address']; echo $row['age']; } // Free the resources associated with the result set // This is done automatically at the end of the script mysql_free_result($result); ?> Trường Đại Học Bách Khoa TP.HCM 19 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 19 © 2020 Adding, Deleting, and Updating Records • To add records to a table, use the INSERT and VALUES keywords with the mysqli_query() function • To add multiple records to a database, use the LOAD DATA statement with the name of the local text file containing the records you want to add • To update records in a table, use the UPDATE statement Trường Đại Học Bách Khoa TP.HCM 20 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 20 © 2020 Adding, Deleting, and Updating Records <?php $con = mysqli_connect("localhost","demo","demo"); if (!$con) { die('Could not connect: '.

mysqli_error($con)); } mysqli_select_db($con, "demo"); mysqli_query($con, "INSERT INTO friends (FirstName, LastName, Age) VALUES ('Lester', 'Longbottom', '35')"); mysqli_query($con,"INSERT INTO friends (FirstName, LastName, Age) VALUES ('Carly', 'Sampson', '33')"); mysqli_close($con); ?> Trường Đại Học Bách Khoa TP.HCM Lập Trình Web Khoa Khoa Học và Kỹ Thuật Máy Tính 21 © 2020 Adding, Deleting, and Updating Records • The UPDATE keyword specifies the name of the table to update • The SET keyword specifies the value to assign to the fields in the records that match the condition in the WHERE clause • To delete records in a table, use the DELETE statement with the mysqli_query() function • Omit the WHERE clause to delete all records in a table Trường Đại Học Bách Khoa TP.HCM 22 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 22 © 2020 Adding, Deleting, and Updating Records ?php $con = mysqli_connect("localhost","demo","demo"); if (!$con) { die('Could not connect: '. mysqli_error($con)); } mysqli_select_db($con,"demo"); mysqli_query($con,"UPDATE friends SET Age = '61' WHERE FirstName = 'Bill' AND LastName = 'Yeakus'"); mysqli_close($con); ?> Trường Đại Học Bách Khoa TP.HCM Lập Trình Web Khoa Khoa Học và Kỹ Thuật Máy Tính 23 © 2020 Retrieving Records into an Indexed Array The mysqli_fetch_row() function returns the fields in the current row of a resultset into an indexed array and moves the result pointer to the next row echo "<table border=1>"; echo "<tr><th>First</th><th>Last</th> <th>Address</th><th>age</th></tr>"; $Row = mysqli_fetch_row($result); do { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td>{$Row[2]}</td>"; echo "<td>{$Row[3]}</td></tr>"; $Row = mysqli_fetch_row($result); } while ($Row); echo "</table>"; mysqli_close($con); ?> Trường Đại Học Bách Khoa TP.HCM 24 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 24 © 2020 Sample Code <?php $con = mysqli_connect("localhost","demo","demo","demo"); if (!$con) { die('Could not connect: '. mysqli_error($con)); } $q = "SELECT * FROM friends"; $result = mysqli_query($con,$q); echo "<table border=1>"; echo "<tr><th>First</th><th>Last</th> <th>Address</th><th>age</th></tr>"; while ($Row=mysqli_fetch_assoc($result)) { echo "<tr><td>{$Row['firstname']}</td>"; echo "<td>{$Row['lastname']}</td>"; echo "<td>{$Row['address']}</td>"; echo "<td>{$Row['age']}</td></tr>"; } echo "</table>"; mysqli_close($con); ?> Trường Đại Học Bách Khoa TP.HCM 25 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 25 © 2020 Using the mysqli_affected_rows() Function • With queries that return results (SELECT queries), use the mysqli_num_rows() function to find the number of records returned from the query • With queries that modify tables but do not return results (INSERT, UPDATE, and DELETE queries), use the mysqli_affected_rows() function to determine the number of affected rows Trường Đại Học Bách Khoa TP.HCM 26 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 26 © 2020 Using the mysql_affected_rows() Function $QueryResult = mysqli_query($con,"UPDATE friends SET Age = '67' WHERE FirstName = 'Bill' AND LastName = 'Yeakus'"); if ($QueryResult === FALSE) echo "<p>Unable to execute the query. "</p>"; else echo "<p>Successfully updated ".

mysqli_affected_rows($con) .</p>"; mysql_close($con); ?> Trường Đại Học Bách Khoa TP.HCM 27 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 27 © 2020 Using the mysql_affected_rows() Function Output of mysql_affected_rows() function for an UPDATE query Trường Đại Học Bách Khoa TP.HCM 28 Web Lập Trình Khoa Khoa Học và Kỹ Thuật Máy Tính 28 © 2020 Using the mysqli_info() Function • For queries that add or update records, or alter a table’s structure, use the mysqli_info() function to return information about the query • The mysqli_info() function returns the number of operations for various types of actions, depending on the type of query • The mysqli_info() function returns information about the last query that was executed on the database connection Trường Đại Học Bách Khoa TP.

Nội dung được bảo vệ bản quyền — Tải xuống đầy đủ