将带有标题名称的php中的数据库上传到mysql中

时间:2018-03-02 09:53:20

标签: php mysql database

我想在php中上传图片,标题名称为... 像这样::(domain.com/image-ID-title.jpg) - (domain.com/shd64ht-this-is-my-first-post.jpg)

这是我的代码,输出是(domain.com/image-ID.jpg) - (domain.com/shhk87y.jpg)

function store_file($file){
    $ext = explode('.', $file['name']);     
    $ext = $ext[count($ext)-1];

    do {
        $file_name = genfilename($ext);
    } while(file_exists("../img/{$file_name}"));

    move_uploaded_file($file['tmp_name'], "../img/{$file_name}");
    return $file_name;
}

function genfilename($ext){
    $a = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
    $nm = "";
    for($i=1; $i<=8; $i++){
        $nm = $nm . $a[rand(0,35)];
    }
    return $nm . ".{$ext}";
}

if (isset($_POST['save'])) {
    $title_save = $_POST['title'];
    $pic = $_FILES['pic'];

    $pic_name = store_file($pic);

    mysql_query("insert my_posts SET title ='$title_save' ,pic ='$pic_name'") or die(mysql_error());
    $flg_okay = 0;
    $flg_okay = 1;
}

1 个答案:

答案 0 :(得分:1)

不确定我是否完全理解您的意图,但我不建议将图像存储在数据库中。我认为你应该做的是收到一张图片并将其存储在桌子上。以下几行:

(使用HTTPPost或Put提交文件,根据您想要的任何验证)

| id | name           | alias     | path                           | created_at | updated_at |
+----+----------------+-----------+--------------------------------+------------+------------+
|  1 | filestored.jpg | mypicture | path/to/image/withoutimagename | timestamp  | timestamp  |

并使用ID(无论您认为合适)返回路径+名称来检索它。此路径+名称可以是网址,也可以告诉它根据http://php.net/manual/en/function.readfile.php下载某个文件