In PHP development, array manipulation is a fundamental skill, and interacting with databases is a common requirement. This article will guide you through the process of using PHP to perform array operations and interact with databases, providing practical code examples and techniques to help developers improve efficiency.
Arrays are an essential data structure in PHP used to store and manipulate related data. Below are some common array operations:
foreach($arr as $key => $value) { echo "Index: " . $key . " - Value: " . $value; }
Interacting with databases is one of the most common tasks in web development. Next, we'll demonstrate how to perform basic database operations with PHP, including sample code examples.
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT id, name, email FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } } else { echo "No data found!"; }
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully!"; } else { echo "Error inserting data: " . $conn->error; }
$sql = "UPDATE users SET email='john.doe@example.com' WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Data updated successfully!"; } else { echo "Error updating data: " . $conn->error; }
$sql = "DELETE FROM users WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "Data deleted successfully!"; } else { echo "Error deleting data: " . $conn->error; }
This article introduced the basic methods for performing array operations in PHP and interacting with databases. Whether you're manipulating array elements or performing database queries, inserts, updates, and deletes, mastering these techniques will significantly enhance your development efficiency. We hope this article has been helpful for your PHP development.