I have searched a lot on about this but I did not find solution.
I have images in a directory in server. And I want to upload those images ( Not Just image Paths) to MySQL database using longblob with PHP.
I know that storing images in the database is not recommended but that is the requirement of my project so I want use this method.
Please suggest me, How can I do that?
Thanks to all.
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("your databse name");
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
$name=$_POST['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 image2 ";
$query .= "(image,name) VALUES ('$data','$name')";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($con);
?>
Related
I am trying to upload a image to MySQL databases using php5 script. And I am receiving an notice error.
Error, query failed
UploadImage.php
<?php
session_start();
?>
<HTML>
<HEAD>
<TITLE> Image Upload</TITLE>
</HEAD>
<BODY>
<FORM NAME="f1" METHOD="POST" ACTION="uploadImage2.php" ENCTYPE="multipart/form-data">
<table>
<tr><td> Image Upload Page </td></tr>
<tr><td> <input type="file" name="imgfile"/></td></tr>
<tr><td> <input type="submit" name="submit" value="Save"/> </td></tr>
</table>
</FORM>
</BODY>
</HTML>
UploadImage2.php
<?php
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['submit']) && $_FILES['imgfile']['size'] > 0)
{
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
mysql_query($query) or die('Error, query failed'.mysql_errno($dbconn) . ": " . mysql_error($dbconn) . "\n");
$imgid = mysql_insert_id(); // autoincrement id of the uploaded entry
//mysql_close($dbconn);
echo "<br>Image successfully uploaded to database<br>";
echo "View Image";
}else die("You have not selected any image");
?>
I have upload an image file but still have error on it.
But now I have counter another error for view Image.
<?php
// get the file with the id from database
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['id']))
{
$id = $_REQUEST ['id'];
$query = "SELECT img_name, img_type, img_size, img_data FROM img_tbl WHERE id = ‘$id’";
$result = mysql_query($query) or die(mysql_error());
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
print $content;
mysql_close($dbconn);
}
?>
The error code:
Notice: Undefined variable: id� in C:\xampp\htdocs\sandbox\Testing\uploadImage2_viewimage.php on line 12
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '�' at line 1
Please advise...
Remove the ' ' from table fields in query .use this query :
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
also please start to use PDO or mysqli as your query is open for sql injection
This should work:
$query = "
INSERT INTO `img_tbl`
(`img_name`, `img_type`, `img_size`, `img_data` )
VALUES
('".$fileName."', '".$fileType."', '".$fileSize."', '".$imgContent."')
";
Seems that some special characters in $imgContent is breaking the query string
Please use mysql_real_escape_string to format your data before sending to the database
mysql_real_escape_string
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
UPDATE
If the first solution didn't fix the problem , please check are there any NULL values , you have some database columns which set to NOT NULL . so you cannot insert NULL values to them .
Hope this helps :)
I've create a table where I've saved images through "LongBLOB". I need to show those images.
i can save images in my sql but when i want to read and display them i have a problem,
"can not be displayed because it contains errores"
im usi8ng this code to save the image to my sql table
<?php
$username = "root";
$password = "";
$host = "localhost";
$database = "imgtest";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database);
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$namee = $_FILES['image']['name'];
mysql_query("INSERT INTO image(cap,image) VALUES ('$namee','$data')");
}
?>
and im using this code to read and display the image from my sql table
<?php
$con=mysqli_connect("localhost","root","","imgtest");
$wich=$_POST['wich'];
$resoult=mysqli_query($con,"SELECT * FROM image WHERE id LIKE '$wich'");
$imgd = $_GET['img'];
$row = mysqli_fetch_array($resoult);
$image = $row['image'];
header("content-type:image/jpeg");
echo $image;
?>
anyone can help me with this??
It is strongly advised to store images within your file structure (a directory on your server, cloud server, or other accessible location) and only keep a reference such as a url, file name or path path in the database in order to recreate a link or path to the actual image. It is a bad practice to keep images in a database.
Why are you using mysql_ library - it is deprecated.
You need to store binary data. Use prepared statements. In that way you get back binary data.
From 2 you can dump addslashes. That is the root of the problem
I am trying to replace one pdf that previously upload in MySQL to another pdf . I created an a href [edit] for user to choose the pdf file and link to editDB.php where query update placed.
This is edit.DB.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
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);
}
$conn = mysql_connect("$host", "$username", "$password");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
Connect database, fetch file_id, fetch other data that updated
$conn = mysql_connect("$host", "$username", "$password");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if (isset($_GET["id"]))
{
$id =$_GET["id"];
}
else
{
echo'failed';
}
mysql_select_db($db_name);
$title=mysql_real_escape_string($_POST['title']);
$author=mysql_real_escape_string($_POST['author']);
$year=mysql_real_escape_string($_POST['year']);
$abs=mysql_real_escape_string($_POST['abstract']);
query here
$query="update publication set title='".$title."', author='".$author."', year='".$year."' , abstract='".$abs."', file_name='".$fileName."', file_size='".$fileSize."', file_type='".$fileType."', content='".$content."' where file_id='$id'";
mysql_query($query) or die(mysql_error());
echo '<script type="text/javascript">alert("'.$title.' updated!");
window.location.href="publication.php";
</script>';
mysql_close($conn);
}
?>
The problem I faced is that , after I key in updated info in my edit form. The data successfully direct to editDB.php. pop up dialog showing data updated is shown but the data did not updated both database and the page showing info. I will be grateful for any help hands. Thanks.
Instead of
if (isset($_GET["id"]))
{
$id =$_GET["id"];
}
else
{
echo'failed';
}
i change it to
if(isset($_POST['submit'])&& $_FILES['userfile']['size'] > 0)
{
$id =$_POST["id"];
Of course the id must pass properly and make sure id is match with ur database.
This code can works. Hope able to help you all.
Right now I am inserting blob files into a database. I have read up on the update syntax for mysql I can not figure out how to modify my code to update a row with the BLOB instead of inserting a new row with the BLOB. Could someone help me with this?
Here is my code:
<?php
// Create MySQL login values and
// set them to your login information.
$username = "root";
$password = "";
$host = "localhost";
$database = "test";
$tbl_name="members";
// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db ($database);
// Make sure the user actually
// selected and uploaded a file
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 members ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($link);
?>
1° You need to pass a referecence for what Data you are trying to update, like the Primary Key Id From Table.
2° Update SQL should be like it
$image = mysql_real_escape_string($unsafe_image);
$id = mysql_real_escape_string($unsafe_id);
$query = "UPDATE members SET image = '$data' WHERE id_image = $id";
$results = mysql_query($query, $link);
I have a form that uploads a file with other information to a database and displays it in a chart. Right now the chart only displays the file name and doesen't link it. If the file was called test1.pdf, how would I make it so on the chart it still says chart1.pdf but links it to the directory that the file is on?
if ('POST' === $_SERVER['REQUEST_METHOD'])
{
$con = mysql_connect("localhost","xxxx","xxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jjlliinn_test", $con);
$target = "clientdoc/";
$target = $target . basename( $_FILES['file']['name']);
$date = $_POST['date'];
$propertydescription = $_POST['propertydescription'];
$transactiontype = $_POST['transactiontype'];
$applicabledocument = ($_FILES['file']['name']);
$received = $_POST['received'];
$paid = $_POST['paid'];
//Writes the to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
//Tells you if its all ok
echo "";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
$sql = mysql_query("INSERT INTO `transactions` (`date`, `agentclient`, `propertydescription`, `transactiontype`, `applicabledocument`, `received`, `paid`)
VALUES
('$date', '$agentclient', '$propertydescription', '$transactiontype', '$applicabledocument', '$received', '$paid')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"48\">";
mysql_close($con);
}
}
?>
Assuming all your uploads are stored in the client doc folder and you have run the query to get the recordset from the transactions table...
link text
Another point, looking at the code, sending raw $_POST values direct to the db is asking for sql injection trouble. Have a look at either htmlentities with ENT_QUOTES set or the input filters available with php.