doumeng06063991 2012-11-29 18:50
浏览 56

上传磁盘上的图像,并使用php将图像名称保存在mysql DB上

I have a MySQL db, with 2 tables, albums and photos:

albums has id and name, photos has 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.

Thanks in advanced.

  • 写回答

1条回答 默认 最新

  • douying0108 2012-12-19 17:31
    关注

    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!

    评论

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题