3

私はMySQL2つのテーブル、アルバム、写真を含むデータベースを持っています:

アルバムにはIDと名前があり、写真にはID、album_id、photo_nameがあります。

そして私は次のスクリプトを持っています:

<?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 );
}
?>

イメージはディスクにアップロードされていますが、DBでイメージ名を取得できません。

4

1 に答える 1

0

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.

And add a few more error checks!

于 2012-12-19T17:31:05.493 に答える