I am new to php. I am uploading multiple files from a form along with other inputs to database. Files complete path and name should be inserted in DB in a single column with commas. How do I do that?
$filename = $_FILES['file']['name'];
$folder = "/var/www/html/PhpProject1/";
for($i=0; $i<count($_FILES['file']['name']);$i++)
{
move_uploaded_file($_FILES['file']['tmp_name'][$i], $folder.$_FILES['file']['name'][$i]);
}
$stmt = $conn->prepare("INSERT INTO studentrecords(name, email, mobileno,address,gender,filename) values (?,?,?,?,?,?)");
$stmt->bind_param("ssssss",$name,$email,$mobno,$address,$gender,$filename);
$stmt->execute();
echo "Successfull";
$stmt->close();
$conn->close();
You need to keep the paths in an array, because you are uploading multiple files. So here i am using $paths array to store the paths.
And in the insert query i am using implode function to convert array to string (with comma). This way you can store all paths as a comma separated value in a single column.
This is your solution
$filename = $_FILES['file']['name'];
$folder = "/var/www/html/PhpProject1/";
$paths = array();
for($i=0; $i<count($_FILES['file']['name']);$i++)
{
$paths[] = $folder.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i], $folder.$_FILES['file']['name'][$i]);
}
$stmt = $conn->prepare("INSERT INTO studentrecords(name, email, mobileno,address,gender,filename) values (?,?,?,?,?,?)");
$stmt->bind_param("ssssss",$name,$email,$mobno,$address,$gender,implode(",",$paths));
$stmt->execute();
echo "Successfull";
$stmt->close();
$conn->close();
Related
I'm having an issue appending a file name variable to a string in a sql insert like so
$insert = $mysqlConn->query("INSERT into images (image_name, url) VALUES ('".$fileName."', 'images/".$fileName."'");
I can do it with just the $fileName and it works fine but my syntax is wrong. I'm simply trying to make sure that every file name inserted starts with 'images/'
So if I'm inserting 'red.jpg' it would be 'images/red.jpg'
You can store image value into one variable
$imgPath = 'images/'.$fileName;
Above variable you can pass into the query
try this,you are missing one bracket
$insert = ("INSERT into images (image_name, url) VALUES ('".$fileName."', 'images/".$fileName."')");
I'm trying something with file upload and sql lately, and I have this small problem. When I'm trying to insert this string to sql, the sql insert different value. Here is the text I'm trying to insert.
C:\xampp\tmp\phpCD2.tmp
and here is the text inserted in mysql
C:xampp mpphpCD2.tmp
so from what I see the php/mysql remove all the '\' and convert the '\t' to a tab or spaces. I know it will be fix if I change the directory but what if I have some file starting with 't' so it will be remove, so How can I fix this. Thanks.
Here is the code:
foreach ($files['name'] as $position => $file_name)
{
$name = $files['name'][$position];
$tempName = $files['tmp_name'][$position];
$type = $files['type'][$position];
$size = $files['size'][$position];
echo $tempName, '<br>';
$insert = "INSERT INTO " . $table . " (id, name, tempName, type, size)
VALUES ('', '$name', '$tempName', '$type', '$size') ";
mysql_query($insert);
}
You have to escape the string.
$tempName = mysql_escape_string($files['tmp_name'][$position]);
I'm pretty new to PHP. I hate to have to ask questions, because I'm sure this is documented somewhere, but after looking for a while, I just cannot seem to put two and two together.
I have a program that will allow multiple images to be uploaded to an item within the database. Basically, for each item in the database, there might be multiple image uploads.
Example:
Item: Xbox 360
Images:
Xbox360.jpg
side.jpg
front.jpg
The image and item information is all stored in the database (MySQL), but the images are stored within the filesystem, and the database points to the URL of the image(s) in the filesystem.
The problem I'm having is that everything works as expected, except it allows duplicate image names to be written to the database. It doesn't allow duplicate images to be written to the filesystem, which I'm happy with. I want to make sure that the name of an image is only added once to the database. If the image name is a duplicate to another, it needs to not write to the database.
add_db.php:
$uniqueDir = uniqid();
$directory = "img/$uniqueDir/";
db_addItem($id_category, $name, $cost, $description, $qty, $directory); //Adds to the `items` table
foreach ($_FILES['i_file']['name'] as $filename) {
if ($filename != '' && $filename != 'No file chosen') {
//I think above is where I check for unique image names
$url = "img/$uniqueDir/$filename";
db_addImg($url, $filename); //Adds to the `img` table
$item_picsID = get_item_PicsID($filename, $url);
$itemID = get_itemID($directory);
db_insertImg($itemID, $item_picsID);
}
}
addFilesystem($directory); //Writes image(s) to filesystem
function db_addImg($url, $filename) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO img (`name`, `url`) VALUES(:filename, :url)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':filename' => $filename,
':url' => $url
));
}
function db_insertImg($itemID, $item_picsID) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO `item_pics` (`item_id`, `img_id`) VALUES(:itemID, :item_picsID)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':itemID' => $itemID,
':item_picsID' => $item_picsID
));
$db = null;
return;
}
Everything works, except it will write duplicate image names to the database. I want the image names to be distinct. I also don't want to rename the images (if possible).
You can define an UNIQUE index on the name column in img table, and then use slightly modified INSERT statement in your db_addImg function:
function db_addImg($url, $filename) {
//...
$query = "INSERT INGORE INTO img (`name`, `url`) VALUES(:filename, :url)";
//...
}
It will quietly cancel any insert where the is a UNIQUE key collision, which will end up in distinct filenames across your img table.
I would use a filename based on the primary key from the img table as you're guaranteed it's unique.
Otherwise, you'll need to guess a unique filename with some type of hashing and then check the file system. All of which can be expensive operations.
Looks like you are using PDO, so the static method lastInsertId will get the last insert id (primary key).
For example:
// after your insert to img
$filename = 'img' . $db->lastInsertId() . $extension;
This will require changing the img table slightly. But you're better off storing meta data (file type, size, etc) in this table as opposed to the file location (as that can change).
I think better to use hash value of your url as the primary key. Be cause string searching is much slower as int.
I have a question about PHP arrays and inserting them as single records into a MySQL database. I have the array sorted and that is working as it should.
This is what I have for the array:
$files = array();
foreach($_FILES['file']['tmp_name'] as $key => $tmp_name )
{
$files[$key] = array
(
$file_name = $_FILES['file']['name'][$key],
$file_type=$_FILES['file']['type'][$key],
$file_size =$_FILES['file']['size'][$key],
$file_tmp =$_FILES['file']['tmp_name'][$key]
);
}
This is what I have for the array to insert them as separate rows in to the database:
$new = array();
foreach($files as $key => $value)
{
$new[] = "'".implode("','", $value)."'";
}
$query = "(".implode("), (",$new).")";
$sqlone = "INSERT INTO files (filename, filetype, filesize, filetempname) VALUES ".$query."";
if (!mysql_query($sqlone, $conn))
{
die("Error: " . mysql_error().".");
}
The issue I am running into is this: I want to add extra information to the query but I am not entirely sure how to do this.
I want to be able to add a reference to the email that the files were attached to. I basically want the query to be as follows:
$sqlone = "INSERT INTO files (filename, filetype, filesize, filetempname, mailid //this is the extra column in the database) VALUES ".$query.", '1'// this is the corresponding value";
The issue I am running in to is that I get an error when trying to add extra information to it.
Are there any pointers you guys could give me?
Thanks in advance
Just change where your parenthesis is added (and quote your inputs):
$query = "('".implode("'), ('",$new);
$sqlone = "INSERT INTO files (filename, filetype, filesize, filetempname, mailid) VALUES ".$query."', '1')";
Should result in the SQL:
INSERT INTO files (filename, filetype, filesize, filetempname, mailid) VALUES
('<file_name>', '<file_type>', '<file_size>', '<file_tmp_name>', '1')
i am trying to upload multiple files and then insert the files names in mysql db
my problem is with inserting the names it only store the last file name
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
}
}
notice that all the files are uploaded successfully
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
}
}
you are just creating a string and storing some value. you have not executed it ..
Say $str = "apple"; Its just a declaration. I presume you have executed the query after the loop. Say you have 10 files. loop gets executed 10 times and $na has the last filename which gets inserted.
Soln: move your execute query inside the for loop.
for($i=0;$i<count($_FILES['file']['size']);$i++){
if(strstr($_FILES['file']['type'][$i], 'image')!==false){
$file = 'uploads/'.time().' - '.$_FILES['file']['name'][$i];
move_uploaded_file($_FILES['file']['tmp_name'][$i],$file);
$na=$_FILES['file']['name'][$i];
$sql="INSERT INTO img (img_name) VALUES ('$na');";
mysql_query($con,$sql); // note: $con is your connection string
}
}