How to use database query and operation functions in PHP?
Database operations are one of the common tasks in web development. In PHP, we can use various functions to perform database queries and operations. This article will introduce how to use database query and operation functions in PHP, and provide code examples.
First, we need to connect to the database. PHP provides an extension called "mysqli" that can be used to connect to the MySQL database. The following is a sample code to connect to the database:
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "my_database"; // 创建数据库连接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 检查连接是否成功 if (!$conn) { die("数据库连接失败: " . mysqli_connect_error()); } // 连接成功,可以执行数据库操作了
After the connection is successful, we can perform the functions of querying and operating the database. The following are some common examples of database operation functions:
$sql = "SELECT * FROM users"; $result = mysqli_query($conn, $sql); // 遍历结果集 if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"] . ",用户名: " . $row["username"] . "<br>"; } } else { echo "没有结果"; }
$sql = "INSERT INTO users (username, password) VALUES ('john', '123456')"; if (mysqli_query($conn, $sql)) { echo "数据插入成功"; } else { echo "数据插入失败: " . mysqli_error($conn); }
$sql = "UPDATE users SET password='new_password' WHERE id=1"; if (mysqli_query($conn, $sql)) { echo "数据更新成功"; } else { echo "数据更新失败: " . mysqli_error($conn); }
$sql = "DELETE FROM users WHERE id=1"; if (mysqli_query($conn, $sql)) { echo "数据删除成功"; } else { echo "数据删除失败: " . mysqli_error($conn); }
In addition to the above examples, there are many other database operation functions that can be used in Used in PHP, such as obtaining a single result, obtaining field information, executing stored procedures, etc. Using these functions, we can easily perform database queries and operations.
Finally, we need to close the database connection to release resources:
// 关闭连接 mysqli_close($conn);
The above is a brief introduction and sample code for using database query and operation functions in PHP. By using these functions, we can easily interact with the database and implement various functions. I hope this article can help you use databases in PHP development!
The above is the detailed content of How to use database query and operation functions in PHP?. For more information, please follow other related articles on the PHP Chinese website!