[英]Insert data into database using codeigniter 3
我不確定我的問題是否措辭正確,所以請隨時告訴我進行更改。
我允許一次上傳多個圖像,然后將文本作為 html img 插入到數據庫中。
這是我的代碼:
if ( ! $this->upload->do_upload('post_image'))
{
$this->session->set_flashdata('post_message', $this->upload->display_errors());
$this->session->set_flashdata('post_message_class', 'alert-danger');
redirect('/user/profile/'.$identity, 'refresh');
}
else
{
$uploaded = $this->upload->data();
// insert pos
if(isset($uploaded['file_name']) && $uploaded['file_name'] == 0){
$post_text = '<img src="/uploads/images/'.$uploaded['file_name'].'" width="251px" alt="'.$uploaded['raw_name'].'" /><br>'.$this->input->post('post_text');
}
else
{
foreach ($uploaded as $images){
$post_text = '<img src="/uploads/images/'.$images['file_name'].'" width="251px" alt="'.$images['raw_name'].'" /><br>'.$this->input->post('post_text');
}
}
$query = $this->user_model->insert_user_posts($this->input->post('poster_id'), $this->input->post('profile_id'), $this->input->post('post_type'), $post_text);
$this->session->set_flashdata('post_message', 'Image has been posted!');
$this->session->set_flashdata('post_message_class', 'alert-success');
redirect('/user/profile/'.$identity, 'refresh');
}
編輯:這是模型的代碼:
public function insert_user_posts($poster_id, $profile_id, $post_type, $post_text)
{
// Users table.
$data = array(
'poster_id' => $poster_id,
'profile_id' => $profile_id,
'post_type' => $post_type,
'post_text' => $post_text,
'datetime' => time()
);
$this->db->insert($this->tables['users_posts'], $data);
if($this->db->affected_rows() > 0)
{
$this->set_message('upload_successful');
return TRUE;
}
else
{
return FALSE;
}
}
另外,我正在使用這個: https : //github.com/avenirer/MY_Upload
如果我echo
或var_dump
$post_text
它將顯示兩個圖像的數據,但它只插入第一個圖像。 我在這里做錯了什么?
如果您想將圖像附加到同一個$post_text
變量中,您必須更改這一行: $post_text = '<img src="/uploads/images/'.$images['file_name'].'" width="251px" alt="'.$images['raw_name'].'" /><br>'.$this->input->post('post_text');
通過將賦值運算符=
更改為連接運算符.=
如下所示:
$post_text .= ...
而不是每次都覆蓋$post_text
變量,而是將每個圖像添加到它的末尾。 我可以猜測您最終的 foreach 循環可能如下所示:
$post_text = ""; foreach ($uploaded as $images){ $post_text .= '<img src="/uploads/images/'.$images['file_name'].'" width="251px" alt="'.$images['raw_name'].'" />'; } $post_text .= '<br>'.$this->input->post('post_text');
這將創建一個字符串,其中包含一行中的所有圖像,最后是'<br>'.$this->input->post('post_text');
. 請注意,您必須首先將$post_text
變量實例$post_text
某些內容(這里我將其設置為空字符串),以便使用連接運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.