一个PHP函数来实现数据库的读取、插入和更新操作

一个PHP函数来实现数据库的读取、插入和更新操作。以下是一个示例:

<?php

// 连接数据库
function connectToDatabase() {

$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("连接数据库失败: " . $conn->connect_error);
}

return $conn;

}

// 读取数据
function getData($condition) {

$conn = connectToDatabase();

$sql = "SELECT * FROM your_table_name WHERE $condition";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $data = $result->fetch_all(MYSQLI_ASSOC);
    return $data;
} else {
    return [];
}

$conn->close();

}

// 插入数据
function insertData($data) {

$conn = connectToDatabase();

$columns = implode(", ", array_keys($data));
$values = "'" . implode("', '", array_values($data)) . "'";

$sql = "INSERT INTO your_table_name ($columns) VALUES ($values)";
$result = $conn->query($sql);

if ($result === TRUE) {
    return "数据插入成功";
} else {
    return "数据插入失败: " . $conn->error;
}

$conn->close();

}

// 更新数据
function updateData($condition, $data) {

$conn = connectToDatabase();

$updates = "";
foreach ($data as $key => $value) {
    $updates .= "$key = '$value', ";
}
$updates = rtrim($updates, ", ");

$sql = "UPDATE your_table_name SET $updates WHERE $condition";
$result = $conn->query($sql);

if ($result === TRUE) {
    return "数据更新成功";
} else {
    return "数据更新失败: " . $conn->error;
}

$conn->close();

}

?>
请注意,上述代码中的your_username、your_password、your_database_name和your_table_name需要根据你的实际情况进行替换。

使用示例:

<?php

// 读取数据
$data = getData("id = 1");
print_r($data);

// 插入数据
$newData = [

"name" => "John",
"age" => 25,
"email" => "john@example.com"

];
$result = insertData($newData);
echo $result;

// 更新数据
$updateData = [

"age" => 26,
"email" => "john@example.com"

];
$result = updateData("id = 1", $updateData);
echo $result;

?>
以上示例代码可以帮助你实现数据库的读取、插入和更新操作。你可以根据自己的需求进行修改和扩展。

发表评论

电子邮件地址不会被公开。 必填项已用*标注