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
}
Related
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.
I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.
I'm having a brain dead moment... If someone could talk this through with me and make suggestions that'd be great.
I'm importing a URL from a database, eg www.mysite.com/images/image1.jpg set as variable newimage1
This is loaded from the DB and placed on the page.
As this is an edit page, the user can upload a new image.
If the user doesn't upload a new image, but saves the page anyway, the variable newimage1 is not set, it clears the existing image url from the database because the variable is set to "".
What's the best way to do this? An if statement, that checks if newimage1 is blank and removes it from the update to the database?
Sorry for this simple question!
$image_name = "";
if(!empty($_FILES)){
$image_name = $_FILES['image']['tmp_name'];
}
$sql = "UPDATE table SET var1 = 'value1', var2='value2'";
if($image_name != "")
$sql .= ", image_name = '".$image_name."'";
$sql .= " WHERE id_entry = 5";
if( empty($_REQUEST['newImage1']) ) {
//program logic
} else {
//program logic
}
Ok, this one is driving me nuts. I have a backend file uploader that uploads .jpg files to the server. Then I want to upload the filename(s) of the .jpgs to my database. So when the page loads I can add the filename from the database and the pictures will display on the page. This works fine, but I also need to be able to update the files and the filenames in the database. If the user changes all the files and file names everything is fine. But if the user wishes to change only one or two file(s) and filename(s) the MySql update statement ends up having some of the variables empty thereby effectively deleting the existing filenames in the record instead of leaving them alone. As usual I have searched stackoverflow and google before asking for help and I have not found anything that is really pertinent. Here is the applicable code.
<?php
session_start();
$id = $_SESSION['id'];
//This is the directory where images will be saved
$target = "imgs/";
// "http://www.surfcup.com/travel_site/images/ ";
$targetlogo = $target . basename( $_FILES['imageLogo']['name']);
$targetpic1 = $target . basename( $_FILES['image1']['name']);
$targetpic2 = $target . basename( $_FILES['image2']['name']);
$targetpic3 = $target . basename( $_FILES['image3']['name']);
$targetpic4 = $target . basename( $_FILES['image4']['name']);
$targetpic5 = $target . basename( $_FILES['image5']['name']);
//This gets all the other information from the form
$logo=($_FILES['imageLogo']['name']);
$pic1=($_FILES['image1']['name']);
$pic2=($_FILES['image2']['name']);
$pic3=($_FILES['image3']['name']);
$pic4=($_FILES['image4']['name']);
$pic5=($_FILES['image5']['name']);
// Connects to Database
mysql_connect("localhost", "surfcup_HotAdmin","password") or die ('I cannot connect to the database because: ' .mysql_error());
mysql_select_db("surfcup_hotels") or die('I cannot connect to the database because: .mysql_error());
$query="UPDATE Hotels
SET
hotel.imageLogo = '".$logo."',
hotel.image1 = '".$pic1."',
hotel.image2 = '".$pic1."',
hotel.image3 ='".$pic1."',
hotel.image4 = '".$pic1."',
hotel.image5 = '".$pic1."'
WHERE Hotels.id='".$id."'";
mysql_query($query) or die ('Error Updating Hotel '.mysql_error());
//stuff to upload the files below
?>
I think I either need to check if the variables are null and somehow not up load them or stop the database from accepting null entries. The later though would make the user have to add 6 files when he/she creates a record. What if they only had 5 or 3? I can't seem to get my head around how I would check if the variables are null and only upload the ones with filenames in them in the UPLOAD statement. Thanks again, in advance, for all your help.
Dave
I think a better way of doing this is to build your query dynamically. For example:
$images = array();
$images[] = ($_FILES['imageLogo']['name']);
$images[] = ($_FILES['image1']['name']);
$images[] = ($_FILES['image2']['name']);
$images[] = ($_FILES['image3']['name']);
$images[] = ($_FILES['image4']['name']);
$images[] = ($_FILES['image5']['name']);
// Looping index to determine which hotel image it is
$index = 0;
// Start building query
$query = "UPDATE Hotels SET hotel.imageLogo = '".$images[0]."'";
// Loop through images and check if empty string
foreach($images as $image)
{
if(!empty($image) && $index != 0)
{
// Image name found, add to query
$query .= " hotel.image".$index." = '".$image."',";
}
// First hotel image iteration needs to be 1
$index++;
}
// Finish query
$query .= " WHERE Hotels.id='".$id."'";
You can try this. Basically it checks if the value is empty. If it is not, then it adds the value to the array. At the end we implode the array into a string that we will add to the your query. In the example I only did a few of the images, but you should get the point. It should work barring syntax errors in my code.
Although I will say that this is not the best way to do it. You can definitely improve on this and make it more secure and efficient.
$uploaded_images = array();
if(!empty($logo)){
$uploaded_images[] = "hotel.imageLogo = '".$logo."'";
}
if(!empty($pic1)){
$uploaded_images[] = "hotel.image1 = '".$pic1."'";
}
if(!empty($pic2)){
$uploaded_images[] = "hotel.image2 = '".$pic2."'";
}
$values_to_set = implode(', ', $uploaded_images);
$query= "UPDATE Hotels SET " . $values_to_set . " WHERE Hotels.id='" . $id . "'";
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.