file not updating in sql in php - php

I am working in php I want browse and upload the image file
this is my php code
<?php
if(isset($_POST['submit']))
{
$link= mysql_connect('localhost','root','');
mysql_select_db('bawa');
if(isset($_FILES['image']) && $_FILES['image']['size'] >0)
{
//Temporary file name stored on the server
$tmpname = $_FILES['image']['tmp_name'];
//read a file
$fp = fopen($tmpname,'r');
$data=fread($fp,filesize($tmpname));
$data=addslashes($data);
fclose($fp);
$query = ("UPDATE user_summary SET image='$data' where user_id=2");
$query .= "(image) VALUES ('$data)";
$results = mysql_query($query,$link);
echo "Working code";
}
else{
echo mysql_error();
}
}
?>
when i click on submit button my image should updated in my database but its not updating in database
any help?

The main problem at the moment is the line...
$query .= "(image) VALUES ('$data)";
This looks more like something that would be part of an INSERT statement. Commenting this out should mean the UPDATE should be correct.
Although as pointed out - you should work towards updating this to use either PDO or mysqli libraries and using prepared statements and bind variables.

Related

error to upload to images with php

I am trying to upload two images with php. And add them to the database. Somehow it only uploads one image and the records in the database always have the same values.
this is the code i use
<?php
include "../connect.php";
$name1 = $_FILES['pic1']['name'];
$size1 = $_FILES['pic1']['size'];
$name2 = $_FILES['pic2']['name'];
$size3 = $_FILES['pic2']['size'];
if(isset($_POST['name']))
{
$extension1 = pathinfo($name1,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension1,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image1 = time().'.'.$extension1;
$file1 = "images/upload";
$pic1 = "$file1/".$new_image1;
move_uploaded_file($_FILES["pic1"]["tmp_name"],"../".$pic1."");
$insert = mysql_query("update temp set pic='$pic1' ") or die("error ins");
}
$extension2 = pathinfo($name2,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension2,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image2 = time().'.'.$extension2;
$file2 = "images/upload";
$pic2 = "$file2/".$new_image2;
move_uploaded_file($_FILES["pic2"]["tmp_name"],"../".$pic2."");
$insert = mysql_query("update temp set passport='$pic2'") or die("error ins");
}
}
?>
One of the problems you have is with your update statement. There is no 'where' statement saying which record in the database should be updated so this query updates them all. That's why you only have the last image in all the database rows.
Besides that, your code is not very good from a security point of view. You should take a look at mysqli or pdo for your database connection and queries because MySQL is deprecated and removed from PHP. Also take a look at SQL injections and data validation. Besides some very basic extension and size validation there is nothing there to keep things save. Try escaping and validating all user inputs.
And another point would be to take a look at 'functions'. You're running almost the exact same piece of code at least twice. And every code change has to be done twice. Perfect for a function call, something like
function storeImage($image){
// write the uploading and storing PHP here
}

Insert image path and data in MySQL database

I have two pages: displayhotels.php and addrooms.php. When I click on the add rooms link which is on the displayhotels.php page, it fetches the hotel name and displays it on the addrooms.php page. Now, I need to insert the hotel name and other variables in a table. For some reason, the image path and data are not storing in the db. However, the image is updating in the folder.
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}else{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']
['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]
["tmp_name"],"rooms/" . $_FILES["image"]["name"]);
if(isset($_POST['submit']))
{
$image="rooms/" . $_FILES["image"]["name"];
$rnum = $_POST['rnum'];
$rtype = $_POST['rtype'];
$people = $_POST['people'];
$cond = $_POST['cond'];
$price = $_POST['price'];
$rooms = $_POST['rooms'];
$sql = "INSERT INTO `room`(`hotel_name`, `roomNum`,`roomType`,
`noOfPeople`, `conditions`, `price`, `rooms`, `image`) VALUES
('$name','$rnum', '$rtype', '$people', '$cond', '$price', '$rooms',
'$image')";
You are first making correct $image variable:
$image="rooms/" . $_FILES["image"]["name"];
But then you overwrite it with a wrong one:
$image = $_POST['image'];
So you need to remove this line and you'll do fine i guess.
Few debugging tips:
First of all add error_reporting() in your code.
Than check are you getting values from HTML form by using:
print_r($_POST);
Also check are you using proper name attributes in input field?
Error in your code:
In your query you didn't defined the variable:
$name
You missed hotel_name in your query.
Try debugging with a logger and using tail -f [log file name] from the terminal if using LAMP to step through the code. Are you sure $_POST['submit'] is set? How are you connecting to the db? This isn't shown in the code. Maybe the file I/O is working fine (the image updates in the folder) but you're not connecting to the db and the problem isn't the sql statement itself but the actual connection.
Also, look into using prepared statements to make your code more secure, and not directly accessing $_POST variables. See http://php.net/manual/it/mysqli.quickstart.prepared-statements.php and http://php.net/manual/en/function.filter-input.php for more information.

Using PHP how can i display images which have been saved in SQL as a image path

I am trying to retrieve images from my SQL database which have been saved using the image path. The images are saved on the server. When i retrieve the images , nothing is returned.
if(isset($_GET))
{
include_once "mysql_connect.php";
$text = $_GET['text'];
if($text=="")
{
$query = mysql_query("SELECT `URL` FROM `gallery` WHERE `img_text` LIKE '1'")
or die(mysql_error());
while( $rows=mysql_fetch_array($query) )
{
$search[] = $rows[0];
}
$result = array();
$result["result"] = 500;
$result["message"] = "Database Read Successfully";
$result["rows"] = $search;
echo json_encode($result);
exit;
The example of code is for a search without the user entering a value. Within the SQL statement 'URL' is the field where the image paths are stored.The images paths values are the complete URL http://example.com/images/test.jpg and stored as a VARCHAR(200) . Any advice would be appreciated
Your code should not work well. You are not closing the if statement.
Also, when $text is not empty you don't have any query to the database...
You would need something like:
if($text==""){
$query = mysql_query("SELECT `URL` FROM `gallery` WHERE `img_text` LIKE '1'")
or die(mysql_error());
}
//when $text is not empty...
else{
$query = mysql_query("SELECT `URL` FROM `gallery` WHERE `img_text` LIKE '".$text."'")
or die(mysql_error());
}
while( $rows=mysql_fetch_array($query)){
$search[] = $rows[0];
}
By the way, try to use PDO instead of mysql_query, this last one is obsolete and is vulnerable to SQL injections.
The images are in the server, so the path only works there.
If you do a:
echo json_encode($result);
I guess you are returning this info to the client, the images path have no value there if you want to display them!
If you want to show the user the image you need to use a HTML img tag and fill the src attribute with the path FROM THE SERVER.

Error while displaying images from mysql php using blob datatype

I am trying to display images from my mysql database using php. The image is not getting displayed fully. It gets cut while trying to display an image more than 200 kb (determined from trials , but not too sure).
HTML Code:
<form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="10240000" type="hidden">
<input name="image" accept="image/jpeg|image/jpg|image|JPG|image/png|image/gif" type="file">
<input value="Submit" type="submit">
PHP Code:
<?php
require('myconnect.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);
// Create the query and insert
// into our database.
$query = "Update whyangry.posts set Photo='$data' where Pid=2";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
$sql = "SELECT * FROM helpme.posts WHERE Pid=2";
$res = mysql_query($sql,$con);
while ($res1=mysql_fetch_assoc($res))
{
$content = $res1['Photo'];
$id=$res1['Pid'];
}
echo '<img src="data:image/png|image/jpeg|image/gif;base64,' . base64_encode( $content ) . '" />';
echo 'Hello world.';
}
else {
print "No image selected/uploaded";
}
?>
Also i am getting the below error while uploading file in phpmyadmin to a blob datatype
UPDATE `helpme`.`posts` SET `Photo` = 0xffd8ffe000104a46494600010201006000600000ffe10f074578696600004d4d002a0000000800060132000200000014000000564746000300000001000300004749000300000001003200009c9d00010000000e00000000ea1c0007000007f40000000087690004000000010000006a000000d4323030393a30333a31322031333a34373a34330000059003000200000014000000ac9004000200000014000000c0929100020000000335340000929200020000000335340000ea1c0007000007b40000000000000000323030383a30333a31342031333a35393a323600323030383a30333a31342031333a35393a3236000005010300030000000100060000011a00050000000100000116011b0005000000010000011e020100040000000100000126020200040000000100000dd90000000000000048000000010000004800000001ffd8ffe000104a46494600010100000100010000ffdb004300100b0c0e0c0a100e0d0e1211101318281a181616183123251d283a333d3c3933383740485c4e404457453738506d51575f626768673e4d71797064785c656763ffdb0043011112121815182f1a1a2f634238426363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363[...]
MySQL said:
2006 - MySQL server has gone away
Please let me know how to fix the issue. The issue is while displaying images. Whether some size issue is there i dont know please help here.
Using addslashes is nowhere near the correct way to do a SQL query. It will not always work correctly with binary data. I don't know what resource you're using, but it's teaching you very bad habits.
Please DO NOT USE mysql_query in new applications. This is a legacy interface from the 1990s that is in the process of being retired because of the hazards involved in using it incorrectly, something all too easy to do. It's best to use either mysqli or PDO in new projects.
Your query should look like this:
Update whyangry.posts set Photo=? where Pid=?
You can bind to those placeholders when executing the query and avoid having encoding problems. There are many examples on how to do this correctly.

Updating Images in MySQL with PHP

I am on my way to create the feature for users to upload their profile photo to the database. I manage to upload my photo to database in binary form (BLOB) but I am having problem while trying to display it.
upload form code:
<?php //get the posted image when the submit button is clicked
$username = "MentorMenteeData";
$password = "mentormenteedata";
$host = "localhost";
$database = "mentormenteesystem";
// 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);
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);
$student_id=$row_student['student_id'];
// Create the query and insert
// into our database.
$query = "UPDATE student SET student_img='$data' WHERE student_id ='$student_id'";
$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);
?>
<form action="" method="post" enctype="multipart/form-data" name="changer">
<strong style="color: #FFD700;">Upload your image:</strong><br />
<input name="MAX_FILE_SIZE" value="102400" type="hidden"><br /><br />
<input namge="image" accept="image/jpeg" type="file">
<input type="submit" value="Submit">
</form>
Code to display image:
<?php
$username = "MentorMenteeData";
$password = "mentormenteedata";
$host = "localhost";
$database = "mentormenteesystem";
mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());
mysql_select_db($database) or die("Can not select the database: ".mysql_error());
$id = $_REQUEST['student_id'];
if(!isset($id) || empty($id) || !is_int($id)){
die("Please select your image!");
}else{
$query = mysql_query("SELECT * FROM student WHERE student_id='".$id."'");
$row = mysql_fetch_array($query);
$content = $row['image'];
}
header('Content-type: image/jpeg');
echo $content;
?>
I could see my database table for the image column containing some bits but I just cant seems to display it. Please advise.
Your code to retrieve and display the image looks like it is correct, however I'm guessing you are never getting to the query due to this filtering line:
$id = $_REQUEST['student_id'];
if(!isset($id) || empty($id) || !is_int($id)){
die("Please select your image!");
}
is_int() tests if the type of a value is an integer, and values coming from $_GET, $_POST, $_REQUEST are always strings. , so your condition is always false. You can test it instead with ctype_digit() or is_numeric(), or intval($id) == $id. Also, empty() calls isset() implicitly, so isset() isn't needed.
// ctype_digit() method...
if (empty($id) || !ctype_digit($id)) {
die("Please select your image!");
}
// intval() method...
if (empty($id) || (intva($id) != $id)) { 
die("Please select your image!"); 
}
Without any errors, it's hard to say, but if it's not the ID problem as suggested by Michael, it might [also] be corruption of your image data on upload. Have you tried downloading the directly (eg wget that URL) and opening it locally? Is the JPEG header there?
Some general comments:
Are you sure you want to store images in the database? It's
generally preferred to store filename / URL fragments, and leave the
binary data on disk, especially if they're larger images. See
php:Store image into Mysql blob, Good or bad?
for a discussion.
Either way that upload code is asking for trouble. addslashes() is
not sufficient to fix the escaping problem, use a specific one like
mysqli::real escape-string
to safeguard against SQL Injection
attacks - this post explores some differences.
If your MySQL DB is hosted on the same box as your webserver, you
could even save effort (and increase speed) by using the MySQL LOAD_FILE function, but this isn't very scalable in the long term.
Consider moving all your login details to a separate file, out of the webroot for security.

Categories