选项动态上传图片到数据库" />
本文旨在提供一个清晰的教程,指导开发者如何根据HTML zuojiankuohaophpcnselect> 元素的选择项,将上传的图片动态保存到数据库中,并将图片路径存储到对应书籍的记录中。我们将重点讲解如何修改HTML表单结构,以及如何编写PHP代码来处理文件上传和数据库更新操作,从而实现图片与特定书籍的关联。
原有的HTML表单结构存在一些问题,导致无法正确传递选定的书籍标题。我们需要将<select>元素放置在<form>元素内部,以便在提交表单时,能够将选定的书籍ID一同传递到服务器端。
<div class="box1">
<form action='includes/upload.php' method='POST' enctype='multipart/form-data'>
<select name='booktitle' class="books-title">
<option selected disabled>-- select book --</option>
<?php
$sql='SELECT `book_id`, `book_title` FROM `books`';
$result=$connection->query($sql);
while($rs=$result->fetch_object())printf('<option value="%s">%s', $rs->book_id, $rs->book_title );
?>
</select>
<input type='file' name='file' class='uploadImg' />
<button type='submit' name='submitImg'>UPLOAD</button>
</form>
</div>关键修改:
upload.php文件需要进行修改,以处理文件上传、验证以及数据库更新。以下是修改后的PHP代码:
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['booktitle'],
$_FILES['file']
)){
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$ext=strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
$allowed = array('jpg', 'jpeg', 'png');
$bid=(int)$_POST['booktitle'];// `book_id` from `select` menu
if( is_uploaded_file( $tmp ) && $error==UPLOAD_ERR_OK && in_array( $ext, $allowed ) && $size < 1024 ){
$destination=sprintf( '../../images/book_image/%s.%s', $bid, $name );
$status=move_uploaded_file( $tmp, $destination );
if( $status ){
$sql='update `books` set `book_picture`=? where `book_id`=?';
$stmt=$connection->prepare($sql);
$stmt->bind_param('ss',$destination,$bid);
$stmt->execute();
}
ob_clean();
exit( header( "Location: index.php?uploadsucess&status=$status" ) );
}
}
?>代码解释:
注意事项:
通过以上步骤,我们可以实现根据<select>选项动态上传图片到数据库的功能。关键在于正确构建HTML表单结构,以及编写安全可靠的PHP代码来处理文件上传、验证和数据库更新。在实际应用中,还需要根据具体需求进行适当的调整和优化。
以上就是如何实现根据选项动态上传图片到数据库的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号