php crud operations basic example
在PHP编程中,CRUD(Create、Read、Update、Delete)是与数据库交互的基础操作。以下是各个操作的简要示例:
创建(Create):向数据库插入新记录。
'localhost';
$username = 'username';
$password = 'password';
$dbname = 'myDB';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die('连接失败: ' . $conn->connect_error);
}
$sql = 'INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')';
if ($conn->query($sql) === TRUE) {
echo '新记录插入成功';
} else {
echo 'Error: ' . $sql . '
' . $conn->error;
}
$conn->close();
?>
读取(Read):从数据库中检索数据。
$sql = 'SELECT id, firstname, lastname FROM MyGuests';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo 'id: ' . $row['id'] . ' - Name: ' . $row['firstname'] . ' ' . $row['lastname'] . '
';
}
} else {
echo '0 results';
}
更新(Update):修改数据库中已有记录。
$sql = 'UPDATE MyGuests SET lastname='Doe' WHERE id=2';
if ($conn->query($sql) === TRUE) {
echo '记录更新成功';
} else {
echo '更新错误: ' . $conn->error;
}
删除(Delete):删除数据库中的特定记录。
$sql = 'DELETE FROM MyGuests WHERE id=3';
if ($conn->query($sql) === TRUE) {
echo '记录删除成功';
} else {
echo '删除错误: ' . $conn->error;
}