10 Replies - 4525 Views - Last Post: 06 November 2011 - 02:52 PM Rate Topic: -----

#1 lesterdgreat123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 04-November 11

Update image to mysql to root folder

Posted 04 November 2011 - 08:40 AM

I would like to ask if anyone can help me to figure out on how to do on the next code, i know there are missing codes here thats why i can not update the image. Help me on this one

<?php 

session_start();
include('../../dbcon.php');

$id = $_POST['pid'];
$prodName = $_POST['prod'];
$price = $_POST['price'];
$desc = $_POST['des'];
$village = $_POST['village'];
$zip = $_POST['zip'];
$category = $_POST['cat'];
$company = $_POST['company'];
$file = $_POST['upload'];
$address = $_POST['add'];
$map = $_POST['map'];
$hours = $_POST['hours'];
$image = $_FILES['upload'];


if($_FILES['upload']['type'] != "image/jpeg" AND $_FILES['upload']['type'] != "image/jpeg") {
    echo '
    <script type="text/javascript">
    alert("Invalid Upload!");
    location = "../updateProduct.php";
    </script>
    ';
}elseif(is_uploaded_file($_FILES['upload']['tmp_name'])) {

    $res = mysql_query("SELECT * FROM `product` WHERE product.pid=".$id);
    $r = mysql_fetch_array($res);
    $fileName=$r['upload'];

    
    $path= '../images/products/';
    $folder='../images/products/';
    if (!file_exists($path)) {
       mkdir('../images/');
    }
    if (!file_exists($folder)){
            mkdir('../images/products/');
    }
    move_uploaded_file($_FILES['upload']['tmp_name'], $folder.$fileName);
    
}else{
    echo '
    <script type="text/javascript">
    alert("ERROR Upload!");
    location = "../updateProduct.php";
    </script>
    ';
}

$query = "UPDATE product 
SET 
	prodName='$prodName', price = '$price', company = '$company' ,description = '$desc',hours = '$hours', catid = '$category', filename = '$fileName',location = '$village', address ='$address', map = '$map'
WHERE 
	pid=$id";
$result = @mysql_query($query);

if($result){

echo '
<script type="text/javascript">
alert("You have already updated your product! - '.$fileName.'");
location = "../updateProduct.php";

</script>

';



}
else
{
	echo'not inserted';
	echo $id;
}

?>

   </div>
    
    </div>
</body>
</html>


This post has been edited by macosxnerd101: 04 November 2011 - 08:47 AM
Reason for edit:: Please use code tags


Is This A Good Question/Topic? 0
  • +

Replies To: Update image to mysql to root folder

#2 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 944
  • View blog
  • Posts: 2,353
  • Joined: 15-February 11

Re: Update image to mysql to root folder

Posted 04 November 2011 - 09:17 AM

Firstly you should look into protecting your database from SQL injections. You can use mysql_real_escape_string which isn't 100% immune to SQL injections or you could use Prepared Statements offered in MySQLi and PDO. Prepared statements however are 100% immune to injections.

Lines #38 - 42 is a bit redundant. Why didn't you pass $path to mkdir?

move_uploaded_file returns a boolean type telling you if it was successful or not. You should check the return type to make sure. You're also updating the database even though there's a possibility that the upload wasn't successful.

Have a look at this tutorial also: Making Your Site More User-Friendly By Handling Errors Correctly
Was This Post Helpful? 2
  • +
  • -

#3 lesterdgreat123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 04-November 11

Re: Update image to mysql to root folder

Posted 04 November 2011 - 09:27 AM

im really confuse, its my first time to use this concept really, is there a problem in this code
 $res = mysql_query("SELECT * FROM `product` WHERE product.pid=".$id);
    $r = mysql_fetch_array($res);
    $fileName=$r['upload'];


because it can not get the value of the image to be updated.
Was This Post Helpful? 0
  • +
  • -

#4 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 944
  • View blog
  • Posts: 2,353
  • Joined: 15-February 11

Re: Update image to mysql to root folder

Posted 04 November 2011 - 09:41 AM

Yes, you don't check the value of $id to make sure it's safe and you don't verify that mysql_fetch_array actually returned a resource and not FALSE. If $id is suppose to be a number then check it with is_int.

mysql_fetch_array return types:

Quote

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.


Always check the return types of functions. They are returned for a reason.
Was This Post Helpful? 0
  • +
  • -

#5 lesterdgreat123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 04-November 11

Re: Update image to mysql to root folder

Posted 04 November 2011 - 10:06 AM

i had tried to update it manually by setting the id of the product but doesnt really work.
Was This Post Helpful? 0
  • +
  • -

#6 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6036
  • View blog
  • Posts: 23,429
  • Joined: 23-August 08

Re: Update image to mysql to root folder

Posted 04 November 2011 - 12:48 PM

It Doesn't Work...That's Not Good Enough
Was This Post Helpful? 0
  • +
  • -

#7 AMZDeCoder  Icon User is offline

  • D.I.C Head

Reputation: 24
  • View blog
  • Posts: 102
  • Joined: 04-November 11

Re: Update image to mysql to root folder

Posted 04 November 2011 - 01:50 PM

Hi,

Here is my code, which I have used in one of my website to move uploaded file from one folder to another, hope it helps you.

<?php
	$MAX_FILE_SIZE = 200*1024;
	if ((/*($_FILES["albumPhoto"]["type"] == "image/gif") || ($_FILES["albumPhoto"]["type"] == "image/jpeg")  || ($_FILES["albumPhoto"]["type"] == "image/pjpeg") || ($_FILES["albumPhoto"]["type"] == "image/jpg")) && */($_FILES["albumPhoto"]["size"] < ($MAX_FILE_SIZE)))) {
		if ($_FILES["albumPhoto"]["error"] > 0) {
			/**
				Some error occured in uploading the file.
			*/
			navigateToPage("uploadPhotoForm.php?errorMessagKey=errorInUploadingFile");
		} else {
			$filePrefix = date("U", time()) + rand(1, 1000); // Here we generate a unique prefix for the file.
			$completeFileName = $filePrefix."_".$_FILES["albumPhoto"]["name"];
			if (file_exists("userImages/" . $completeFileName)) {
				/**
					The file already is existing on the server.
				*/
				navigateToPage("uploadPhotoForm.php?errorMessagKey=fileAlreadyExists");
			} else {
				/**
				The file was sucessfully uploaded.
				*/	
				move_uploaded_file($_FILES["albumPhoto"]["tmp_name"], "userImages/".$completeFileName);
				$queryToGetUserPicLibId = "SELECT pic_library_id AS pic_library_id FROM t_pic_library WHERE usr_id='$navgUserId'";
				$queryResult = executeQuery($queryToGetUserPicLibId);
				$libraryRow = mysql_fetch_array($queryResult);
				$libraryId = $libraryRow['pic_library_id'];
				$queryToInsertPicture = "INSERT INTO t_pic(pic_library_id, pic_path, pic_caption, pic_description) VALUES('$libraryId', '$completeFileName', '$_POST[photoCaption]', '$_POST[photoDescription]')";
				executeQuery($queryToInsertPicture);
				navigateToPage("uploadPhotoForm.php?sucessMessagKey=fileSucessFullyUploaded");
			}
	  }
	} else {
		
	  navigateToPage("uploadPhotoForm.php?errorMessagKey=fileOfUnspecfiedExtensionOrTooLarge");
	}
?>


Was This Post Helpful? 0
  • +
  • -

#8 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3712
  • View blog
  • Posts: 5,963
  • Joined: 08-June 10

Re: Update image to mysql to root folder

Posted 04 November 2011 - 03:22 PM

View Postcodeprada, on 04 November 2011 - 04:41 PM, said:

...If $id is suppose to be a number then check it with is_int.

Form input values are always strings so you'd have to use is_numeric to check it.

That, or cast it to an int and make sure it's not 0.


@lesterdgreat123
There are a few things in that code that you need to change. I've commented your code to point them out. A lot of them codeprada has already mentioned. These need to be fixed if you want this to work!

<?php
session_start();
include('../../dbcon.php');

// This is kind of pointless. You're basicall just creating
// duplicates of the $_POST values in the global scope. Why?
// You should, at the very least, be using mysql_real_escape_string
// here. Otherwise you may as well remove this and use the $_POST
// array directly.
$id = $_POST['pid'];
$prodName = $_POST['prod'];
$price = $_POST['price'];
$desc = $_POST['des'];
$village = $_POST['village'];
$zip = $_POST['zip'];
$category = $_POST['cat'];
$company = $_POST['company'];
$file = $_POST['upload'];
$address = $_POST['add'];
$map = $_POST['map'];
$hours = $_POST['hours'];
$image = $_FILES['upload'];

// This IF statements does the same exact check
// twice, once on either side of the AND keyword.
// Also, if you were checking two types you'd want to use
// the OR keyword, not AND. You want this to fail if *either*
// of them doesn't match, not if *both* of them do.
if ($_FILES['upload']['type'] != "image/jpeg" AND $_FILES['upload']['type'] != "image/jpeg") {
	echo '
    <script type="text/javascript">
    alert("Invalid Upload!");
    location = "../updateProduct.php";
    </script>
    ';
} elseif (is_uploaded_file($_FILES['upload']['tmp_name'])) {
	
	// You should test to see if the $res actually has a
	// valid result set before trying to use the
	// mysql_fetch_array function on it, in case the query
	// fails.
	// Also, seeing as you are only using the "upload" field,
	// why are you fetching all of them? You should specify
	// only the fields you need in a SELECT query. As a general
	// rule, never use the wild-card (*) in a select query!
	$res = mysql_query("SELECT * FROM `product` WHERE product.pid=" . $id);
	$r = mysql_fetch_array($res);
	$fileName = $r['upload'];


	// Both of these have the same value... I'm guessing
	// the $path variable was supposed to be just:
	//  "../images/"
	$path = '../images/products/';
	$folder = '../images/products/';
	if (!file_exists($path)) {
		// Why not use the $path variable here instead of
		// entering the path manually... again.
		// You should also be checking if the mkdir command
		// returns FALSE, to see if it failed. Because if it
		// fails to create the directory, the rest of the code
		// won't work.
		mkdir('../images/');
	}
	if (!file_exists($folder)) {
		// Same deal as with the above comment.
		mkdir('../images/products/');
	}
	// Capture and verify the return value of the function!
	// Otherwise you won't know if the function fails.
	move_uploaded_file($_FILES['upload']['tmp_name'], $folder . $fileName);
} else {
	echo '
    <script type="text/javascript">
    alert("ERROR Upload!");
    location = "../updateProduct.php";
    </script>
    ';
}

// Why is this query here? When you put it way out here
// it will execute regardless of whether the upload failed
// or not. (Not that you actually check that it does...)
// This should be in the IF statement above, to be executed
// only if the move_uploaded_file function succeeded.
$query = "UPDATE product 
SET 
	prodName='$prodName', price = '$price', company = '$company' ,description = '$desc',hours = '$hours', catid = '$category', filename = '$fileName',location = '$village', address ='$address', map = '$map'
WHERE 
	pid=$id";
$result = @mysql_query($query);

if ($result) {
	// In this IF statement you only check to see if the command
	// was executed successfully, but not if it did anything.
	// An UPDATE can execute successfully without actually 
	// updating a thing. Use the mysql_affected_rows function
	// to see how many rows were affected by the UPDATE, then
	// print a message based on that. (0 rows means it didn't,
	// 1 row means it did.)
	echo '
<script type="text/javascript">
alert("You have already updated your product! - ' . $fileName . '");
location = "../updateProduct.php";

</script>

';
} else {
	echo'not inserted';
	echo $id;
}
?>

<!-- Why the random HTML? -->
</div>

</div>
</body>
</html>


Was This Post Helpful? 1
  • +
  • -

#9 lesterdgreat123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 04-November 11

Re: Update image to mysql to root folder

Posted 06 November 2011 - 05:37 AM

I had already solved it. first i just delete the product and insert it the updated product a new product but it contains the old product id.



$pid = $_POST['pid'];


//First i deleted the product

$qdelete = "DELETE FROM product WHERE pid=$pid";
$result = @mysql_query($qdelete);


//After deleting i insert a product where it contains its old id	
if (isset($_POST['upload'])){
if($_FILES['upload']['type'] != "image/jpeg" AND
$_FILES['upload']['type'] != "image/jpeg")
{
echo "Invalid Upload";
query();
}elseif(is_uploaded_file($_FILES['upload']['tmp_name'])) {
$des=mysql_real_escape_string($_POST['des']);
$prod= $_POST['prod'];
$price = $_POST['price'];
$loc = $_POST['village'];
$zip = $_POST['zip'];
$cat = $_POST['cat'];
$subcat = $_POST['subcategory'];
$map = $_POST['map'];
$add = $_POST['add'];
$uid = $_SESSION['userID'];;
$hours = $_POST['hours'];
$company = $_POST['company'];
$id = $_POST['pid'];

$query= "INSERT INTO product(pid,userID,prodName,price,company,description,hours,catid,filename,filesize,type,location,address,zipcode,map,date_upload)
VALUES ('$id','$uid','$prod','$price','$company','$des','$hours','$cat','{$_FILES['upload']['name']}','{$_FILES['upload']['size']}','{$_FILES['upload']['type']}','$loc','$add','$zip','$map', NOW())";




Was This Post Helpful? 0
  • +
  • -

#10 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6036
  • View blog
  • Posts: 23,429
  • Joined: 23-August 08

Re: Update image to mysql to root folder

Posted 06 November 2011 - 06:16 AM

Of course it is, you are explicitly setting it to the old product ID!

Deleting old product id:
$pid = $_POST['pid'];


//First i deleted the product

$qdelete = "DELETE FROM product WHERE pid=$pid";


Setting new product:

$id = $_POST['pid'];

$query= "INSERT INTO product(pid,userID,prodName,price,company,description,hours,catid,filename,filesize,type,location,address,zipcode,map,date_upload)
VALUES ('$id','$uid','$prod','$price','$company','$des','$hours','$cat','{$_FILES['upload']['name']}','{$_FILES['upload']['size']}','{$_FILES['upload']['type']}','$loc','$add','$zip','$map', NOW())";



Same value!

If you want to generate a new ID, chances are (based on your product table definition) you want to pass NULL for the pid field so a new product ID will be generated. Also, if any of these fields are numeric, you should not be quoting them in the query.
Was This Post Helpful? 2
  • +
  • -

#11 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10385
  • View blog
  • Posts: 38,434
  • Joined: 27-December 08

Re: Update image to mysql to root folder

Posted 06 November 2011 - 02:52 PM

Also, don't just suppress any warnings you get: @mysql_query($qdelete);. There is the mysql_error() function for a reason. When you get SQL Errors, you want to know about them. At least die(mysql_error()) when a query fails. Or log it.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1