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 :)
Related
I've to import a CSV file in a table of a MySql database using PHP code. The CSV file is the following:
"2016-09-02", "100.01", "4005.09", "5000", "1.09", "120.09", "100.5", "200.77"
"2016-09-03", "150.01", "4205.09", "5600", "1.10", "150.09", "300.5", "300.77"
File permissions are 755.
Table fields are 9 (id field included): the firts is a datetime field and other are float fields.
The code I use is the following and it will run on the server site:
$csvFile = "../scripts/tabella.csv";
$db = #mysql_connect('**.***.**.***', 'Sql******', '*******');
#mysql_select_db('Sql******_*');
$query = 'LOAD DATA LOCAL INFILE \' '. $csvFile .' \' INTO TABLE mytable FIELDS TERMINATED BY \',\' ENCLOSED BY \'"\' LINES TERMINATED BY \'\n\' ';
if(!mysql_query($query)){
die(mysql_error());
}
mysql_close($db);
First error is returned from mysql_error: 'file not found'. The CSV file is in 'www.mysite.it/mysite/scripts/tabella.CSV'. Its permissions are 755. I tried to use realpath($csvFile) function but the error is always the same.
I tried to run the same query in localhost and there isn't this error but only a record is inserted into the table and its fild values are NULL.
Can you help me, please?
Thanks!
Use mysql_error to get the error
if(!mysql_query($query)){
die(mysql_error());
}
Try below code..
$csvFile = "../scripts/tabella.csv";
//The Connection
$mysqli = new mysqli($host,$username,$password,$database);
//Check for successful connection
if ($mysqli->connect_errno) echo "Error - Failed to connect to MySQL: " . $mysqli->connect_error; die;
$query = 'LOAD DATA LOCAL INFILE \' '. $csvFile .' \' INTO TABLE mytable FIELDS TERMINATED BY \',\' ENCLOSED BY \'"\' LINES TERMINATED BY \'\n\' ';
//Do your query
$result = mysqli_query($mysqli,$query);
//Close the connection
mysqli_close($mysqli);
Try This coding It's work
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["submit"]))
{
if($_FILES['file']['name'])
{
$filename = explode(".", $_FILES['file']['name']);
if($filename[1] == 'csv')
{
$handle = fopen($_FILES['file']['tmp_name'], "r");
while($data = fgetcsv($handle))
{
$item1 = mysqli_real_escape_string($connect, $data[0]);
$item2 = mysqli_real_escape_string($connect, $data[1]);
$query = "INSERT into excel(excel_name, excel_phone) values('$item1','$item2')";
mysqli_query($connect, $query);
}
fclose($handle);
echo "<script>alert('Import done');</script>";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<form method="post" enctype="multipart/form-data">
<div align="center">
<label>Select CSV File:</label>
<input type="file" name="file" />
<br />
<input type="submit" name="submit" value="Import" class="btn btn-info" />
</div>
</form>
</body>
</html>
try this simple way to import your CSV data to Mysql database.The file is a HTML element name to browse your file path.
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name= $filesop[0];
$sql = mysql_query("INSERT INTO tab(name) VALUES ('$name')");
$c = $c + 1;
}
if($sql){
echo "You database has imported successfully. You have inserted ". $c ." recoreds";
}else{
echo "Sorry! There is some problem.";
}
}
I am trying to display an image uploaded to my "upload" table in MySql. I've been reading a lot on how to do this but no luck.
"news_content" table is for uploading NEWS content to Mysql and has 6 columns: id,title, description, content_text, date, time
and "upload" table has 5 columns: id, name, size, image, date
In "news_content" table I upload the date and the time columns separately but the date column in "upload" table is a string concatenated with both date and time. For example if in "news_content" table the date is 2/3/2016 and the time is 5:30, in "upload" table the date is going to be 2/3/20165:30. I organized it that way in order to retrieve the image by its specific date and time that the related post uploaded.
I upload the image in news.php page with this following code:
news.php :
// Create connection
$connection = mysql_connect("localhost","root","p206405az");
// Check connection
if (!$connection) {
die("Connection failed: " . mysql_error());
}
//select a database to use
$db_select = mysql_select_db( "news" , $connection) ;
if (!$db_select) { die("Selection faild:" . mysql_error()) ;
}
//uploading the content of news and date and time
if(isset($_POST["submit"])){
$title = $_POST["title"] ;
$description = $_POST["description"] ;
$content_text = $_POST["content_text"] ;
$date = $_POST["date"] ;
$time = $_POST["time"] ;
//perform mysql query
$result = mysql_query("INSERT INTO news_content (title, description, content_text, date, time)
VALUES ('$title', '$description', '$content_text' ,'$date' , '$time' )") ;
if (!$result) {
die("Insert failed: " . mysql_error());
$submitMessage = "Problem with updating the post, please try again" ;
} else if ($result){
$submitMessage = "Your post succsessfully updated" ;
}
}
// uploading the image
if(isset($_POST['submit']) && $_FILES['image']['size'] > 0)
{
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
$filedate = "$date" . "$time" ;
$fp = fopen($tmpName, 'r');
$content2 = fread($fp, filesize($tmpName));
$content3 = addslashes($content2);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (name, size, type, image, date ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content3', '$filedate')";
mysql_query($query) or die('Error2, query failed');
}
And I want to retrieve that image by getImage.php page to use it as source page later by this following code but it seems it can't retrieve the blob data:
P.S. The image is successfully uploaded but I can't retrieve it with specific date that I Posted lately
getImage.php :
// Create connection
$connection = mysql_connect("localhost","root","p206405az");
// Check connection
if (!$connection) {
die("Connection failed: " . mysql_error());
}
//select a database to use
$db_select = mysql_select_db( "news" , $connection) ;
if (!$db_select) { die("Selection faild:" . mysql_error()) ;
}
//perform mysql query
$result = mysql_query("SELECT * FROM news_content" , $connection);
if (!$result) {
die("read failed: " . mysql_error());
}
//useing returned data
while ($content = mysql_fetch_array($result)){
$date = $content["date"];
$time = $content["time"] ;
}
$filedate = "$date" . "$time" ;
$result2 = mysql_query("SELECT image FROM upload WHERE date='$filedate'" , $connection);
if (!$result2) {
die("read failed: " . mysql_error());
};
$row = mysql_fetch_assoc($result2);
mysql_close($connection);
header("Content-type: image/jpeg");
echo $row['image'];
And I want to display the image in index.php page with this following HTML code:
index.php :
<img src="getImage.php?date=<?php echo $filedate ; ?>" width="175" height="200" />
How can I retrieve that data in getImage.php page and then use that page az source page to display the image in index.php page?
Any help would be appreciated.
cant figure out the error unless php throws an error. but i would save the images as files instead of db and keep its name if news table's row, unless there are multiple images per news.
in case of multimple image per news, i would just match the image id to news id.
schema for news.db
id, title, description, content_text, date, time
schema for upload.db:
id, image, newsid
my image html link would have been:
<img src="getImage.php?id=<?php echo $newsid; ?>" width="175" height="200" />
and then my getimage.php would have been like this:
$connection = mysql_connect("localhost","root","p206405az");
if (!$connection) {
die("Connection failed: " . mysql_error());
}
$db_select = mysql_select_db( "images" , $connection) ;
if (!$db_select) {
die("Selection faild:" . mysql_error()) ;
}
$id=$_GET["id"];
$result = mysql_query("SELECT image FROM upload WHERE newsid='$id' LIMIT 1" , $connection);
if (!$result) {
die("read failed: " . mysql_error());
};
$row = mysql_fetch_assoc($result);
mysql_close($connection);
header("Content-type: image/jpeg");
print $row['image'];
To show errors:
add error_reporting(E_ALL); ini_set('display_errors', '1'); at top of your page;
temporarily comment the header line: header("Content-type: image/jpeg");;
retrieve image directly from browser address bar (see image below);
If you obtain a “500 Server Error” check your Apache error log (compile errors are not displayed even with error_reporting enabled);
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 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);
?>
I am building a simple website, I want to allow the users to upload and change their avatars. At present I have been able to upload images to a mysql database, stored as blobs with the code as follows:
//connected to DB, userID fetched
$image = $FILES['fileToUpload']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql = "UPDATE tbUsers SET profileImage = '".$content."' WHERE userID = ".userID;
$result = mysql_query($sql) or die (mysql_error());
When I download the files from phpmyadmin after upload they are saved as .bin files, but can be viewed normally. I'm not sure if this is correct or not.
My code to display the images is as follows:
HTML:
<?php echo '<img src ="showPic.php?q='.$_SESSION['profile'].'"/>'; ?>
PHP:
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
header('Content-type: image/jpeg');
$row = mysql_fetch_object($result);
echo $row['image_data'];
}
I am unsure if I am attempting to display the image in the correct way, any help (corrections/alternative solutions) would be greatly appreciated :)
You can do this :
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
$content = mysql_result($result,0,"file_content");
$name = mysql_result($result,0,"file_name");
$type = mysql_result($result,0,"file_type");
$size = mysql_result($result,0,"file_size");
header("Content-type: $type");
echo $content
}
Note : You should have these column in you table where you save your BLOB data
file_name = for save filename
$_FILES['file']['name']
file_type = for save file type
$_FILES['file']['type']
file_size = for save file size
$_FILES['file']['size']
You select this
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
and refer to not selected column
echo $row['image_data'];