php – how to store and retrieve images in database using CodeIgniter
php – how to store and retrieve images in database using CodeIgniter
DO NOT STORE FILES INSIDE THE DATABASE!!!
This is always a bad design idea. Store the files in the file system and simply store the file names and point to the file, it will save you a lot of headaches in the future.
// uploading
public function do_upload(){
...
$image_path=$this->upload->data();
$uploaded_image = $image_path[full_path];
// Read the file
$fp = fopen($uploaded_image, r);
$data = fread($fp, filesize($uploaded_image));
$data = addslashes($data);
fclose($fp);
// here you can easy insert $data to a_photo column.
}
// Viewing, $image_id is row id
public function getImage($image_id){
// select $row from database as usual and then
$content = $row[a_photo];
echo <img src=data:image/jpeg;base64,.base64_encode($content).>;
}
In your template:
<?php getImage(12); ?>
where 12 is row id.
php – how to store and retrieve images in database using CodeIgniter
try this code
models code
function do_upload() {
$config = array(
allowed_types => jpg|png|bmp,
upload_path=>./images1/, //make sure you have this folder
max_size=>2000
);
$this->load->library(upload,$config);
if ($this->upload->do_upload()) {
echo Upload success!;
} else {
echo Upload failed!;
}
$image_data = $this->upload->data();
}
function get_images()
{
$query = $this->db->get(animalstore);
return $query;
}
function Save_gallery($in)
{
$save=$this->db->insert(animalstore,$in);
return $save;
}
controller code
function index()
{
$this->load->model(Image_control); //call a models
if ($this->input->post(upload)) {
$in=array();
$in[a_name] = $this->input->post(a_name),
$in[a_details] = $this->input->post(a_info),
$in[a_photo]=$_FILES[userfile][name];
if($this->Image_model->do_upload()) {
echo $this->upload->display_errors();
}else {
$this->Image_model->Save_gallery($in);
header(location:index);
}
$data[images]=$this->Image_model->get_images();
$this->load->view(image_view,$data);
}
view
<?php
echo form_open_multipart(image_control/index);
echo form_input(a_name,Animal Name);
echo form_input(a_info,Animal Information);
echo form_upload(userfile);
echo form_submit(upload,Upload);
echo form_close();
?>
<?php foreach ($images as $image):?>
<h1><?php echo $image[a_name];?></h1>
<h1><?php echo $image[a_details];?></h1>
<?php echo <img src =. base_url().images1/.$image[a_photo]. >;
endforeach; ?>