我正在尝试在提交表单时保留表单字段(标题)上的值。我希望值保留在表单字段上,即使显示错误消息但这不起作用。它返回一个空格。这里有什么问题?
<?php
$err = array(
'01' => "Your Ad was submitted!",
'02' => "Your Ad was not submitted, try again",
'03' => "Image format not supported",
'04' => "Only letters and numbers are allowed",
'05' => "Only letters and numbers are allowed"
);
$err_code = isset($_GET['err']) ? $_GET['err'] : null;
if (isset($_POST['submit'])) {
$param = array(
'title' => $_POST['title'],
'category' => $_POST['category'],
'school' => $_POST['school'],
'description' => $_POST['description'],
'price' => $_POST['price'],
'date' => date('Y-m-d H:i:s'),
'member' => $_SESSION['id']
);
$sql = "INSERT INTO ads
(title, category, school, description, price, member_id, date)
VALUES
(:title, :category, :school, :description, :price, :member_id, :date)";
if ($db->query($sql, $param)) {
$ad_id = $db ->getLastInsertId();
header ("Location: submit_ad.php?err=01");
}
else{
header ("Location: submit_ad.php?err=02");
}
?>
<form action="" class="" role="form" id="idea" method="post" enctype="multipart/form-data">
<?php
echo ('01' == $err_code) ? "<span class='error'>{$err['01']}</span>" : '';
echo ('02' == $err_code) ? "<span class='error'>{$err['02']}</span>" : '';
echo ('03' == $err_code) ? "<span class='error'>{$err['03']}</span>" : '';
?>
<div class='form-group'>
<label for="title">Title*</label>
<input type="text" class="form-control form-3x" id="title" name="title" value="<?php echo isset($_POST['title']) ? $_POST['title'] : '' ?>" >
<p class='help-block'>Add a short title to describe your Ad</p>
</div>
<div class='form-group'>
<label for="desc">Description*</label>
<textarea name="description" class="form-control form-3x" id="desc"></textarea>
<p class='help-block'>Describe your ad</p>
</div>
<div class='form-group'>
<input type="submit" value="Post" name="submit" class="btn btn-success" />
</div>
</form>
答案 0 :(得分:1)
您输入了两次,并且您正在使用两次名称属性。
<input type="text" class="form-control form-3x" id="title" name="title" <input type="text" name="myField1" value="<?php echo isset($_POST['title']) ? $_POST['title'] : '' ?>" >
正确的语法是:
<input type="text" class="form-control form-3x" id="title" name="title" value="<?php echo isset($_POST['title']) ? $_POST['title'] : '' ?>" >
输入名称必须是“标题”才能使您的php代码正常工作
答案 1 :(得分:1)
当请求新页面时,浏览器通常会清除一种输入形式。由于您执行了header ("Location: submit_ad.php?err=01");
,因此会清除该字段,并且您丢失了$ _POST数据。
在这种情况下,你可以做的是将发布数据存储在会话中,并在输入元素的value属性中回显它。
<input type="text" name="fname" value="<?php echo $_SESSION['post.fname']; ?>">
答案 2 :(得分:0)
标题输入 你的样子
<input type="text" class="form-control form-3x" id="title" name="title" <input type="text" name="myField1" value="<?php echo isset($_POST['title']) ? $_POST['title'] : '' ?>" >
issue here ^ to here ^
应该是:
<input type="text" class="form-control form-3x" id="title" name="title" value="<?php echo isset($_POST['title']) ? $_POST['title'] : '' ?>" >