php - 使用 if else 语句更新或插入数据
问题描述
使用一种形式。试图让用户插入或更新数据库。
试过 var_dump(); 试过error_reporting(E_ALL);
$stmt = $connection->prepare("SELECT * FROM profiles WHERE user=?");
$stmt->bind_param("s", $user);
/* execute prepared statement */
$stmt->execute();
$result = $stmt->get_result();
if (isset($_POST['text']))
{
if ($result->num_rows)
$text = ($_POST['text']);
$birthday = ($_POST['birthday']);
$gender= ($_GET['gender']);
$stmt = $connection->prepare("UPDATE profiles SET
user=?, text=?, birthday=?, gender=?
WHERE user=?");
$stmt->bind_param("ssss", $user, $text, $birthday, $gender);
/* execute prepared statement */
$stmt->execute();
}
//using bound paramaters for profile
else
{
$stmt = $connection->prepare("INSERT INTO profiles
(user, text, birthday, gender)
VALUES (?,?,?,?)");
$stmt->bind_param("ssss", $user, $text, $birthday, $gender);
/* execute prepared statement */
$stmt->execute();
/* close statement and connection */
$stmt->close();
}
确实收到了关于性别的未定义变量(一个单选按钮),但它消失了。数据不插入数据库。有时我会在列中看到 null。
解决方案
该UPDATE
查询有 5 个占位符,但您只在bind_param
. 最后你需要另一个$user
。
$stmt = $connection->prepare("UPDATE profiles SET
user=?, text=?, birthday=?, gender=?
WHERE user=?");
$stmt->bind_param("sssss", $user, $text, $birthday, $gender, $user);
但是没有必要设置user
,因为您只是将其设置为相同的值,因此将其更改为:
$stmt = $connection->prepare("UPDATE profiles SET
text=?, birthday=?, gender=?
WHERE user=?");
$stmt->bind_param("ssss", $text, $birthday, $gender, $user);
如果该user
列是唯一键,您可以将所有代码组合到一个查询中,使用INSERT ... ON DUPLICATE KEY UPDATE
.
$stmt = $connection->prepare("
INSERT INTO profiles (user, text, birthday, gender)
VALUES (?,?,?,?)
ON DUPLICATE KEY UPDATE text = VALUES(text), birthday = VALUES(birthday), gender = VALUES(gender)");
$stmt->bind_param("ssss", $user, $texxt, $birthday, $gender);
推荐阅读
- javascript - 如何在 Google 表格中制作一个按钮,连续触发两个不同的功能
- javascript - 使用 css 或 js 以一些倾斜角度或椭圆形状旋转对象 360 度
- spring-boot - Sprinboot:尝试将对象传递给我的模型属性时出现 java.lang.StackOverflowError
- python - Reporlab 使用 PDFImage 类更改 hAline
- android - 如何在日历意图中插入多天?
- c# - 展开可为空的
在 IValueConverter 中获取 T - java - 无法从 Scaleset 获取虚拟机列表
- powershell - 为什么powershell会收集未捕获的值并将其作为数组返回
- azure - 超过 3 小时超时自动化 Runbook Azure
- c# - 在 MVVM / MVVM Light 中绑定单选按钮的正确方法是什么