Search code examples
phpjquerymysqljquery-file-upload

how do I insert data when the DB value of "position" is equal to "id" in jquery-file-upload


how do I insert data when the DB value of "position" is equal to "id", in jquery-file-upload, thanks

if (empty($file->error)) {
            $sql = 'INSERT INTO `'.$this->options['db_table']
                .'` (`name`, `size`, `type`, `title`, `description`, `position`)'
                .' VALUES (?, ?, ?, ?, ?, ?)';
            $query = $this->db->prepare($sql);
            $query->bind_param(
                'sisssi',
                $file->name,
                $file->size,
                $file->type,
                $file->title,
                $file->description,
                $file->position
            );
            $query->execute();
            $file->id = $this->db->insert_id;
        }
        return $file;

Solution

  • You should do it in 2 steps:

    if (empty($file->error)) {
            $sql = 'INSERT INTO `'.$this->options['db_table']
                .'` (`name`, `size`, `type`, `title`, `description`)'
                .' VALUES (?, ?, ?, ?, ?)';
            $query = $this->db->prepare($sql);
            $query->bind_param(
                $file->name,
                $file->size,
                $file->type,
                $file->title,
                $file->description
            );
            $query->execute();
            $file->id = $this->db->insert_id;
    
            $sql = 'UPDATE `'.$this->options['db_table']
                .'` SET `position` = `id` WHERE `id` = ?';
            $query = $this->db->prepare($sql);
            $query->bind_param(
                $file->id
            );
            $query->execute();
        }
        return $file;
    

    First insert without position, then update the position based on the last inserted id.