PHP study notes: Database connection and operation
Overview:
In Web development, database connection and operation are very important links. As a scripting language widely used in web development, PHP provides rich database connection and operation functions. This article will introduce how to connect to the database and common database operation methods in PHP, and will also provide specific code examples so that readers can better understand and apply them.
1. Database connection
In PHP, we can use extensions such as mysqli or PDO to connect to the database. The following is a code example for using the mysqli extension to connect to a MySQL database:
$servername = "localhost";
$username = "root";
$password = "password ";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check whether the connection is successful
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "Connection successful";
?>
2. Database operation
After the connection is successful, we can perform various operations on the database, including query, insert, update, delete, etc. The following are some common database operation code examples:
$sql = "SELECT id, username, email FROM users";
$ result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["username"]. " - Email: " . $row["email"]. "<br>"; }
} else {
echo "0 结果";
}
?>
$sql = "INSERT INTO users (username, email) VALUES ('John', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
$sql = "UPDATE users SET email='newemail@example.com' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "记录更新成功";
} else {
echo "Error updating record: " . $conn->error;
}
?>
$sql = "DELETE FROM users WHERE id=1";
if ($conn ->query($sql) === TRUE) {
echo "记录删除成功";
} else {
echo "Error deleting record: " . $conn->error;
}
?>
3. Close the database connection
After completing the database operation, we need to close the database connection to release resources. The following is a code example for closing a database connection:
$conn->close();
?>
Conclusion:
This article is simple It introduces how to connect to the database in PHP and common database operation methods, and provides specific code examples. By learning and understanding this knowledge, readers can better apply PHP for database operations and improve the efficiency of Web development. Hope this article is helpful to readers.
The above is the detailed content of PHP study notes: database connection and operation. For more information, please follow other related articles on the PHP Chinese website!