douxianglu4370 2012-02-13 13:28
浏览 107
已采纳

按ID重命名文件名

i am trying to rename an image file and save the file location in database. i am having problem problem with it, as i want to name the file as the id of the table row i am inserting in. after uploading and inserting i want to see my table as like this:

----------------------------------------
| id | name | category | image         |
----------------------------------------
| 1  | foo  | category | uploads/1.jpg |
----------------------------------------

the id field is auto incremented. here is my code for it:

function service()
{
    $con=$this->do_upload();
    $id=mysql_insert_id();
    $data=array(
        'name'=>$this->input->post('name'),
        'category'=>$this->input->post('category'),
        'image'=>'uploads/'.$id.$con['file_ext'];
     );
    $query=$this->db->insert('table',$data);
    return $query;
}

this is not the correct way and as assumed the file is not saved in the database as wanted.instead of saving it as 'uploads/1.jpg' it is saved as 'uploads/0.jpg'.
can any one provide me the right convention to do it? n.b. i am using codeigniter 2.1.0 and mySQL database.

  • 写回答

4条回答 默认 最新

  • douduiwei2831 2012-02-13 13:32
    关注

    You cannot access id with mysql_insert_id without calling mysql query before. You have to insert new record and then update it. with new filename.

    Edit:

    When I was uploading images/other files to the server, I was always renaming them with some random hash. So files had unique hash name on filesystem and in mysql row there was set just this hash to associate db row with file.

    So before inserting new record into db, generate some random string with checking if file with this name already exists:

    $filename = '';
    do {
      $filename = substr(md5(uniqid(rand(), true)), 0, 8);
    } while ( !file_exists('uploads/'.$filename) );
    

    Do it in do_upload method and let it to return file's name in $con array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度