Interaction methods and techniques between PHP arrays and databases
Introduction:
In PHP development, operating arrays is a basic skill, and interaction with databases is a common requirement. This article will introduce how to use PHP to manipulate arrays and interact with databases, and provide some practical code examples.
1. Basic operations of PHP arrays
In PHP, arrays are a very useful data type that can be used to store and operate a set of related data. The following are some common examples of array operations:
Traverse the array:
foreach($arr as $key => $value) {
echo "索引:".$key.",值:".$value;
}
2. Interaction with the database
Interaction with the database is a common task in Web development. The following will introduce how to use PHP to perform basic database operations, with code examples.
Connect to the database:
$servername = "localhost";
$username = "root";
$password = "password ";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn-> connect_error) {
die("数据库连接失败: " . $conn->connect_error);
}
?>
Query data:
$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 "没有找到数据!";
}
?>
Insert data:
$sql = "INSERT INTO users (name , email) VALUES ('John Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功!";
} else {
echo "插入数据时出错: " . $conn->error;
}
?>
Update data:
$sql = "UPDATE users SET email='john.doe@example.com' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "数据更新成功!";
} else {
echo "更新数据时出错: " . $conn->error;
}
?>
Delete data:
$sql = "DELETE FROM users WHERE id= 1";
if ($conn->query($sql) === TRUE) {
echo "数据删除成功!";
} else {
echo "删除数据时出错: " . $conn->error;
}
?> ;
3. Conclusion
This article introduces the basic methods of operating arrays in PHP development, and provides some sample codes for interacting with the database. Mastering these methods and techniques will be of great help to PHP development and interaction with databases. I hope this article can inspire and help readers.
The above is the detailed content of Interactive methods and techniques for PHP arrays and databases. For more information, please follow other related articles on the PHP Chinese website!