Store file path in database - php

I want to store file path in database. i tried it. but it's not worked. This is my code. But it's not worked.`
//This is the directory where images will be saved
$target = "uploads/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$cat=$_POST['cat'];
$desc=$_POST['desc'];
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("selfie") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO image_upload (category, description,image_url) VALUES ('$cat', '$desc',".$_FILES['photo']['name'].")");
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Can any one help me to store file path in database

You need to put quotes around the filename. You should also escape all user-provided data, in case it contains special characters that will cause a SQL syntax error.
$filename = mysql_real_escape_string($_FILES['photo']['name']);
mysql_query("INSERT INTO image_upload (category, description,image_url, image_path) VALUES ('$cat', '$desc','$filename', '$target')");

Try to change this:
mysql_query('INSERT INTO image_upload (category, description,image_url) VALUES ("'.$cat.'", "'.$desc.'","'.$_FILES['photo']['name'].'");');
I assuming your $cat and $desc are string type.

Related

PHP upload script not working, empty variables

I've tried to add image upload to an already working script that posts a subject and description. For some reason it's failing at the point where I'm using move_uploaded_file
The file name is successfully inserting into the database and the print_r statement is showing that the file is going into /tmp. I've tried to echo and print the $tempname and $folder but they seem to be blank and I don't know why. I'm guessing this is the problem.
My php.ini and httpd.conf and permissions are all good as another upload script written by someone else works fine.
if(isset($_POST['submit']))
{
$date = date('Y-m-d H:i:s');
$subject = $_POST['subject'];
$description = $_POST['description'];
$upload_dir = './image';
$filename = $_FILES["choosefile"]["name"];
$tempname = $_FILES["choosefile"]["temp_name"];
move_uploaded_file($tempname, "$upload_dir/$filename");
$insert = mysqli_query($db,"INSERT INTO xv.post (subject, description, creation_date, image) VALUES ('$subject', '$description', '$date', '$filename')");
if(!$insert)
{
echo mysqli_error();
}
else
{
print "<p>Here is some more debugging info:</p>";
print_r($_FILES);
echo $tempname . $folder;
}
}
It should be tmp_name instead of temp_name.
So changing to below should do the trick:
$upload_dir = './image';
$filename = $_FILES["choosefile"]["name"];
$tempname = $_FILES["choosefile"]["tmp_name"];
move_uploaded_file($tempname, "$upload_dir/$filename");
$insert = mysqli_query($db,"INSERT INTO xv.post (subject, description, creation_date, image) VALUES ('$subject', '$description', '$date', '$filename')");
please add a print_r to the $_FILES to see the content:
print_r($_FILES);
Provably there is another structure that you have to get.

php file upload data is not going into mysql

<?php
include 'db.php';
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$stnam = $_POST['stName'];
$stage = $_POST['stAge'];
$stdob = $_POST['stDob'];
$pic=($_FILES['photo']['name']);
mysqli_query("INSERT INTO test (name, age, dob, photo) VALUES ('$stnam', '$stage', '$stdob', 'pic')");
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
I have been trying to upload an image file into sql database using phpmyadmin I used this above code when I executed it the file goes into directory well but the data values are not being inserted into mysql. Can anyone help?
Changes
1) Put $ before pic in insert query.
2) And, keep insert query inside if(). Because, row will get inserted even though file is not moved to desired folder.
3) No connection variable is used in mysqli_query. It requires 2 arguments. [I assumed $conn as connection variable. Replace it according to your connection variable.] For more info, click mysqli_query
Updated Code
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)){
mysqli_query($conn, "INSERT INTO test (name, age, dob, photo) VALUES ('$stnam', '$stage', '$stdob', '$pic')");
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
} else {
echo "Sorry, there was a problem uploading your file.";
}

add multiple pdf files to blobs usng php

I have to migrate a legacy database up to MySQL using PHP. One of the components of the old system is a large (>1000) list of attached files (mostly .pdf, some are .doc/.docx).
I have so far done the following:
created mysql table, with a blob to contain the file (this method has
been chosen for valid reasons)
imported all the data except the attachments
extracted all the attachments into a folder, naming each file with a unique name
added and populated in mysql a column containing the unique name of the attachment
created a file containing the full names of all the attachments in the folder.
To add a single file is the only solution that I found in stack
But my requirement is to RECURSIVELY go through the list of filenames and find the matching row in mysql, then insert the file from the folder into the blob
example ...
I have a text file with entries like this (filename, date created, size)..
024048DE44C-RUE_MA.pdf,05/24/2013,80233
024048DE44C-RUE.pdf,06/21/2013,85151
... (1000 more)
I have a file with name 024048DE44C-RUE_MA.pdf in the folder
I have a row column filename containing 024048DE44C-RUE_MA.pdf in mysql database
I think the solution is something like this, but need help in the middle bit.
$myfile = fopen("filelist.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
$attfile =fgets($myfile);
...upload the file
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'dbase');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `deal_attachment` (
`deal_att_name`, `deal_att_mime`, `deal_att_size`, `deal_att_content`, `deal_att_created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
}
fclose($myfile);
Why don't you just use mysql LOAD_FILE function if you already have a table with the filename?
UPDATE mytable SET blobdata=LOAD_FILE(concat("/path/to/", filename));
Your files need to be on your mysql server in order for it to work.
If your only problem is how to read the CSV file you can do:
list($filename,$date, $size)=explode(",", $attfile);
Adam's suggestion worked perfectly for me with the important proviso in Windows that file path must contain double backslashes (so you would construct it like this
$path = 'c:\\dir\\subdir\\' . trim($filename) ;.
Following snippet of code shows the call ..
$query = "UPDATE `attachments` SET `att_content`=LOAD_FILE('" .$path . "') WHERE `att_name` = '" . $filename ."'" ;
$result = mysqli_query($dbcon,$query) ;
// Check if it was successful (maybe add some more insurance by going back to the database to see if the file is there - it can be that no error was reported but LOAD_FILE didn't work (like if the path is invalid)
if (false === $result) {
echo mysqli_error($dbcon);
die ;
} else { echo 'Success! Your file was successfully added!'; }

Insert and select from database

i've a problem with my query. The problem is that: the file is correctly loaded in the uploads folder. But not in the database with the content of the textarea.
i ve created this table into my database with:
CREATE TABLE dati(article VARCHAR(30), photo VARCHAR(30))
this is my code (pick from internet)
<?php
//This is the directory where images will be saved
$target = "../image/";
if(isset($_FILES['photo']['name'])) {
$target = $target . basename($_FILES['photo']['name']);
//This gets all the other information from the form
}
$article = (isset($_POST['article']));
$pic = (isset($_FILES['photo']['name']));
// Connects to your Database
//Writes the information to the database
if (isset($_FILES['photo']['name'])) if (isset($_POST['article'])) {
mysql_query("INSERT INTO nome_tabella (photo, article) VALUES ('{$_FILES['photo']['name']}', '{$_POST['article']}'");
}
//Writes the photo to the server
if(isset($_FILES['photo']['tmp_name']))
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename(isset($_FILES['uploadedfile']['name'])). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
I tried several times, but does not insert data into the database. What's wrong?
This is the code for read the results
<?php
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM 'dati' (photo, article)") or die(mysql_error());
while($info = mysql_fetch_array( $data )) {
echo "<div id='cover'>";
echo "<img src='http://localhost/chiedifilm/image/".$info['photo']. "'>";
echo "</div>";
echo "" .$info['article']. "";
echo "<hr>"; } ?>
It does not load the image name and the textarea tinymce.
Im sorry for my bad english, i don't speak it very well.
Check your code:
//Writes the information to the database
if (isset($_FILES['photo']['name'])) if (isset($_POST['article'])) {
mysql_query("**NSERT** INTO nome_tabella (photo, article) VALUES ('{$_FILES['photo']['name']}', '{$_POST['article']}'");
}
where's "I" on INSERT statement
regards

PHP File Validation using If statements uploads

Hi I am quite new to php but i have been following some tutorials but they don't seem to work so I have tried to adapt them.
I have tested this code and it works to a point but theres something else I can't get my head around, the php file is not uploading (fine) but the details are still being writen to the datbase although the $ok is spose to be set to 0 (not fine). It might be easier if explain what is ment to happen here:
-The User can upload gif or jpeg files. Details added to the db.
-The User can upload no file as a default will be used. Details added to the db.
-The User should not be able to upload any other file. No record should be on the db, user should have to try again.
My Code so far:
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$ok=0;
//This gets all the other information from the form
$name= mysql_real_escape_string ($_POST['nameMember']);
$bandMember= mysql_real_escape_string ($_POST['bandMember']);
$pic= mysql_real_escape_string ($_FILES['photo']['name']);
$about= mysql_real_escape_string ($_POST['aboutMember']);
$bands= mysql_real_escape_string ($_POST['otherBands']);
$uploaded_size=$_FILES['photo']['file_size'];
if ($uploaded_size > 350000)
{
echo "Your file is too large, 35Kb is the largest file you can upload.<br>";
$ok=0;
}
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
if (!($uploaded_type =="image/jpeg"))
{
echo "JPEG<br>";$ok=1;
}
if ($uploaded_type =="image/gif")
{
echo "GIf<br>";$ok=1;
}
if (empty($pic)){
echo "You haven't uploaded a photo, a default will be used instead.<br/>";$ok=1;}
if ($ok==0)
{
Echo "Sorry your file was not uploaded, please try again with the correct format.";
}
//If everything is ok we try to upload it
else
{
// Connects to your Database
mysql_connect("localhost", "*******", "******") or die(mysql_error()) ;
mysql_select_db("project") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO dbProfile (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory<br/>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
else {
//Gives and error if its not
echo "<p>If you have uploaded a picture there may have been a problem uploading your file.</p>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
}
?>
Cheers in advance. CHL
The error probably is this if statement:
if (!($uploaded_type =="image/jpeg"))
{
echo "JPEG<br>";$ok=1;
}
Because every time you upload an image that does not have a content type that equals "image/jpeg", $ok evaluates to 1, so everything gets written to the database.
But also notice, that just checking the MIME type like this can get you into trouble, since the user is able to fake the MIME type of a file.
You could use Imagick to get the correct image MIME type, for example. See more details here: http://de2.php.net/manual/en/function.imagick-identifyimage.php
Edit: Just noticed, that $uploaded_type does not get initialized anywhere in your script. As I said, you can do a rough estimation of the MIME type by using $_FILES['photo']['type'].

Categories