Page 1 of 1
Get names from foreach and insert them in the db
Posted: Tue Sep 20, 2011 5:18 pm
by Kleidi
Hello,
I have a simple image multi uploader that uploads images on the folder correctly but i don't know how to get the image names and insert them in the db. The uploader is part of a complex form for adding an article informations (id, name, permanenturl, section, etc) that works correctly.
Image fields in db has names as follows: img1 img2 img3 img4 im5, a field for each image (since i thought that this is the best way to add the images on the article).
The upload sections looks like this:
Code: Select all
<?php
/**
* Smart Image Uploader by @cafewebmaster.com
* Free for private use
* Please support us with donations or backlink
*/
$upload_image_limit = 5; // How many images you want to upload at once?
$upload_dir = "/var/www/tour/te-ngarkuara/oferta/"; // default script location, use relative or absolute path
################################# UPLOAD IMAGES
foreach($_FILES as $k => $v){
$img_type = "";
### $htmo .= "$k => $v<hr />"; ### print_r($_FILES);
if( !$_FILES[$k]['error'] && preg_match("#^image/#i", $_FILES[$k]['type']) && $_FILES[$k]['size'] < 1000000){
$img_type = ($_FILES[$k]['type'] == "image/jpeg") ? ".jpg" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/gif") ? ".gif" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/png") ? ".png" : $img_type ;
$data = (date("jnHi")); // Merr daten dhe oren ne momentin e shtimit te fotografise
$img_rname = $data."-".$_FILES[$k]['name']; // shton daten dhe oren perpara emrit te fotografise per te krijuar emer unik
$img_rname = str_replace(" ","-",$img_rname); // Heq hapesirat dhe i zevendeso me -
$img_path = $upload_dir.$img_rname;
copy( $_FILES[$k]['tmp_name'], $img_path );
chmod("$img_path",0777);
$feedback .= "Image and thumbnail created $img_rname<br />";
}
}
############################### HTML FORM
while($i++ < $upload_image_limit){
$form_img .= '<label>Image '.$i.': </label> <input type="file" name="uplimg'.$i.'"><br />';
}
$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />
</form>
';
echo $htmo;
Can anyone help me on this, please?
Thank you in advance!
Re: Get names from foreach and insert them in the db
Posted: Wed Sep 21, 2011 12:29 am
by Neilos
If the image names reside in $img_rname in the foreach loop (which it seems to be) then I would make an array adding the image name to the array each time you iterate through the foreach.
Then you can make a database query like so...
Code: Select all
$i=0
foreach () {
$imageNames[$i] = $img_rname;
$i++;
}
$string = "";
foreach($imageNames as $value) {
$string .= $value . ","
}
$string = substr($string,0,-1);
$query = mysql_query("INSERT INTO image_table (images) VALUES ('$string');");
The way I have done it gives you a comma delimited string of image names so you don't always have to have the same ammount of images, it is a bit more dynamic that how you were going about it and would be my preferred option. To retrieve the names just use explode().
Of course here
image_table is the table containing the image names
images is the field. Don't forget to connect to your database too! You can extend this to add each image to a separate field too if that is what you want.
Does this help?
Re: Get names from foreach and insert them in the db
Posted: Wed Sep 21, 2011 7:42 am
by Kleidi
Neilos wrote:If the image names reside in $img_rname in the foreach loop (which it seems to be) then I would make an array adding the image name to the array each time you iterate through the foreach.
Then you can make a database query like so...
Code: Select all
$i=0
foreach () {
$imageNames[$i] = $img_rname;
$i++;
}
$string = "";
foreach($imageNames as $value) {
$string .= $value . ","
}
$string = substr($string,0,-1);
$query = mysql_query("INSERT INTO image_table (images) VALUES ('$string');");
The way I have done it gives you a comma delimited string of image names so you don't always have to have the same ammount of images, it is a bit more dynamic that how you were going about it and would be my preferred option. To retrieve the names just use explode().
Of course here
image_table is the table containing the image names
images is the field. Don't forget to connect to your database too! You can extend this to add each image to a separate field too if that is what you want.
Does this help?
Thank you very much for your help Nelios. I have tried to use your code with minor changes but i got an error. The code looks like this
Code: Select all
$foto=0;
foreach() {
$imageNames[$foto] = $img_rname;
$foto++;
}
$string = "";
foreach($imageNames as $value) {
$string = $value . ",";
}
$ofertaFoto = substr($string,0,-1);
and the error is:
Parse error: syntax error, unexpected ')' in /var/www/tour/admin/oferta_add.php on line 61
where line 61 is:
Thank you!
Re: Get names from foreach and insert them in the db
Posted: Thu Sep 22, 2011 1:49 pm
by Neilos
you must supply arguments in the foreach() loop.
That foreach was meant to be the one where you set the $img_rname variable, ie this one...
So your actual code might look like this...
Code: Select all
<?php
/**
* Smart Image Uploader by @cafewebmaster.com
* Free for private use
* Please support us with donations or backlink
*/
$upload_image_limit = 5; // How many images you want to upload at once?
$upload_dir = "/var/www/tour/te-ngarkuara/oferta/"; // default script location, use relative or absolute path
################################# UPLOAD IMAGES
$i = 0; // initialise $i
foreach($_FILES as $k => $v){
$img_type = "";
### $htmo .= "$k => $v<hr />"; ### print_r($_FILES);
if( !$_FILES[$k]['error'] && preg_match("#^image/#i", $_FILES[$k]['type']) && $_FILES[$k]['size'] < 1000000){
$img_type = ($_FILES[$k]['type'] == "image/jpeg") ? ".jpg" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/gif") ? ".gif" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/png") ? ".png" : $img_type ;
$data = (date("jnHi")); // Merr daten dhe oren ne momentin e shtimit te fotografise
$img_rname = $data."-".$_FILES[$k]['name']; // shton daten dhe oren perpara emrit te fotografise per te krijuar emer unik
$img_rname = str_replace(" ","-",$img_rname); // Heq hapesirat dhe i zevendeso me -
$img_path = $upload_dir.$img_rname;
copy( $_FILES[$k]['tmp_name'], $img_path );
chmod("$img_path",0777);
$feedback .= "Image and thumbnail created $img_rname<br />";
$imageNames[$i] = $img_rname; // construct the array
$i++; // increment $i
}
}
$string = ""; // initialise the string
foreach($imageNames as $value) {
$string .= $value . ","; // I was missing a semi colon here, this constructs the string
}
$string = substr($string,0,-1); // removes the last comma
$query = mysql_query("INSERT INTO image_table (images) VALUES ('$string');"); // the mysql insert query, DON'T FORGET TO CONNECT TO DB FIRST
############################### HTML FORM
while($i++ < $upload_image_limit){
$form_img .= '<label>Image '.$i.': </label> <input type="file" name="uplimg'.$i.'"><br />';
}
$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />
</form>
';
echo $htmo;
Re: Get names from foreach and insert them in the db
Posted: Fri Sep 23, 2011 1:35 pm
by Kleidi
Neilos, thank you very very much. It worked

Images are uploaded at server and their names inserted correctly to the db row. It looks great now. The problem is, when i should update the article. I don't know how to deal with it. Any suggestion on it?
Thanks again.

Re: Get names from foreach and insert them in the db
Posted: Fri Sep 23, 2011 8:15 pm
by Neilos
When you update the article I assume that you'll be
- Keeping some images
- Deleting other images
- Uploading new images
So you will have three different scenarios to deal with. The way I would do it is to have a comma delimited list stored in the database (like how I explained earlier) then you select this field from the table, use
Code: Select all
$images = explode(",", $imageList);
leaving you with an array which you then add to, delete from, and leave some the same, you can even reorder it if necessary. Then I'd use a foreach loop to generate the comma delimited string to place it back in the database.
There are a million different ways to do it so if you give more info on how you intend to update the page then people may have more specific advice for you.
ps. glad you got the uploader working

Re: Get names from foreach and insert them in the db
Posted: Sat Sep 24, 2011 8:38 am
by Kleidi
Neilos wrote:When you update the article I assume that you'll be
- Keeping some images
- Deleting other images
- Uploading new images
So you will have three different scenarios to deal with. The way I would do it is to have a comma delimited list stored in the database (like how I explained earlier) then you select this field from the table, use
Code: Select all
$images = explode(",", $imageList);
leaving you with an array which you then add to, delete from, and leave some the same, you can even reorder it if necessary. Then I'd use a foreach loop to generate the comma delimited string to place it back in the database.
There are a million different ways to do it so if you give more info on how you intend to update the page then people may have more specific advice for you.
ps. glad you got the uploader working

Thanks again for helping me.
I have a form that gets informations from db and fill's it. After that i can made the needed modifications and update the db. The way you suggest, is the best way, i think, since the upload/insert images works at the same direction: comma delimited image names in a single field of db.
So, need a way to keep some images and to delete some images, upload new images and all modifications to reflect in the database.
Thanks

Re: Get names from foreach and insert them in the db
Posted: Sun Sep 25, 2011 1:01 am
by Neilos
The way I would do it then is to build myself some sort of CMS (Content Management System) page where I get all the info from the database for the page I want to update. I think that this is what you are saying you are doing with the form yes?
In other words your edit.php page gets info from the database and uses that to populate a form. If this is what you are doing then good.
To simplify things I would attack it as a three part problem, rather than trying to do it all in one big update. You have most of the code required for the upload new images part of it, the one thing that you do not take into account is the fact that there may already be a string of image names in the database that you simply overwrite. You can modify that with a simple step that you have a query to retrieve the string first (bare in mind that there won't be a comma after the last image). I would make it Default: Null in the database for image names and then check if the select returns a field of null, if not then $string = the field and then add a comma and proceed as normal.
You then need a delete images part, well this could simply be that you get rid of the reference to the image in the string but actually leave the image on the server, but you might want to delete the image too. to build the delete list I would use a foreach similar to what you already have to populate a load of select boxes and then POST that form top a delete handler. the delete handler will be passed the string from the database along with all names to delete, it will make an array of those names then perform the removal of the name from the array and delete the file, delete files with
http://www.tizag.com/phpT/filedelete.php.
The last thing to do would be implement something to change the order.
Give it a try and see what you come up with, we can always help more if you get stuck.
Re: Get names from foreach and insert them in the db
Posted: Sun Sep 25, 2011 1:29 pm
by Kleidi
Neilos wrote:The way I would do it then is to build myself some sort of CMS (Content Management System) page where I get all the info from the database for the page I want to update. I think that this is what you are saying you are doing with the form yes?
In other words your edit.php page gets info from the database and uses that to populate a form. If this is what you are doing then good.
To simplify things I would attack it as a three part problem, rather than trying to do it all in one big update. You have most of the code required for the upload new images part of it, the one thing that you do not take into account is the fact that there may already be a string of image names in the database that you simply overwrite. You can modify that with a simple step that you have a query to retrieve the string first (bare in mind that there won't be a comma after the last image). I would make it Default: Null in the database for image names and then check if the select returns a field of null, if not then $string = the field and then add a comma and proceed as normal.
You then need a delete images part, well this could simply be that you get rid of the reference to the image in the string but actually leave the image on the server, but you might want to delete the image too. to build the delete list I would use a foreach similar to what you already have to populate a load of select boxes and then POST that form top a delete handler. the delete handler will be passed the string from the database along with all names to delete, it will make an array of those names then perform the removal of the name from the array and delete the file, delete files with
http://www.tizag.com/phpT/filedelete.php.
The last thing to do would be implement something to change the order.
Give it a try and see what you come up with, we can always help more if you get stuck.
Wow...thanks for the explain.
I have an edit page that populates all the fields with infos got from database. I know that, to get the images i should use explode, but the problem starts when i need to modify the images on the database; also, an if statement should be use (i suppose) in case of image modifications or not (if input field of image is nul, update the db with new images - else, update the db without image modifications).
I'm new on this and i'm learning by myself via examples and tutorials. All i now is from examples

Thanks again for your help.
Re: Get names from foreach and insert them in the db
Posted: Mon Sep 26, 2011 9:00 am
by Neilos
Kleidi wrote:but the problem starts when i need to modify the images on the database
Are you storing the images in the database? Or just the location of the images? (the latter is better imho)
What I would have is this; A database with a filed containing a comma delimited list of image names, all images stored in the file system (public_html/images or similar).
A simple example for deleting images would be;
Code: Select all
<?php
// form for deciding what to delete
$page = "whateverpage"
$query = mysql_query("SELECT * FROM pages WHERE page = '$page';");
$page_data = mysql_fetch_array($query, MYSQL_ASSOC);
$images = explode(",", $page_data['images']);
echo '<form action="delete.php" method="post">';
echo '<input type="hidden" value="' . $page . '" name="page" />';
foreach ($images as $image) {
echo '<input type="checkbox" name="images[]" value="' . $image . '" />' . $image . '<br />';
}
echo '<input type="submit" value=" Delete " />';
echo '</form>'
?>
Then deal with the form;
Code: Select all
<?php
// delete.php
$postImages = $_POST['images'];
$page = $_POST['page'];
$query = mysql_query("SELECT * FROM pages WHERE page = '$page';");
$page_data = mysql_fetch_array($query, MYSQL_ASSOC);
$images = explode(",", $page_data['images']);
$imagesString = "";
foreach ($images as $image) {
if (in_array($image, $postImages)) {
$path = 'images/' . $image;
unlink($path);
} else {
$imagesString .= $image . ",";
}
}
if (strlen($imagesString) > 0) {
$imagesString = substr($string,0,-1);
}
$updateQuery = mysql_query("UPDATE pages SET images='$imagesString'
WHERE page='$page';");
?>
A limitation is that no two pages can use the same image else when you delete it the other page won't have it there for use anymore, but there are ways round this you just have to find them lol
I haven't checked that code but the logic is ok lol!
That is how I would approach it, I can't be bothered to write all the code for you but that should get you most of the way there if you cannibalise the upload code you already have for the rest lol!