【发布时间】:2018-01-10 06:49:17
【问题描述】:
我有一个表单,它使用 PHP 从 MySQL 数据库中回显特定用户的值。我试图弄清楚如何允许用户提交表单以更新他们的用户信息,但让表单跳过他们没有填写的任何字段。
当前更新声明
if (!isset($_POST['btnLogin'])) {
$db = DB();
$stmt = "UPDATE users SET fName = :fName,
lName = :lName,
emailAddress = :emailAddress
WHERE user_id = $user->user_id";
$query = $db->prepare($stmt);
$query->bindParam(':fName', $_POST['fName'], PDO::PARAM_STR);
$query->bindParam(':lName', $_POST['lName'], PDO::PARAM_STR);
$query->bindParam(':emailAddress', $_POST['emailAddress'], PDO::PARAM_STR);
$query->execute();
};
表单回显用户信息
<form class="form-horizontal" action="profile.php" method="post">
<div class="form-group">
<label class="col-lg-3 control-label">First name:</label>
<div class="col-lg-8">
<input class="form-control" type="text" name="fName" placeholder="<?php echo $user->fName ?>"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Last name:</label>
<div class="col-lg-8">
<input class="form-control" type="text" name="lName" placeholder="<?php echo $user->lName ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" type="email" name="emailAddress" placeholder="<?php echo $user->emailAddress?>">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Username:</label>
<div class="col-md-8" style="margin-top: 7px;">
<?php echo $user->username ?>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" name="btnUpdate" value="Save Changes" type="button">
<span></span>
<input class="btn btn-default" value="Cancel" type="reset">
</div>
</div>
</form>
目前这似乎根本不会更新数据库。如果我将表单完全留空并提交,则数据库中存在的值现在为空。即,只是空白列。
我一直在查看有关如何执行此操作的其他示例,但我似乎无法弄清楚这一点。任何帮助将不胜感激。
为了确保我实际上更新了正确的用户,我确保我的 $user->user_id 语句实际上从数据库中返回了正确的 user_id 以进行更新。
更新
目前这就是我拥有更新语句/代码的方式
if(!empty(['btnUpdate'])) {
$stmt = "UPDATE users SET fName = IF(:fName = '', fName, :fName),
lName = IF(:lName = '', lName, :lName),
emailAddress = IF(:emailAddress = '', emailAddress, :emailAddress)
WHERE user_id = $user->user_id";
$db = DB();
$query = $db->prepare($stmt);
$query->bindParam("fName", $fName, PDO::PARAM_STR);
$query->bindParam("lName", $lName, PDO::PARAM_STR);
$query->bindParam("emailAddress", $emailAddress, PDO::PARAM_STR);
$query->execute();
}
使用<?php var_dump($_POST) ?> 提交表单后返回0,我仍然得到空的数据库列
【问题讨论】:
-
$_POST['$fName']是名称上的拼写错误。您还应该绑定$user->user_id。如果设置了$fName,则应该不加引号或用双引号。 -
我不确定我是否完全理解您的评论。我看到 fName 上的错字。如果我只是抓取user_id而不提交,是否需要绑定?
-
您的代码中还有其他拼写错误:您的命名占位符在
bindParam()中使用时,必须以:开头,即$query->bindParam(':lName'...)。您在$_POST对象中引用对象的方式也不正确:例如,$_POST['$fName']应该是$_POST['fName']。 -
@Terry 没有必要了。
-
您需要动态构建查询。使用
empty函数(除非0是您的某些字段的有效值)。你应该到处绑定,不要在查询中放变量。