Saving image in the database not working properly - php

I am trying to create a cross platform application and I would like to save images from different devices in the database using Codeigiter. I am able to select the images form the device but I am confused and stocked on how to save images and retrieving them from the database.
Controller
function addstatesoothing() {
// write user data into the user database
$config['upload_path'] = './';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000000';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
$image_path = $this->upload->data('soothing-img');
$data = array(
'soothing-img' => $image_path[full_path],
'soothing-title' => $this->input->post('soothing-title'),
);
$this->favourite_db->addstatesoothing($data);
$this->load->view('soothing');
}
Model
function addstatesoothing($data) {
$this->load->database();
$this->db->insert('soothing', $data);
return $data;
}
View
<form method="post" action="addstatesoothing">
<!-- <button data-theme="d" onclick="capturePhoto();">Capture Photo</button> -->
<a data-theme="d" onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Click to Add Pictures</a>
<img style="width:100%;" id="largeImage" src="" name="soothing-img"/> <br>
<input type="text" name="soothing-title" id="Climbed a Mountain" value="" placeholder="Climbed a Mountain"/>
<button data-theme="a">Save Memory</button>
</form>

To save image in database:
1 - Your image field on database should be BLOB type.
2 - Get file content from your image:
$image = file_get_contents($_FILES['image']['tmp_name']);
3 - Save it in your BLOB type field on database
mysql_query("insert into images (image) values ('$image') ");
I don't know if you use another approach to save data in database, your code is a bit different , but that's the way, right? In the end it'll be a row inserted in database, If you have any doubt, comment here, but at this point is all easy, ham? now let's go to retriving images
First of all, storing images content in database is a real mistake, but that isn't the question right? So I'm not an expert in this approach, but is how I would:
Create an another page like image.php, receiving some id or image name by parameter
image.php:
<?php
$id = $_GET['id'];
$query = "SELECT image FROM images WHERE `id`=$id";
$result = mysql_query($query);
header("Content-type: image/jpeg"); //if is another format like .png change here
while($row = mysql_fetch_assoc($result))
{
echo $row['image'];
}
?>
Nice, you have a nice *.php file that response an image just like any *.jpg file, so now call it in your HTML
SomePage.html:
<img src="image.php?id=12345" />
Ok, all done,
but why I told that saving image content is bad?: SO fellas are awesome, we have amazing material to explain why saving images in database is BAD! You could check it, here's:
Storing Images in DB - Yea or Nay?
Store images in database or on file system

The first thing in this question is your form is not able to upload image because your not using multipart form data
you can try like this
<form enctype="multipart/form-data"></form>

Related

Updating Images Array

I have a table named tabel_foto which has 2 fields inside it, they are
foto (which contains the image's name), and
kondisi (which contains the image's description)
foto and kondisi's field value is from an-imploded multiple image upload. In other words, i have an upload form which it can upload multiple images, and those images are imploded before they are INSERTED into the sql table, like this :
I can show the image from my table as a list like this :
Please ignore it's bad layout, it's just a prototype/experiment before i add a new feature to my site
My question is, how to update those images to my table? I only want to update the image that is changed, i.e :
foto's field value is borobudur.jpg, bromo.jpg, merapi.jpg, prambanan.jpg, if i update the second image (bromo.jpg) from the form, i only want to update the "bromo.jpg" string in the foto field, how do i detect which image is changed on the form in php since the file upload button is a single file upload (not multiple upload) :
for($i = 0; $i < count($xplode_foto); $i++) {
?>
<img src="<?php echo $xplode_foto[$i]; ?>" id="<?php echo $i; ?>">
<input type="file" id="<?php echo $i; ?>" name="foto_kondisi" onChange="previewFotoJalan(this, this.id)">
<?php
}
Thanks in advance, i appreciate any solutions and answers :)
I would strongly suggest you to use a different mysql schema, like this.
photo_id
group_id
kondisi
Also, you can send a ajax request after every picture's upload , and refresh the page (or just a div).
This will make your life easier.. believe me... been there.
Success!!
Considering you save images on table column as img1,img2,img3 and description as desc1,desc2,desc3
and considering you use explode to update image.
you can make change like that:
<?php
$id = $_POST['imgid'];
//get images string from db and save to $x;
$images_array = explode(',', $x);
unset($images_array[$id]);
$y = implode (',', $images_array);
// now save again $y to db as images
//get description string from db and save to $x;
$desc_array = explode(',', $x);
unset($desc_array [$id]);
$y = implode (',', $desc_array);
// now save again $y to db as desc
Hope this help you

READ empty file image in Codeigniter

which i need to update the profil user with or without user's photo profile, here my code in view
<input type="file" name="file_foto" class="form-control">
how i can read the file is empty or not, to chose when update data is with image or without image.
and how to make unlink image to delete previouse image in Codeigniter. thanks
here is my Controller
if (empty($_FILES['file_foto']['name'])) {
$data_profil = array(
'name'=>$name
);
}else{
$foto_up = $this->do_upload_image('file_foto');
$data_profil = array(
'name'=>$name,
'foto'=>$foto_up['file_name']
);
}
if($_FILES['file_foto']['name'])){
code to upload image
}
oh sory all, my problem now solve, just use this code
if (empty($_FILES['file_foto']['name']))

Trying to display images from a filesystem in php

Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end

Codeigniter multiple images upload, get each filename

I am using the code below to handle image upload. Every thing is going fine. I have allowed the option to upload two images, one will be the logo and another the screenshot.
Now when I am providing the option to edit the uploads, say choose new files to upload and replace the old ones, I am having this problem.
In my images[] array, I will get the image names one by one with the help of loop. However when the user wants to change the second image(screenshot) and selects nothing in the logo field, only screenshot should be changed.
But in the images[] array, the first element will be the first from the uploads. If i select both the images it is all right, I will get logo.jpg in images[0] and screenshot.jpg in images[1]. But when I select only the second image, i will get screenshot.jpg in images[0]. However, the first element of the array should be blank and the second element of the array should have the data of the second image upload option so the the changes to take into effect. How can i acheive that?
$config['upload_path'] = '../uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
$image = array();
foreach ($_FILES as $key => $value) {
if (!empty($value['tmp_name'])) {
if ( ! $this->upload->do_upload($key)) {
$error = array('error' => $this->upload->display_errors());
//failed display the errors
} else {
//success
$data = $this->upload->data();
$image[]= $data['file_name'];
}
}
}
Remember, You must to initialize the upload library with each upload.
$this->load->library('upload');
$this->upload->initialize($config);
User guide: http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
Edit:
You can check the $_FILES array and check if there are the name of the screenshot input and the logo input, if they aren´t, you can create the array you need
I´ve found this:
A simpler way to have create that data structure is to name your HTML file inputs different names. >If you want to upload multiple files, use:
<input type=file name=file1>
<input type=file name=file2>
<input type=file name=file3>
Each field name will be a key in the $_FILES array.
http://www.php.net/manual/es/features.file-upload.multiple.php#53933

uploading image to mysql using php

I am new to php and trying to upload an image file in mysql database using php.I tried various tutorial but it didnot work for me.
Code Snippet:-
<?php
//connect to database. Username and password need to be changed
mysql_connect("localhost", "root", "");
//Select database, database_name needs to be changed
mysql_select_db("yelldb");
if (!$_POST['uploaded']){
//If nothing has been uploaded display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
ENCTYPE="multipart/form-data">
Upload:<br><br>
<input type="file" name="image"><br><br>
<input type="hidden" name="uploaded" value="1">
<input type="submit" value="Upload">
</form>
<?php
}else{
//if the form hasn't been submitted then:
//from here onwards, we are copying the file to the directory you made earlier, so it can then be moved
//into the database. The image is named after the persons IP address until it gets moved into the database
//get users IP
$ip=$_SERVER['REMOTE_ADDR'];
//don't continue if an image hasn't been uploaded
if (!empty($image)){
//copy the image to directory
copy($image, "./temporary/".$ip."");
//open the copied image, ready to encode into text to go into the database
$filename1 = "./temporary/".$_SERVER['REMOTE_ADDR'];
$fp1 = fopen($filename1, "r");
//record the image contents into a variable
$contents1 = fread($fp1, filesize($filename1));
//close the file
fclose($fp1);
//encode the image into text
$encoded = chunk_split(base64_encode($contents1));
//insert information into the database
mysql_query("INSERT INTO servicelist (ImgData)"."VALUES ('$encoded')");
//delete the temporary file we made
//unlink($filename1);
}
}
?>
We don't save out the whole image in our database usually. We go through inserting the permanent of picture in our database. Use this php function
move_uploaded_file(file,newloc)
This will move from your temporary directory to permanent directory. Then, get path from there and insert that to the database.
Typically, you wouldn't save an entire image into an SQL database. Instead, you store the on disk path or some other 'pointer' to the actual file.
Change your code to read something like the following:
//don't continue if an image hasn't been uploaded
if (isset($_POST['image'])){
$image = $_POST['image'];
//copy the image to directory
$path = "/some/path";
move_uploaded_file($image,$path);
//store the name and path. PS: you will want to validate your input, and look
//at using prepared statements.
//Concentating values like this is NOT safe, or ideal
$location = $path . "/" . $image
mysql_query("INSERT INTO servicelist (ImgData) VALUES (" . $location . ")");
}
If however, you still wish to store the image in the SQL database, look into the blob storage type, not encoded text.
PHP move_uploaded_file

Categories