Ibrahim Alsaman Ibrahim Alsaman - 6 months ago 24
SQL Question

codeigniter auto increment foreignkey


In my application i have function to insert data to mysqldb and have more one image for one news and in database I make news id as foreign key in upload table and all inserts is work fine but the problem news FK in upload table when i insert data the first row inserted take the value i set it and the other take auto increment so the next you found code :

the inserted data in upload table

upload table data

as you se the correct data is row have id 31 and the other is auto increment

the code I insert by him ;

the controller

public function insertNews() {
$this->do_one_upload();
$this->load->model('newsModel');
$this->load->model('fileModel');
$ad_ne_data = array(
'titel' => $this->input->post('ad_news_title') ,
'content' => $this->input->post('ad_news_content') ,
'news_category_id' => $this->input->post('ad_news_category') ,
'img_url' => $this->do_one_upload()[1]['full_path'],
'created_at' => date("Y-m-d")
);

$this->newsModel->addNews($ad_ne_data);
$i=0;
while($i < count($this->do_one_upload())) {
// var_dump($this->do_one_upload());
$ad_imgs_news =array(
'title' => $this->do_one_upload()[$i]['client_name'],
'file_path' => $this->do_one_upload()[$i]['full_path'],
'type' => $this->do_one_upload()[$i]['file_type'],
'size' => $this->do_one_upload()[$i]['file_size'],
'img_news_id' => $this->newsModel->getLastNewsId()
);
$i++;
$this->fileModel->addUpload($ad_imgs_news);
var_dump($ad_imgs_news);
}
}



the news model

the get Last news id inserted ;

public function getLastNewsId()
{
$last_id = $this->db->insert_id();
return $last_id;
}


the upload inset method in upload model

public function addUpload($data)
{
// $this->db->set('name', $name);
$this->db->insert('upload', $data);
}



So where the problem are in db or in code or???

Thanks,
Regards

Answer

try to return

$last_id = $this->db->insert_id();

from

$this->newsModel->addNews($ad_ne_data);

Get the insert_id immediately after the query in addNews function.

Comments