我正在尝试使用id从数据库中获取值,并使用PHP将其显示在<input>
中的值中,这是我的代码:
<?php
require_once 'core/init.php';
$id = (isset($_POST['id']) ? $_POST['id'] : '');
$result = $db->query("SELECT * FROM customers WHERE id = '{$id}'");
while($res = mysqli_fetch_assoc($result)) {
$first_name = $res['first_name'];
$last_name = $res['last_name'];
$mobile_number = $res['mobile_number'];
}
?>
<form action="personal_details.php" method="post" id="personal_details">
<div class="row">
<div class="form-group col-lg-12">
<label for="First_Name" style="font-weight: bold; cursor:text;"><span style="color:red;">* </span>First Name</label>
<input type="text" name="First_Name" id="First_Name" class="form-control form-control-lg"
value="<?php if(isset($_POST['first_name'])){ echo $_POST['first_name'];}?>" style="width:770px; background-color:#EEEEEE;">
</div>
</div>
<div class="row">
<div class="form-group col-lg-12">
<label for="Last_Name" style="font-weight: bold; cursor:text;"><span style="color:red;">* </span>Last Name</label>
<input type="text" name="Last_Name" id="Last_Name" class="form-control form-control-lg"
value="<?php if(isset($_POST['last_name'])){ echo $_POST['last_name'];}?>" style="width:770px; background-color:#EEEEEE;">
</div>
</div>
<div class="row">
<div class="form-group col-lg-7">
<label for="mobile_number" style="font-weight: bold;"><span style="color:red;">* </span>Mobile Phone Number</label>
<input type="tel" name="mobile_number" id="monu" class="form-control form-control-lg"
value="<?php if(isset($_POST['mobile_number'])){ echo $_POST['mobile_number'];}?>" style="background-color:#EEEEEE;">
</div>
</div>
<div class="row">
<div class="form-group col-lg-12">
<input type="submit" class="btn btn-lg btn-success" value="UPDATE" name="submit_0" style="width:770px;" id="button_0">
</div>
</div><div class="clearfix"></div>
</form>
但是它不起作用,所有字段都是空的……我尝试了<?php echo $first_name ?>
,但是仍然不起作用,我收到一条消息,提示:未定义变量:first_name。
答案 0 :(得分:0)
理论上,您想要的值是数据库结果中的值,但您输入中包含的值则来自$_POST
。
如果此表单是提交给自己而不是其他页面,则$_POST
值将在那里,并且输入将具有提交的任何值,但是假设您是根据id从其他地方加载的,表单最初加载时,只有在提交表单后,它们才不会出现。即使是那时,它们也将是发布的值,而不是数据库中的值。
您应该使用在顶部创建的$first_name
,$last_name
和$mobile_number
变量。
例如代替
value="<?php if(isset($_POST['first_name'])){ echo $_POST['first_name'];}?>"
使用
value="<?php echo $first_name ?>"
顺便说一句,由于只获取一条记录,可能不需要while循环,并且如果您不打算使用准备好的语句在查询中包含$id
,则至少应强制转换设置为int(假设id为int)。