Failed to replace PDF in database with another PDF using PHP - php

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.

Related

Cannot upload image into mysql database use php

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 :)

Modifying Insert data into table so that it is now Update Table

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);

PHP: Upload images from folder to MySQL Database

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);
?>

Unable to show Images stored in mySQL using PHP

I am trying to store images in mySQL database and then displaying on the other page. I have this function to store images in mySQL.
function upload() {
include "databaseConnection.php";
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK) {
//check whether file is uploaded with HTTP POST
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
//checks size of uploaded image on server side
if ($_FILES['userfile']['size'] < $maxsize) {
// prepare the image for insertion
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE(mysql_error());
// select the db
mysql_select_db($db) OR DIE("Unable to select db" . mysql_error());
// our sql query
$sql = "INSERT INTO carsinfo
(carName, carPicture)
VALUES
('{$_FILES['userfile']['name']}', '{$imgData}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg = '<p>Image successfully saved in database with id =' . mysql_insert_id() . ' </p>';
} else {
// if the file is not less than the maximum allowed, print an error
$msg = '<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is ' . $maxsize . ' bytes</div>
<div>File ' . $_FILES['userfile']['name'] . ' is ' . $_FILES['userfile']['size'] .
' bytes</div><hr />';
}
}
else
$msg = "File not uploaded successfully.";
}
else {
$msg = file_upload_error_message($_FILES['userfile']['error']);
}
return $msg;
}
And this code to show iamges.
<?php
include "databaseConnection.php";
// just so we know it is broken
error_reporting(E_ALL);
// some basic sanity checks
//connect to the db
$link = mysql_connect("$host", "$user", "$pass") or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("$db") or die(mysql_error());
// get the image from the db
$sql = "SELECT carPicture FROM carsinfo;";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($result);
// set the header for the image
echo $row['carPicture'];
header("Content-type: image/jpeg");
// close the db link
mysql_close($link);
?>
When this code is run, nothing is shown on the page, even if I write some HTML inside this code, empty page is shown.
I assume you are saving the image content as blob and if your sql is returning the correct data then you can display as
header("Content-type: image/jpeg");
echo $row['carPicture'];
You need to add the header first before the image.
or
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['carPicture']) . '">';
do not write
include databaseConnection.php
nothing include anything.

Import csv from Yahoo Finance into MySQL using PHP

Using Johnboy's tutorial on importing .csv files to MySQL, I tried to make a script that would take exchange rate data from Yahoo finance, and write it to the MySQL database.
<?php
//connect to the database
$host = "****"
$user = "****"
$password = "****"
$database = "****"
$connect = mysql_connect($host,$user,$password);
mysql_select_db($database,$connect);
//select the table
if ($_FILES[csv][size] > 0) {
//get the csv file
$symbol = "ZARINR"
$tag = "l1"
$file = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=$tag&s='$symbol'=x";
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO ZAR_to_INR(exchange_rate) VALUES
(
'".addslashes($data[0])."',
)
");
echo "done";
}
} while ($data = fgetcsv($handle,1000,",","'"));
//redirect
header('Location: import.php?success=1'); die;
}
else{
echo "nope";
}
?>
I added the echos in the hope that they'd tell me whether or not the script worked. It doesn't work at all. There are no error messages or anything. When I run the script by opening it in my webhost, it simply does not run.
I'd appreciate any advice on how to make this script work (or even an alternate way of solving the problem).
try using mysql debugs :
mysql_select_db($database) or die('Cant connect to database');
$result = mysql_query($query) or die('query fail : ' . mysql_error());
$connect = mysql_connect($host,$user,$password)
or die('Cant connect to server: ' . mysql_error());
to find this outputs you need to check your php error_log : where-does-php-store-the-error-log

Categories