query failed when upload pdf file to mysql via php - 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')";

Related

Uploading data and files to MySQL database through a single PHP form

I am having some input types in a HTML form and a file uploader. But I am unable to upload both data and file at the same time in the MySQL database. Every time blank entries are filled up into the database...
HTML Form
<form method="post" action="upload.php" enctype="multipart/form-data">
<p>
<label>Name:</label>
<input type="text" name="name" size="40">
</p>
<p>
<label>Email:</label>
<input type="email" name="email">
</p>
<p>
<input type="radio" name="gen" value="Male">Male
<input type="radio" name="gen" value="Female">Female</p>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<br>File to upload:
<br>
<input type="file" name="File" size="40">
<p>
<input type="submit" name="submit" value="submit">
</form>
PHP Code
if(isset($_POST['name']) && isset($_POST['email']) &&
isset($_POST['gen']) && $_FILES['File']['size'] > 0) {
$name=get_POST('name');
$email=get_POST('email');
$gender=get_POST('gen');
$filename = $_FILES['File']['name'];
$tmpname = $_FILES['File']['tmp_name'];
$filesize = $_FILES['File']['size'];
$filetype = $_FILES['File']['type'];
$fp = fopen($tmpname, 'r');
$file = fread($fp, filesize($tmpname));
$file = addslashes($file);
fclose($fp);
if(!get_magic_quotes_gpc()) {
$filename = addslashes($filename);
}
$query = "
INSERT INTO uploadform
(Name, Email, Gender, Filename, Filetype, Filesize, File) VALUES
('$name', '$email', '$gender', '$filename', '$filetype', '$filesize', '$file');";
mysql_query($query) or die('Error, query failed');
}
In the database the datatype of the file is MEDIUMBLOB
Ok I found the Answers...! Just check with the variables...I have used other database and example (common sense)...
<?php
//This is the directory where images will be saved
$target = "images/";
if(!is_dir($target)) mkdir($target);
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['username'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$fname=($_FILES['photo']['name']);
$tmpName = $_FILES['photo']['tmp_name'];
$fileSize = $_FILES['photo']['size'];
$fileType = $_FILES['photo']['type'];
//process the file
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc()){
$fname = addslashes($fname);}
// Connects to your Database
require_once 'login.php';
$db_server=mysql_connect($db_hostname,$db_username,$db_password);
if(!$db_server) die("Unable to connect to MySQL" .mysql_error());
mysql_select_db($db_database,$db_server)
or die("Unable to connect to database" .mysql_error());
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$fname','$fileType','$fileSize','$content')") ;
//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.";
}
?>
<form enctype="multipart/form-data" action="up.php" method="POST">
Name: <input type="text" name="username"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Add">
</form>

strip slashes error in file upload

i get the below error msg for the code given below
"Warning: stripslashes() expects parameter 1 to be string, array given in /home/stthohuu/public_html/forms/upload_newsletter.php on line 32"
can you please guide me.. am not aware of file upload processes.. please share your suggestions
<html>
<head></head>
<body>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1"
cellspacing="1" class="box">
<tr>
<td><h4>Please select a file</h4></td></tr>
<tr>
<td>
<input type="hidden" name="MAX_FILE_SIZE"
value="16000000">
<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>
Back
</body>
</html>
<?php
if(isset($_POST['upload'])&&$_FILES['userfile']['size']>0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fileType=(get_magic_quotes_gpc()==0 ? mysql_real_escape_string(
$_FILES['userfile']['type']) : mysql_real_escape_string(
stripslashes ($_FILES['userfile'])));
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$con = mysql_connect('localhost', 'stthohuu_batch', 'abc') or die(mysql_error());
$db = mysql_select_db('stthohuu_church', $con);
/* identify the max id in existing data*/
$max_id[0]='';
$sql="SELECT id FROM newsletter WHERE id=(SELECT max(id) FROM newsletter)";
$result = mysql_query($sql);
$max_id = mysql_fetch_array($result);
if ($max_id[0]=='')
{
$max_id[0]=0;
}
$id=0;
$id=$max_id[0]+1;
/* to insert data into newsletter table */
if($db){
$query = "INSERT INTO newsletter (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
mysql_close();
echo "<br>File $fileName uploaded<br>";
}else { echo "file upload failed"; }
}
?>
This s workin well in local xampp.. But NOT in web server.. :(
you are passing $_FILES['userfile'] array to stripslashes, pass $_FILES['userfile']['name'] or $_FILES['userfile']['tmp_name']
Replace
stripslashes ($_FILES['userfile'])));
to
stripslashes ($_FILES['userfile']['name'])));
stripslashes is string function and you are trying to pass file in it.

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.

To upload a image in MySql database via 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';
?>

Using PHP to upload an image and store data in MSSQL

I'm attempting to upload an image as well as add details such as; title, description and filepath into a database table.
I'm using the following code, but it isn't adding any data to the database;
(The session.php include contains the database connectivity.)
<?php include('includes/session.php');
$uploadDir = 'submitted/pictures/';
if(isset($_POST['submit']))
{
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading <strong>file</strong>";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$title = $_POST['title'];
$description = $_POST['description'];
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
mssql_query($query);
}
?>
The form code;
<form name="Image" enctype="multipart/form-data" action="upload-pics2.php" method="POST">
Title <input type="text" name="title" maxlength="100" class="textbox" value="<?php echo $form->value("title"); ?>" />
Description <textarea name="description" rows="8" cols="40" class="textbox" value="<?php echo $form->value("description"); ?>"></textarea>
File <input type="file" name="file" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" class="textbox" />
<input type="submit" name="submit" value="Upload" class="button" />
</form>
I was wondering if someone could tell me what might be going wrong?
Thank you.
This code do not work because of several problems.
First, you should rename one of html fields or change field name when you are checking for upload:
<input type="submit" name="Upload" value="Upload" class="button" />
or
if(isset($_POST['submit']))
Second one, this script will not store any data into DB.
You should get, sanitize and write data into according fields, for example:
$title = mysql_real_escape_string($_POST['title']);
$description = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
You should make sure these fields present in DB, if not - you should create them:
ALTER table user_pictures ADD column description text, add column title varchar(255);
You has an error at this line if(isset($_POST['Upload']))
Change this to the if(isset($_POST['submit']))
is the 'submitted/pictures/' writable? also you might want to run is_uploaded_file() for an extra layer of security.
Also your query seems to be wrong
"INSERT INTO $user_pictures ( file ) VALUES ('$filePath')"
$user_pictures needs to be a table
try
"INSERT INTO `user_pictures` ( `file` ) VALUES ('$filePath')"

Categories