php 查询到一组数据,然后根据通过查询a表中的cardid,如果存在相应的cardid就更新,没有就插入
时间: 2024-10-06 21:02:43 浏览: 17
在PHP中,你可以使用`mysqli`或`PDO`来实现这样的功能,首先查询源表(假设为`table_a`),找到数据,然后判断是否存在对应的`cardid`在目标表(假设为`table_b`)。如果存在则更新,不存在则插入。以下是基本的示例代码:
```php
<?php
// 数据库连接
$conn = new mysqli('localhost', 'username', 'password', 'database');
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 假设你有查询数据的SQL(比如从源表获取cardid及其相关信息)
$query = "SELECT cardid, other_data FROM table_a";
$result = $conn->query($query);
if ($result->num_rows > 0) {
// 遍历查询结果
while($row = $result->fetch_assoc()) {
$cardid = $row['cardid'];
$other_data = $row['other_data'];
// 检查目标表中是否存在该cardid
$check_query = "SELECT * FROM table_b WHERE cardid = ?";
$check_result = $conn->prepare($check_query);
$check_result->bind_param("i", $cardid);
$check_result->execute();
$check_row = $check_result->get_result()->fetch_assoc();
if ($check_row) { // 存在,则更新
$update_query = "UPDATE table_b SET other_data = ? WHERE cardid = ?";
$update_stmt = $conn->prepare($update_query);
$update_stmt->bind_param("si", $other_data, $cardid);
$update_stmt->execute();
} else { // 不存在,则插入
$insert_query = "INSERT INTO table_b (cardid, other_data) VALUES (?, ?)";
$insert_stmt = $conn->prepare($insert_query);
$insert_stmt->bind_param("is", $cardid, $other_data);
$insert_stmt->execute();
}
// 清理准备好的语句
$check_result->close();
$update_stmt->close();
}
} else {
echo "0 results";
}
// 最后别忘了关闭连接
$conn->close();
?>
```
阅读全文