To upload a image in MySql database via php - php

I am currently working on a website that needs to upload the images of different products by its users. I am implementing it by using MySql database via php.
My code for a basic form for taking input from users is:
<form enctype="multipart/form-data" action="testimage1.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
My database table is:
mysql> CREATE TABLE tbl_images (
> id tinyint(3) unsigned NOT NULL auto_increment,
> image blob NOT NULL,
> PRIMARY KEY (id)
> );
testimage1.php has the following code:-
$username = "root";
$password = "";
$host = "localhost";
$database = "thinstrokes";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db ($database);
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link) or die(mysql_error());
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
On submitting the form I am getting an error: No image selected/uploaded
I am not getting the error... and I've already asked for this before as:
mysql error during inserting a image in mysql database
How can I insert an image in a MySQL database using PHP?
But until now I am not successful in storing the image in the database.

Your script is working just fine, This is what I test:
<?
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
?>
<form enctype="multipart/form-data" action="" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
And it works just fine, if you want to see it in action I can send you the link.
It must be something else that is ruining your code (*note that I removed the DB queries to avoid getting mysql errors but the script was working even with them there.

//Here is the solution for your problem
<form enctype="multipart/form-data" action="" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
// connection to database
include 'includes/connection.php';
?>
<?php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$result = mysql_query("INSERT INTO image (image)VALUES ( '$data')", $connection);
if(!$result)
{
die("Database query failed: ". mysql_error());
}
// Print results
print "Thank you, your file has been uploaded.";
}
else
{
print "No image selected/uploaded";
}
?>
<?php
//close connection
include 'includes/close.php';
?>

Related

exporting ang retrieving data from excel to database using php

I am trying to create a feature in my program where in you could upload data to the database by uploading data from excel (uploading excel file) i have provided the code below but the data in the database is encoded(i provided a screenshot).
is there something wrong with the code?
Excel format:
firstname lastname
_____________________
amir kumar
jhon doee
But this is what the data looks like when inserted into the database:
This is my index.php:
<form enctype="multipart/form-data" method="post" action="import.php" role="form">
<div class="form-group">
<label for="exampleInputFile">File Upload</label>
<input type="file" name="file" id="file" size="150">
<p class="help-block">Only Excel/CSV File Import.</p>
</div>
<button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button>
</form>
import.php
<?php
if(isset($_POST["Import"]))
{
//First we need to make a connection with the database
$host='localhost'; // Host Name.
$db_user= 'root'; //User Name
$db_password= '';
$db= 'testdatabase'; // Database Name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
$count = 0;
$sql_data = "SELECT * FROM person";
echo $sql_data;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//print_r($emapData);
//exit();
$count++;
if($count > 1) {
$sql = "INSERT into person(firstname , lastname) values ('$emapData[0]','$emapData[1]')";
mysql_query($sql);
echo "success";
}
}
fclose($file);
echo 'CSV File has been successfully Imported';
header('Location: index.php');
}
else
echo 'Invalid File:Please Upload CSV File';
}
?>
Don't use the Excel file as is. You see what gibberish you get.
Instead, do one of these:
"Export" the data from Excel into a .csv file, then LOAD DATA into MySQL.
Use a PHP API that lets you fetch data from Excel. Then INSERT the data into a MySQL table.

How to move an uploaded file and upload the path into mySQL database? Using PHP

I would like to know how i can move my uploaded file into my database and move it to a folder on my pc.
Here is my HTML CODE:
<form method="post" name="update" action="updateform.php" enctype="multipart/form-data" />
<label>Id:</label>
<input type="text" value="<?php print ("$row[id]")?>" name="id" />
<label>Logo:</label>
<input type="file" name="file" id="fileToUpload"/>
<input id="submit" type="submit" name="Update Record" value="update" />
Here is my PHP code (it's not all of it but just the parts you need):
I already made a database connection and that's working for my other inputfields.
PHP Code:
<?php
//database connected
$id = $_POST['id'];
if (isset($_FILES['file']['tmp_name'])){
$file = $_FILES['file']['tmp_name'];
$folder="uploads/";
move_uploaded_file($file,$folder);
$handle = fopen($_FILES['file']['tmp_name'],'r');}
$query= "UPDATE config SET showimage = '$handle' WHERE id='$id'"
if (mysql_query($query)){
echo "updated";
header('Refresh:1;url=admin.php');}
else{
echo "fail";}
// Close connection
mysql_close($db);
?>
I know i'm not using PDO or MySQLi so don't say that i have to use this to prevent MySQL injections...I know that?
But can someone tell me why my file path won't save in my database and why my file doesn't want to move to my folder??
if you want the path to be saved in db you should use this -
<?php
//database connected
$id = $_POST['id'];
if (isset($_FILES['file']['tmp_name'])){
$file = $_FILES['file']['tmp_name'];
$filename = $_FILES['file']['name'];
$folder="/uc webserver formulier/root/uploads/";
move_uploaded_file($file,$folder.$filename);
$handle = $folder.$filename ;
}
$query= "UPDATE config SET showimage = '$handle' WHERE id='$id'";
if (mysql_query($query)){
echo "updated";
header('Refresh:1;url=admin.php');}
else{
echo "fail";}
// Close connection
mysql_close($db);
?>

query failed when upload pdf file to mysql via php

I am trying to do a upload button which able to upload a pdf file to database but it faced some problems. database i used mySQL.
pop out window for user to key in document
<form method="POST" action="upload.php" enctype="multipart/form-data">
<div>
<label for="citation">Citation</label>
<textarea name="citation" id="citation" placeholder="Enter text here..."></textarea>
</div>
<div>
<label for="abstract">Abstract</label>
<textarea name="abstract" id="abstract" placeholder="Enter text here..."></textarea>
</div>
<p>Upload your file here</p>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
<br/>
<input name="submit" type="submit" value="Upload" style="width: 150px">
<a class="close" href="#close"></a>
</form>
this is upload.php
<?php
// Connect to the database
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="is"; // Database name
$tbl_name="publication"; // Table name
$conn = mysql_connect("$host", "$username", "$password");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name);
$cit=mysql_real_escape_string($_POST['citation']);
$abs=mysql_real_escape_string($_POST['abstract']);
if(isset($_POST['submit']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO publication ('citation','abstract','file_name', 'file_size', 'file_type', 'file_content' ) VALUES ('$cit','$abs','$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
echo "<script type='text/javascript'>alert('File $fileName uploaded!');
window.location.href='home_unlogin.php';
</script>";
}
mysql_close($conn);
?>
at the next it show error, query failed and i have no idea whats wrong with it.
$query = "INSERT INTO publication (`citation`,`abstract`,`file_name`, `file_size`, `file_type`, `file_content`) VALUES ('$cit','$abs','$fileName', '$fileSize', '$fileType', '$content')";
or you can use without wrapping field names
$query = "INSERT INTO publication (citation, abstract, file_name, file_size, file_type, file_content) VALUES ('$cit','$abs','$fileName', '$fileSize', '$fileType', '$content')";
Because your field names are standard names which are not reserved word or contains special chars.
For the fields in SQL you can leave it without quotations but for the values it should be inside a quotations whether it is variable or static.
$select = "INSERT INTO tbl_table (tbl_field1,tbl_field2) VALUES ('$value1','Test')";

Uploading an image to the database

This is the code for the upload form to enable me to upload an image to the database
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="file_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This is the code that I have in a in a file called file_uploader.php. When trying to complete this I get the error Could not copy file!
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "databasehostdetails" ) or
die( "Could not copy file!");
}
else
{
die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body>
</html>
You need to use tmp_name. Also, what is databasehostdetails? The second parameter is the destination (where you want to copy the file to).
copy($_FILES['file']['tmp_name'], DESTINATION_PATH);
Here is a simple way to do this. I am giving you my script
index.html
But be carefull:
It is not recommended since it is to costly for your database to store files
Fix any sql injection vurnelabilities. I my self don't know how to do this. You can make a research and fix it.
Also check out here Storing Images in DB - Yea or Nay?
However the code works pretty good if it not a large scale application and no sql injection attacks could happen.
<html>
<body>
<form method="post" enctype="multipart/form-data" action="doupload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
<input name="upload" type="submit" id="upload" value=" Upload ">
</form>
</body>
</html>
doupload.php
<?php
include("config.php");
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload set name='".$fileName."', size='".$fileSize."', type='".$fileType."', content='".$content."'";
mysql_query($query) ;
?>
getuploaded.php
<?php
// select records from database if exists to display
include("config.php");
$query1 = "SELECT id, name FROM upload";
$result1 = mysql_query($query1) or die('Error, query failed');
if(mysql_num_rows($result1)>0)
{
while(list($id, $name) = mysql_fetch_array($result1))
{
?>
<?php echo $name;?> <br>
<?php
}
}
?>
download.php
<?php
//header("Content-type: $type");
include("config.php");
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
?>
config.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'uploadfile';
mysql_select_db($dbname);
?>
Createing the table
CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);

PHP upload to MySQL database with download and view file

Does not download correctly: can't open the link. Help appreciated. I am new to PHP and MySQL. I have MySQL set to BLOB for the content and I am not sure how to be clearer, I can see the link(s) for the file with the respective id to the file content $id in the url, but when I click on the link nothing opens up, I want to be able to open the file inthe brownser. I intend on being able to open .zip files and extract in later development. A sfar as security please also explain in good details so I can learn. I see my code was mod, but still not working in the array link.
UPLOAD.PHP:
<?php
$dbname="upload";
$host="localhost";
$user="SELF";
$pass="PICME";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileType = $_FILES['userfile']['type'];
$fileSize = $_FILES['userfile']['size'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (name, type, size, content) ".
"VALUES ('$fileName', '$fileType', '$fileSize', '$content')";
mysql_query($query) or die('Error, query failed');
echo "<br>File $fileName uploaded<br>";
}
?>'
(DOWNLOAD.PHP)FILE
'<?php
$dbname="upload";
$host="localhost";
$user="SELF";
$pass="PICME";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
$query = "SELECT id, name FROM upload";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "Database is empty <br>";
}
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
?>
<?php echo urlencode($name);?> <br>
<?php
}
}
exit;
?>
<?php
$dbname="upload";
$host="localhost";
$user="SELF";
$pass="PICME";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
$query = "SELECT id, name FROM upload";
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
$content = $row['content'];
header("Content-Disposition: attachment; filename=$name");
header('Content-type: image/jpeg' . $type); // 'image/jpeg' for JPEG images
header('Content-Length:' . $size);
exit;
print $content;
ob_clean();
flush();
echo $content;
}
?>
It seems you are not validating the Mime type of the file while uploading and setting Mimetype for JPEG while downloading.
Please make sure you are uploading the correct file format.
Also, the id is urlencoded but not decoded while retrieving from DB.

Categories