简体   繁体   English

使用 php 将图像上传到磁盘并在 mysql 数据库中保存图像名称

[英]Upload images on disk and save image name on mysql DB with php

I have a MySQL db, with 2 tables, albums and photos:我有一个MySQL数据库,有 2 个表、相册和照片:

albums has id and name, photos has id, album_id, photo_name. albums 有 id 和 name,photos 有 id,album_id,photo_name。

and I have the following script:我有以下脚本:

<?php

$albumsQuery = $mysqli->query( "SELECT `album_id`, `album_name` FROM `albums` ORDER BY `album_name` ASC" );

if( isset( $_FILES["albumPhoto"] )  )
{
    move_uploaded_file( $_FILES["albumPhoto"]["tmp_name"], "photos/" .$_FILES["albumPhoto"]["name"] );
}

if( isset( $_POST["album_name"] ) )
{
    $uploadQuery = $mysqli->query( "INSERT INTO `photos` ( `photo_id`, `photos`.`photo_id_album`, `photos`.`photo_name` )
    VALUES ( NULL,'" . $mysqli->real_escape_string( $_POST["album_name"] ) . "','" . $mysqli->real_escape_string( $_FILES["albumPhoto"]["name"] ) . "' )" )
    or die( $mysqli->error );

    $upload = $uploadQuery->fetch_array( MYSQLI_ASSOC );
}
?>

The image is uploaded on disk, but I can't get the image name on DB.图片已上传到磁盘,但我无法在数据库中获取图片名称。

I wrote some code while you answered your own question so I'll just post it anyway:我在您回答自己的问题时写了一些代码,所以无论如何我都会发布它:

$albumsQuery = $mysqli->query('SELECT album_id, album_name FROM albums ORDER BY album_name');

// assume image not uploaded
$imagePath = null;

// if a photo is being uploaded
if (isset($_FILES["albumPhoto"])) {
    $source = $_FILES["albumPhoto"]["tmp_name"];
    $target = sprintf('photos/', $_FILES["albumPhoto"]["name"]);

    // try to move the file
    $move = move_uploaded_file($source, $target);
    if ($move !== true) {
        throw new Exception('Could not move the uploaded file: ' . $_FILES["albumPhoto"]["name"]);
    }
}

// attach the image to the specified album
if (isset($_POST["album_name"])) {
    $stmt = 'INSERT INTO photos (photo_id_album, photo_name)
             VALUES (?, ?)';
    $stmt->bind_param('ss', $albumName, $photoName);

    // values of bound variables
    $albumName = $_POST["album_name"];
    $photoName = $_FILES["albumPhoto"]["name"];

    // insert the record
    $stmt->execute();
    $stmt->close();
}

Also, it's not a good idea to use the original filename as users might want to upload multiple files with the same name into the same album over the time.此外,使用原始文件名也不是一个好主意,因为用户可能希望在一段时间内将多个同名文件上传到同一个相册中。 Consider using hashes or prepending the album id to the file name.考虑使用散列或将专辑 ID 附加到文件名。

And add a few more error checks!并添加更多的错误检查!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM