我有这个表格:
<div class="col-md-6">
<h4>Update Contact Details</h4>
<form action="" method="post" name="contact" id="contact">
<div class="form-group">
<label>*Address:</label>
<input type="text" class="form-control" id="address_line_1" name="address_line_1" value="<? echo $address_line_1; ?>" placeholder="Address Line 1..." required="required">
<input type="text" class="form-control" id="address_line_2" name="address_line_2" value="<? echo $address_line_2; ?>" placeholder="Address Line 2...">
<label>*Postcode:</label>
<input type="text" class="form-control" id="postcode" name="postcode" value="<? echo $postcode; ?>" placeholder="Postcode" required="required">
</div>
<div class="form-group">
<label>*Phone Number:</label>
<input type="number" class="form-control" id="contact_number" name="contact_number" value="<? echo $contact_number; ?>" placeholder="Phone Number" required="required">
</div>
<div class="form-group">
<input type="hidden" class="form-control" id="userid" name="userid" value="<? echo $userid; ?>">
<button type="submit" id="contact" name="contact" class="btn btn-primary btn-sm">Save Details</button>
</div>
</div>
运行到这个脚本:
if(isset($_POST['contact'])){
$address_line_1 = str_replace("'","\\'",$_POST['address_line_1']);
$address_line_2 = str_replace("'","\\'",$_POST['address_line_2']);
$postcode = str_replace("'","\\'",$_POST['postcode']);
$contact_number = $_POST['contact_number'];
$uid = $_POST['userid'];
mysqli_query($conn, "UPDATE ap_users SET address_line_1 = '$address_line_1', address_line_2 = '$address_line_2', postcode = '$postcode', $contact_number = '$contact_number' WHERE user_id = '$uid'");
}
非常基本,我知道 - 当我发送表单时,页面上回显的变量(例如 echo $address_line_1
)都会更改为新结果,尽管当我重新加载页面时,它们回到原来的结果。当我发送表单时,似乎 MySQL 数据库没有更新,我不太确定为什么?
最佳答案
根据 OP 的要求。
添加或 die(mysqli_error($conn))
至 mysqli_query()
看看是否有错误。
也最好使用affected_rows()
也在更新。
此外,您正在使用 if(isset($_POST['contact'])){
并为表单和按钮提供 2x 名称属性。
从 <form>
中删除一个. <form>
上的名称属性仅在使用 jQuery/Ajax 时有效。
此外,如果您的表单和 PHP/SQL 在同一文件中,请使用 header 重定向到同一页面并确保您不是 *
在标题之前输出。并确保已启用短标签。
引用资料:
- http://php.net/manual/en/mysqli.affected-rows.php
- http://php.net/manual/en/mysqli.error.php
- http://php.net/manual/en/function.header.php
-
*
How to fix "Headers already sent" error in PHP
您现在的密码是开放给SQL injection .使用 mysqli_*
with prepared statements , 或 PDO与 prepared statements .
关于php - HTML 表单更改回显变量而不是数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33983579/