我一直试图让这个语句更新我的数据库,但没有成功。我有一个表单,允许用户更新他们的用户名和电子邮件。我在俯瞰什么?
以下是我的发言:
<?php require_once('config.php');
$id= $_SESSION['id'];//get user id you can use session also
if (isset($_POST['submit'])){
$username = $_POST['username'];
$email = $_POST['email'];
$query = "UPDATE members SET username = :username ,email = :email WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->bindParam(':username',$username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
}
$query = "SELECT * FROM members WHERE id = $id"; //Get user info
$stmt = $db->prepare($query);
$stmt ->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
// output data of each row
foreach($result as $row){
$username = $row['username'];
$email = $row['email'];
}
}
?>
这是我的表格:
<form role="form" class="cf-form floating-labels" method="post" action="<?php filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ?>">
<fieldset>
<legend>My Account<br />
<img class="logo_contact" src="img/jobmiser_logo2.png" alt="jobmiser logo" />
</legend>
<div class="icon">
<label class="cf-label" for="username">Username</label>
<input class="user" type="text" name="username" id="username" value="<?php echo $username ?>" tabindex="2" required />
</div>
<div class="icon">
<label class="cf-label" for="email">Email</label>
<input class="email" type="email" name="email" id="email" value="<?php echo $email ?>" tabindex="3" required />
</div>
</fieldset>
<fieldset>
<div class="icon">
<input name="submit" type="submit" value="Update" />
</div>
</fieldset>
</form>
答案 0 :(得分:0)
您需要在更新查询中绑定:id参数:
// bind :id
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
// You also need to execute it
$stmt ->execute();
在第二个语句中,您还应该绑定值id,而不是将其直接插入到字符串中。
// BAD
$query = "SELECT * FROM members WHERE id = $id";
// GOOD
$query = "SELECT * FROM members WHERE id = :id"; //Get user info
$stmt = $db->prepare($query);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt ->execute();