我需要创建else动作。如果用户不上传新图像,数据库中应该保留旧图像。添加图像的代码是:
<?php
require_once 'database.php';
require_once 'functions.php';
$content_pic = false;
$id = $_POST['id'];
$title = trim($_POST['title']);
$text = trim($_POST['text']);
if (!empty($_FILES["content_pic"])) {
if ($_FILES["content_pic"]["error"] == UPLOAD_ERR_OK) {
$uploads_dir = __DIR__ . '/files';
$tmp_name = $_FILES["content_pic"]["tmp_name"];
$name = $_FILES["content_pic"]["name"];
if (move_uploaded_file($tmp_name, "{$uploads_dir}/{$name}")) {
$content_pic = "files/{$name}";
}
}
}else{
}
$db = database_connect();
$stmt = $db->prepare($select_query);
$stmt->execute(array($id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $db->prepare("UPDATE content SET title = ?, text= ?, content_pic = ? WHERE id = ? ");
header("Location: item_view.php?id=" . $id);
exit();
我不知道如何创建else action
您可以尝试以下几行-其中变量$content_pic
默认设置为false,因此如果没有上传图像,则可以执行不同的sql语句。
<?php
if( isset( $_POST['id'], $_POST['title'], $_POST['text'] ) ){
require_once 'database.php';
require_once 'functions.php';
$id = $_POST['id'];
$title = trim( $_POST['title'] );
$text = trim( $_POST['text'] );
$field = 'content_pic';
/* will be populated if new upload detected */
$content_pic = false;
if( !empty( $_FILES[ $field ] ) ) {
$file=$_FILES[ $field ];
if( $file["error"] == UPLOAD_ERR_OK ) {
$uploads_dir = __DIR__ . '/files';
$tmp_name = $file['tmp_name'];
$name = $file['name'];
$savepath = $uploads_dir . DIRECTORY_SEPARATOR . $name;
if( move_uploaded_file( $tmp_name, $savepath ) ) {
$content_pic = realpath( $savepath ) ? "files/{$name}" : false;
}
}
}
switch( $content_pic ){
case false:
$sql='update `content` set `title`=? `text`=? where `id`=?';
$params=array( $title, $text, $id );
break;
default:
$sql='update `content` set `title`=? `text`=?, `content_pic`=? where `id`=?';
$params=array( $title, $text, $content_pic, $id );
break;
}
$db = database_connect();
$stmt = $db->prepare( $sql );
$stmt->execute( $params );
$db->close();
}
?>