如果photo
列为空,我正在尝试创建一个只允许用户更新MySQL表列photo
的PHP表单。目前,即使存在“空白”数据以外的数据,表单仍会更新photo
列。例如,photo
列包含数据“columbia.jpg”,用户在第一个输入中提交带有图像“Jefferson.jpg”的表单。当image
列的数据根本不应替换时,columbia.jpg
列的数据会从jefferson.jpg
替换为<?php
if (isset($_GET["id"])) {
$sn = (int)($_GET["id"]);
?>
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
Photo 1: <input type="file" name="photo"><br>
<input name="add_image" id="add_image" type="submit" value="Upload file">
</form>
<p>
<a href="pdfget.php">See all files</a>
</p>
</body>
</html>
<?php
if(isset($_POST['add_image']))
{
$dbLink = new mysqli('daom', 'sm', 'aer', 'kabm');
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
$query = "SELECT photo FROM used_trailers WHERE id = $sn";
$result = mysqli_query($dbLink, $query);
$array=mysqli_fetch_assoc($result);
if($query = " "){
//Writes the information to the database
$query1 =
"UPDATE used_trailers ".
"SET photo = '$pic' ".
"WHERE id = $sn" ;
// Execute the query
$results = $dbLink->query($query1);
// Check if it was successfull
if($results) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded to Photo 1, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your image.";
}
} else {
echo '<p>You must first delete the "Photo 1" image, $array, in order to add a new photo. This is to prevent the server from overloading with too many images.</p>';
}
}
}
echo "$query1";
?>
。相反,它应该返回一条错误消息,指出用户必须先删除旧图像,然后才能添加新图像。只有当列数据等于“空白”时才应替换列数据。 (不是“空白”而是“”。)
这是我的完整PHP页面代码:
{{1}}
感谢您的帮助。感谢所有帮助。
答案 0 :(得分:1)
您的脚本中存在一些错误。首先,if ($query = " ")
将始终返回true,因为您正在为变量$query
分配字符串" "
。要正确检查此内容,您需要使用if ($query == " ")
。
但是,这不会解决您的问题,因为$query
是查询 - 而不是结果。这应该工作
$query = "SELECT photo FROM used_trailers WHERE id = $sn";
$result = mysqli_query($dbLink, $query);
$array = mysqli_fetch_assoc($result);
if (empty($array['photo'])){
//etc.
}