Updating Images Array - php

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

Related

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

How to check an IF statement every 5sec in PHP?

I have a li and inside that i have a div class="reload" that have some content that should be reloaded for every 10 sec.
<li class="b1">
<div class="reload">
</div>
</li><!--col-->
So therefore i have got a script that does just that.
<script type="text/javascript">
$('.b1').children('.reload').load('php/reload/reload.php'); // load the content at start
window.setInterval(function(e) {
$('.b1').children('.reload').load('php/reload/reload.php'); // reload the content every 10 sec
}, 10000);
In the reload.php i get some content from a database. It looks like this, sort of..
<?php
// login info
require("../../connection_to_database_login.php");
// My query
$result = mysqli_query($l,'SELECT * FROM abcd WHERE efg=1 LIMIT 1');
// include some stuff
$r = mysqli_fetch_row($result);for ($p = 0; $p < $r[4]; ++$p){include("../some/stuff_$p.php");};
// include a random picture script or just load a picture
if ($r[4] == 0){include ('getRandPic.php');}
else {echo ('<img src="images/picture.png" />');}
?>
So far so good.. everything works.
The getRandPic.php file.. select one random picture from a folder
<?php
$img_dir = "images/images";
$images = scandir($img_dir);
$html = array();
foreach($images as $img) {
if($img === '.' || $img === '..') {continue;}
if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ) {
$html[] .= '<img class="img-responsive" src="'.$img_dir.$img.'" />';
}
else { continue; }
};
echo $html[rand(0,6)];
?>
So this works ok.
But the thing is, i want to check if it shall "include a random picture script or just load a picture" every 5sec.
Therefore i need to check "if ($r[4] == 0)" every 5 sec.
So my question is: Is there any other way to do that?
As you asked in the comment... This is a rough guide only. You will have to develop and write your own code based on this guide.
Step 1a: optional
Make an ajax call from your webpage to the server. to get image file names.
Step 1b:
On server side in php file perform DB operation.
Let assume you have a table imageTable and column name images so you would read from DB using query SELECT images FROM imageTable
You will have to change the query, add condition (e.g. all images with animal and cute tags) to it and if you want limit the number of files that you want to randomize then you will have to add that as well.
Step 2:
Once you read from DB, as you are already doing, read all image names and put it in json format (json_encode). I personally prefer json. If you prefer, you can also return all names in simple string where names are separated by comma.
Step 3:
Store your response in JS.
var imagesArray = new Array();
$.ajax({
type: 'post',
url: pathtophpfile,
success: function(htmll) {
// get object with all data
imagesArray= JSON.parse(htmll);
},
});
Step 4:
Once you have it in your js object named imagesArray, use setInetval to perform task every 5 seconds.
Read a random value from 0 to imagesArrays length, and change the source of your image tag, <img class="img-responsive" src="+ randomimage +" />
Periodic updater will do your task.
Use ajax framework, it will reduce your db connection burden at the server side.
Have a look at it. It is a simple and nice way to achieve your task.
http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/

Saving image in the database not working properly

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>

Redundant way of getting multiple $_POST records?

EDIT : I might just make it a more 'step-by-step' process i.e.
Seeing as it feels more user-friendly & it's only for <5 images. I have read & appreciate all of the help that I have received so far.
I'm fairly new to PHP & I'm building a basic PHP image editor which may allow multiple image data auditing which is then inserted into a MySQL database. A limit of 5 images may be uploaded at a time for this system (implying that there will only be a low amount of records to play with), but I'll get to that further down.
GUI:
Some of the data columns used:
image id
caption
description
published
imageposition
delete button
All images are echo'd in a while loop by a previous 'SELECT *' result set. Each image will have the 'image id' echo'd inside each input name, so output will be for example:
caption-2, description-2, published-2, imageposition-2, caption-3, description-3
Also, the data values from the previous resultset are echo'd into the input value, allowing the client to edit the current data that exists in the database. There is only one submit button.
My question:
I want to be able to post all of the modified image(s) data to a processor.php form which will then allow me to insert it as an INSERT sql string into the MySQL images table. I need the PHP to be dynamic incase:
images are deleted (image id)
new images are uploaded (image id)
If there is an easier way of doing any of the above, I am welcome to new ideas/opinions. Sorry in advance for my poor understanding of PHP.
Once you get result from 'select *' statement you do foreach
foreach ($images as $image) {
?>
<img src="imagesrc">
<input type="text" name="title_<?php echo $image['image_id'] ; ?>" value="<?php echo $image['title']; ?>">
<input type="text" name="desc_<?php echo $image['image_id'] ; ?>" value="<?php echo $image['description']; ?>">
<input type="button" onclick="markDeleted('<?php echo $image['image_id'] ; ?>')">
<?php } ?>
.....
Once you receive the post value you can explode with "_" and you will get the Primary key and you can update the image table with image ID.
In the javascript function markDeleted you can set the primary key in some hidden field and sent to process.php.
Add it like comma separated 1,2,3 like this (Split by comma in action page)
function markDeleted (imageId)
{
document.getElementById('deleted_image_ids').value = imageId + ","
}
To delete the records easily :
<form action="processor.php" method="post">
<?php
foreach ($images as $img) { // assuming $images is the result set of your sql query
?>
<input type="text" name="name<?php $img['image_id'];?>" value="<?php $img['caption'];?>">
<input type="text" name="desc<?php $img['image_id'];?>" value="<?php $img['description'];?>">
...
<a href="http://yoursiteurl/deleteimg.php?id=<?php $img['image_id']?>">
<?php } ?>
</form>
In deleteimg.php :
<?php
$del = $_POST[id];
$query = $msqli->prepare("DELETE FROM imagetablename WHERE image_id=?");
$query->bind_param( 's', $del );
$query->;execute();
?>
Updating and adding new rows may involve javascript, and much more harder.

PHP: Properly storing image names in MySQL DB

I am storing images name inside on MySQL database. Everytime I perform an upload, I have it return a link back with the image name attached which then I extract the image name and saved to the database. I have corrections to some critical flaws but I am still facing issues of having blank spaces/ duplicate names inserted into my database even though I have established checkpoints.
How can I avoid duplication/blank spaces of file names?
Is there a better approach in storing names in DB?
Location of image inside webserver:
http://www.example.com/imageupload/uploads/medium/50038dc14afb7.jpg
Link in the browser:
http://www.example.org/imageupload/index.php?i=50038dc14afb7.jpg
PHP
<?
$images = retrieve_images();
insert_images_into_database($images);
function retrieve_images()
{
$images = explode(',', $_POST['i']);
return $images;
}
function insert_images_into_database($images)
{
if(!$images) //There were no images to return
return false;
$db = dbConn::getConnection();
foreach($images as $image)
{
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ( ? )";
$prepared = $db->prepare($sql);
$prepared->execute(array($image));
}
}
?>
First, the blank name issue can perharps be fixed by checking $_POST['i']:
if (!isset($_POST['i'])) {
echo "No image to upload!";
die();
}
Have you tried redirecting after uploading the image?
// When image is uploaded
header("Location: http://example.org/imageupload/index.php");
die();
you can change the image name at the time of upload,
rand() is the function, which return random value, so you can avoid the duplicate image name,
the date time option will return always new date time, so you can diffidently get unique image name
Ex.$imageName.rand().$extention;
OR
Ex. $date = new DateTime(now);
$date = $date->format('Y_m_d_H_i_s');
$imageName.$date.$extention;
a couple of things:
To make sure you have unique file names, use tempnam() (
http://php.net/manual/en/function.tempnam.php )
To avoid page reload issue, post the upload form to a different page, which redirects to a
different page (or the previous form page) after it finishes doing the upload.
This is unrelated to your question but your SQL prepared statement should be outside of the loop.

Categories