我有编辑某些信息的表单。这还包括一个图像字段。问题是我无法将链接(或图像)加载到图像中,当我提交表单时,我没有提供新的图像,旧的图像从DB中删除,这是正常的,因为我提供空字段。问题是在这种情况下该怎么做? 这是我的表格
if ( !empty($_POST))
{
// keep track post values
$name = $_POST['name'];
$image = $_POST['image'];
$text = $_POST['text'];
$adress = $_POST['adress'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE rest set name = ?, image = ?, text = ?, adress = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$image,$text,$adress,$id));
Database::disconnect();
//header("Location: index.php");
echo "<code>Done!</code>";
}
else
{
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM rest where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($rest_id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$image= $data[image];
$text = $data['text'];
$adress = $data['adress'];
Database::disconnect();
}
?>
<form role="form" action="" method="post">
<!-- Form Name -->
<legend>Редакция на ресторант</legend>
<!-- Text input-->
<div class="form-group">
<label for="name">Name</label>
<input value="<?php echo !empty($name)?$name:'';?>" id="name" name="name" class="form-control" type="text">
</div>
<!-- Text input-->
<div class="form-group">
<label for="text">Text</label>
<input value="<?php echo !empty($text)?$text:'';?>" id="text" name="text" class="form-control" type="text">
</div>
<div class="form-group">
<label for="image">Image</label>
<input value="<?php echo !empty($image)?$image:'';?>" id="image" name="image" class="form-control" type="text">
</div>
<!-- Text input-->
<div class="form-group">
<label for="adress">Adress</label>
<input value="<?php echo !empty($adress)?$adress:'';?>" id="adress" name="adress" class="form-control" type="text">
</div>
</form>
正如您可以看到表单打开时我检查并从DB获取字段数据并编辑我需要的内容。这种方式如果我不想要edin Name
我不会提交空字段。问题出在图像领域。我该怎么做?它没有apear链接/名称或该位置上的任何内容。
答案 0 :(得分:1)
如果图像字段为空或为空,请不要更新图像字段,只需更改sql从更新中删除图像字段:
if ($image != null && $image != ''){
$sql = "UPDATE rest set name = ?, image = ?, text = ?, adress = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$image,$text,$adress,$id));
}
else {
$sql = "UPDATE rest set name = ?, text = ?, adress = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$text,$adress,$id)); //remove image from here too..
}