I have two tables:
first and parent "register"
and second is
What I wanted is to create a script in which one User with unique SN whenever upload a pic that pic path save in "userimg" i user SN as foreign key in userimg
code is below
if(isset($_POST['SN']))
{
$filename = $_FILES['upload_image']['name'].$user_SN;
$filesize = $_FILES['upload_image']['size'];
$filetype = $_FILES['upload_image']['type'];
$target_path ="uploads/". basename( $filename );
if (move_uploaded_file($_FILES['upload_image']['tmp_name'], $target_path))
{
$result = $target_path ;
$sql="INSERT INTO userimg (src, size, type,SN ) VALUES ('".$result."', '".$filesize."','".$filetype."','".$user_SN."')";
echo $sql." ";
echo $filesize." ";
echo $filetype." ";
$inst=mysql_query($sql);
if (!$inst)
{
print "error";
}
}
}
This script is working for one picture but what I want is like multiple uploads (just like a gallery) by user and saving that path in my second table.
Do I need to create a userimg table for each SN means user? What am I missing?
[EDIT]
Problem solved. Mistake was Making SN in userimg a unique and i rename image like this(code is below ) - Thankx Tuhin!
if(isset($_POST['SN']))
{
$filename = $_FILES['upload_image']['name'];
$filesize = $_FILES['upload_image']['size'];
$filetype = $_FILES['upload_image']['type'];
$timeSt = time();
$info = pathinfo($filename);
$name = $info['filename'];
$format = $info['extension'];
$target_path ="uploads/".basename( $name )."_".$user_SN."_".$timeSt.".".$format;
}
If the same user (means same SN value) tries to upload the same image (means already uploaded by him with same image name in this app) then the 'src' column in the second table will be same. Also if the uploaded folder first image file will be replaced by the newer file. Thats why I proposed you to add time stamp and rename the uploaded image file and store it into the DB.
Related
I add/upload image avatar using md5 user id and file_put_contents like this:
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = md5(Session::get('user_id')) . '.png';
file_put_contents(Config::get('PATH_UPLOAD') . '/' . Session::get('user_id') . '/' . $imageName, $data);
with this method I add only one image avatar for each user into my directory with this structure :
public
upload
images
avatar
77 <-- userID
d41d8cd98f00b204e9800998ecf8427e.png
Now I have two way for get image.
add image name/type into database and retrieve data from database and show in view page
get image name with session unique userId from file folder/directory without database
which way is better for performance(fast load)?!
I am uploading multiple images in the database in a single column with comma separated format. I am first creating a folder for each user and inside that folder, images are stored. car_images is my root directory inside that with the name of logged_in user new directory will create.
My images are stored in below format :
Here, emp_code is unique I am using this as SESSION and for the name of the folder of each user.
as you see car_images column where I am storing image name with ,.
I am using below code to stored images in folders and database. I don't know idea how to fetch all images of a single user.
$car_images_all="";
for($i=0; $i<count($_FILES['car_images']['name']); $i++)
{
$tmpFilePath = $_FILES['car_images']['tmp_name'][$i];
if ($tmpFilePath != "")
{
if (!file_exists('car_images/'.$emp_code))
{
mkdir('car_images/'.$emp_code, 0777, true);
}
$location = 'car_images/'.$emp_code.'/';
$name = $_FILES['car_images']['name'][$i];
$size = $_FILES['car_images']['size'][$i];
list($txt, $ext) = explode(".", $name);
$file= time().substr(str_replace(" ", "_", $txt), 0);
$info = pathinfo($file);
$filename = $file.".".$ext;
if(move_uploaded_file($_FILES['car_images']['tmp_name'][$i], $location.$filename))
{
$car_images_all.=$filename.",";
}
}
}
First of all,
Select all images from database by emp_code (as you want all images of a particular user/emp).
select car_images from TableName where emp_code = $emp_code;
Now, by this you will get one or more rows.
So, add one by one images to array with using explode() function per row (i.e. if row has multiple image name with comma separated).
Use the array as per your choice of manipulation.
Below code will fetch the data from table and save images in array. For more details check the explode function.
$query = "select car_images from table_name where emp_code = 'emp_code'";
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_assoc($result);
$images = $row['car_images'];
$images = explode(',',$images);
foreach($images AS $image){
echo '<img src="car_images/'.$emp_code.'/'.$image.'">';
}
You can use GROUP_CONCAT() function
SELECT GROUP_CONCAT(car_images) FROM TableName
You can use group by also with emp_code or brand_id or any other column whatever your business logic is met.
SELECT GROUP_CONCAT(car_images) FROM TableName GROUP BY emp_code
OR
SELECT GROUP_CONCAT(car_images) FROM TableName GROUP BY brand_id
<?php
$x=0;
$car_img =explode(",",$car_images);
foreach($car_img as $car_images{
$x+=1;0
?>
<?php echo '<img src="'."images/".$car_images.'" width="70" height="70" />';?>
I have a few questions regarding moving and removing image (path and name) in a sql database.
Here's how I upload and name the images:
if(count($_FILES['upload']['name']) > 0){
//Loop through each file
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if($tmpFilePath != ""){
//Grab file extension
$extension = pathinfo($_FILES['upload']['name'][$i], PATHINFO_EXTENSION);
//save the filename
$shortname = $name . "_" . $i . "." .$extension;
//save the url and the file
//Modify this to year, make, _, id, #
$filePath = "images/" . $shortname;
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $filePath)) {
$files[] = $shortname;
//insert into db
//use $shortname for the filename
}
}
}
} //end images
Then I take the $files[#] and insert the image name and path into the database and the image is uploaded into the images directory. My question would be, if I want to remove an image from the database or change the order it would be saved, how would I go about doing that?
For removing from database, use DELETE statement:
DELETE FROM myTable where id='$id'
Or
DELETE FROM myTable where name='$name'
You need to be sure that you are trying to delete the correct row. If you don't have a primary_key, your name column should be UNIQUE.
About order, there is no order in your database, at least not explicit. If you need to have an order, add a column, let's say, order and query with ORDER BY clause:
SELECT * FROM myTable ORDER BY order ASC
You will not have any problem with gaps in your order using this.
I have tried many hours just to get this tiny piece of information to show, I need help before I decide to brake my laptop in two pieces.
I am trying to get an uploaded image to display a caption along with username (person who uploaded it) and date. These three values are stored in my database, the upload works fine. As I loop through the directory to display my images, I cannot get these values (passed as variables) to display correctly, rather the last upload input is the only one that displays for every image in my gallery.
I assume there is something wrong in my loop code and will post it here in hope that it is a simple overlooked fact.
//Open directory
$dir_handle = opendir($thumb_dir) or die('Error opening thumbnail directory.');
while ($file = readdir($dir_handle)) { //go through files
//if ($file == '.' || $file == '..') continue;
$file_parts = explode('.', $file); //split filename and put extensions in array
$ext = strtolower(array_pop($file_parts)); //last element file extension
//Filename w/o extension.
$title = implode('.', $file_parts); //only filename
$title = htmlspecialchars($title); //security measure
$dbconnect = mysqli_connect('localhost', 'peter', '1234', 'dt091g');
$query = 'SELECT username, date FROM image_info';
$result = mysqli_query($dbconnect, $query);
while ($row = mysqli_fetch_assoc($result)){
$username = $row['username'];
$date = $row['date'];
}
//add every image if good extension
if (in_array($ext, $allowed_exts)) {
echo '<a class="example-image-link"
href="'.$img_dir.$file.'"
data-lightbox="example-set"
data-title="'.$username.$date.'">
<img class="example-image" src="'.$thumb_dir.$file.'" alt="hello"/>
</a>';
$i++; //increment the image counter
}
}
closedir($dir_handle); ?>
I am assuming I must incorporate the unique ID somehow, and I have tried myself blind, but still end up with only the last value for any row of my db table.
Appreciate any kind of input, even if you're just writing to say 'Duh! You idiot'.
EDIT: Showing a record of image_info
$image_info = array( array('id' => '50','username' => 'Peter','date'
=> '05052015','filename' => '20140808_220541.jpg','mimetype' => 'image/jpeg','filesize' => '2404856','caption' => 'Norwegian
Mountains'));
I searched Google all over the place for an answer but I can't seem to find the right one so I'll try it here.
I want to store the users' firstname, lastname and the path of the images in the mysqli database and the image in the folder uploads. (the user can upload multiple images)
This works and is no problem.
The issue is:
When for example they type their firstname and lastname and select two images and press the upload button it uploads everything but it also creates two rows with the exact same values.
I want to store everyting in one row, see my code below:
<?php
$con = mysqli_connect('localhost','root','','img_db');
mysqli_select_db($con,'img_db');
$rn = mt_rand();
if(isset($_POST['submit'])&& isset($_FILES['image'])&& !empty($_POST['firstname'])&& !empty($_POST['lastname']))
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
for($i=0; $i<count($_FILES['image']['name']); $i++)
{
$tmp_name = $_FILES['image']['tmp_name'][$i];
$max_size = 100000;
$path = "uploads/";
$name = $_FILES['image']['name'][$i];
$size = $_FILES['image']['size'][$i];
$type = $_FILES['image']['type'][$i];
$ext = strtolower(substr($name, strpos($name, '.') +1));
$name = str_replace('_','',trim($name));
$name = str_replace('-','',trim($name));
$name = str_replace(' ','',trim($name));
$name = str_replace('__','',trim($name));
if(($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')&&($type=='image/jpeg' || $type=='image/png' || $type=='image/gif')&&$size<=$max_size)
{
if(move_uploaded_file($_FILES['image']['tmp_name'][$i], $path.$rn.$name))
{
mysqli_query($con,"INSERT into `img` (firstname,lastname,url) VALUES('$firstname','$lastname','$rn$name')");
}
}// END EXT
}// END FOR LOOP
}// END IF ISSET POST SUBMIT
?>
Suggestion 1
One solution is to store uploaded file urls in an array (declared before the for loop) and utilize the array outside of the for loop, like so:
if (isset(/* ... */)) {
// Outside your for loop
$files = array();
for (/* .. */) {
// Doing things
if (/* $ext stuff */) {
if (move_uploaded_file(/* ... */))
{
$files[] = $rn.$name;
}
} // End EXT
} // End FOR
// Utilize $files array to determine how you want to store all of these URLs in one field.
// Let's say you created a variable called $store with the desired representation.
mysqli_query($con,"INSERT into `img` (firstname,lastname,url) VALUES('$firstname','$lastname','$store')");
} // End ISSET
Suggestion 2
You could use a two-table structure (one table is users, one table is images) and create a foreign key relation from each image table row to a user table row via the desired user's primary key.
See: http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html