How to get the next id in a database table to save an uploaded file in a CodeIgniter application
03:21 22 Dec 2018

I have script to upload an image with automatic naming, but I give the name with id from database, but the data in database isn't exist yet, so I insert the data first, then I get the max id as name of image (you can find it out clearly in my attachment code below and id is auto-increment), and the problem is I think if the server get much request to upload image, the image will have wrong name or name with id that doesn't belong to it. Is there best practice regard to my problem? or you have better process for this?

This code written in PHP with CodeIgniter.

if (isset($_FILES['gambarProduk'])) {
    $this->db->select_max('idProduk', 'maks');
    $this->db->insert('gambarProduk', array('idProduk' => $this->db->get('produk')->result()[0]->maks));
    $config['upload_path']          = 'images/produk/';
    $config['allowed_types']        = 'gif|bmp|jpg|png|jpeg';
    $this->db->select_max('idGambar', 'maks');
    $config['file_name'] = $this->db->get('gambarProduk')->result()[0]->maks;
    $extension = pathinfo($_FILES["gambarProduk"]['name'], PATHINFO_EXTENSION);
    $fullpath = $config['upload_path'] . $config['file_name'] . '.' . $extension;

    if (file_exists($fullpath)) {
        unlink($fullpath);
    }
    $this->db->where('idGambar', $config['file_name']);
    $this->db->update('gambarProduk', array('extension' => $extension));
    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('gambarProduk')) {
        $this->session->set_flashdata('uploadGambarProduk', 2);
    }
}
php codeigniter file-upload max