Jump to content

Updating Records But Problem With Errors And Retaining Field Values


AJayUK

Recommended Posts

Hey,

Im needing some help with an update form that I have created using PHP/MySQL. Basically the form is working great (updating records, retrieving records and showing errors) but there is a problem with the errors.

 

If there are no errors and I edit the existing text input values, the database updates fine. However if I edit the existing text input values and there is an error, the edited input values dont save, they revert back to the values of the database.

 

I understand why this is happening, its because the text inputs are set to show the values of the database so if i edit the existing values and an error occurs or the page is refreshed, the values revert back to the database values. However id like it so that if any text in the text field have been edited and an error occurs, the text stays to how it is until the user by passes any errors and then the database is updated.

 

Hopefully this makes sense. I have attached the php page just incase anybody wants to look into it but any help would be much appreciated!

 

Also, im not looking for someone to just to fix this for me but if someone knows my problem and can guide me in the right direction, that would be great.

 

[attachment deleted by admin]

Link to comment
Share on other sites

<?php include_once('header.php');?>
<?php

if($_GET['id'] != "")
$id = $_GET['id'];
$fileName=array();

if(isset($_GET['id']))
{
$result = mysql_query("SELECT * FROM news WHERE id='$_GET[id]'");
while($row = mysql_fetch_assoc($result))
{
	$title = stripslashes($row["title"]);
	$short_description = stripslashes ($row["short_description"]);
	$long_description = stripslashes ($row["long_description"]); 
	$category = stripslashes ($row["category"]); 
	$tags = stripslashes ($row["tags"]);
	$page = stripslashes ($row["page"]); 
	$image_01= stripslashes ($row["image1"]);
}
}
   
if($_POST['act']=='d')
{
$i=$_POST['del'];
$title = mysql_real_escape_string(trim($_POST['title']));
$short_description = mysql_real_escape_string(trim($_POST['short_description']));
$long_description = str_replace('\r\n', '', mysql_real_escape_string(trim($_POST['long_description'])));
$category = mysql_real_escape_string(trim($_POST['category']));
$tags = mysql_real_escape_string(trim($_POST['tags']));
$page = mysql_real_escape_string(trim($_POST['page']));

switch($i)
{
	case 1:
	$sql3 = "UPDATE news SET title=".$db->qstr ($title).", short_description=".$db->qstr ($short_description).", long_description=".$db->qstr ( $long_description ).", category=".$db->qstr ( $category ).", tags=".$db->qstr ( $tags ).", page=".$db->qstr ( $page ).", image1='' WHERE id='$_GET[id]'";						
	break;
}

$result = mysql_query("SELECT * FROM news WHERE id='$_GET[id]'");
while ($row = mysql_fetch_assoc($result))
{
	$imgname = "image".$i;
	$mainpicp = '../images/news/'.$row[$imgname];
	$thumbpicp= '../images/news/thumbnails/'.$row[$imgname];
		unlink($mainpicp);
	unlink($thumbpicp);
}	
        
$query = $db->query ($sql3);		
    $url2go = "edit_news_article.php?id=".$id;
  	header("Location: $url2go");
}

if($_POST['act']=='s')
{
$result = mysql_query("SELECT * FROM news WHERE id='$_GET[id]'");
$row = mysql_fetch_assoc($result);

if (empty($_POST['title']))
{
	$error = 'Please enter a title';
} 
elseif (empty($_POST['short_description']))
{
	$error = 'Please enter a short description';
} 
elseif (empty($_POST['long_description']))
{
	$error = 'Please enter a long description';
}
elseif (empty($_POST['category']))
{
	$error = 'Please enter a category';
}
else 
{	
	for($i=0;$i<=1;$i++)
	{		
        	$j = $i - 1;
		$fileName[$j]=$row["image".$i];

		if(!empty($_FILES["userfile0".$i]["name"]))
		{
			$file=$_FILES["userfile0".$i]["name"];

			if ($_FILES["userfile0".$i]["error"] > 0)
			{
				$err=$_FILES["userfile0".$i]["error"] . "<br />";
			}	
			else if($size<1048576)
			{
				$brk_org_file = explode(".",$file);
				$file_extnsn = $brk_org_file[1];
				srand ((double) microtime( )*1000000);
				$file=date("Ymd").'_'.rand().".".$file_extnsn;

				$news_photo_W = 600;
				$news_photo_H = 600;
				$thumb_photo_W = 300;
				$thumb_photo_H = 300;

				$file_type = $_FILES["userfile0".$i]['type'];
				$file_name = $_FILES["userfile0".$i]['name'];
				$file_size = $_FILES["userfile0".$i]['size'];
				$file_tmp  = $_FILES["userfile0".$i]['tmp_name'];

				if(is_uploaded_file($file_tmp) && $file_size)
				{  
					$rand_name = $file;
					// strip extension from filename
					$ext = strrchr($rand_name, '.'); 

					if($ext !== false){
	 				$rand_name = substr($rand_name, 0, -strlen($ext));
					// and replace it with forced jpg
	 				$rand_name.=".jpg";

					if($file_size)
					{
						if($file_type == "image/gif")
						{
							$new_img = imagecreatefromgif($file_tmp);				
						}
						elseif($file_type == "image/x-png" || $file_type == "image/png")
						{
							$new_img = imagecreatefrompng($file_tmp);
						}
						elseif($file_type == "image/pjpeg" || $file_type == "image/jpeg")
						{
							$new_img = imagecreatefromjpeg($file_tmp);
						}
						else 
						{
							// raise an error due to unknown format 
							$error="Unsupported image format: only png, gif, and jpg files are accepted.";
							$new_image=false;
						}

						list($width, $height) = getimagesize($file_tmp);
						$ratio_H = $height/$news_photo_H;
						$ratio_W = $width/$news_photo_W;
						$thumb_ratio_H = $height/$thumb_photo_H; 
						$thumb_ratio_W = $width/$thumb_photo_W; 

						if($ratio_H>=1 || $ratio_W>=1)
						{
							if($ratio_H > $ratio_W)
							{
								$newheight 	= $news_photo_H; 
								$newwidth 	= ceil($width*$news_photo_H/$height);
							}
							else
							{
								$newheight 	= ceil($news_photo_W*$height/$width); 
								$newwidth 	= $news_photo_W;
							}
						}
						else
						{ 
							$newheight 	= $height; 
							$newwidth 	= $width;
						}
                      
				    	if($thumb_ratio_H>=1 || $thumb_ratio_W>=1)
						{
							if($thumb_ratio_H > $thumb_ratio_W)
							{
								$thumb_newheight = $thumb_photo_H; 
								$thumb_newwidth = ceil($width*$thumb_photo_H/$height);
							}
							else
							{
								$thumb_newheight = ceil($thumb_photo_W*$height/$width); 
								$thumb_newwidth = $thumb_photo_W;
							}
						}
						else
						{
							$thumb_newheight = $height; 
							$thumb_newwidth = $width;
						}

						if (function_exists(imagecreatetruecolor))
						{
							$resized_img = imagecreatetruecolor($newwidth,$newheight);
                            	$resized_thumb = imagecreatetruecolor($thumb_newwidth,$thumb_newheight);
						}

						// dont run image conversion if an error occured 
						if (!isset($error))
						{
							imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
							//save image
							@ImageJpeg ($resized_img, "../images/news/".$rand_name, 100);
							imagecopyresampled($resized_thumb, $new_img, 0, 0, 0, 0, $thumb_newwidth, $thumb_newheight, $width, $height);
						}

						@ImageJpeg ($resized_thumb, "../images/news/thumbnails/".$rand_name, 100);
						@ImageDestroy ($resized_img);
						@ImageDestroy ($resized_thumb);
						@ImageDestroy ($new_img);
					}		   		  
				}

				$photo.="userfile".$i."='".$file."',";
			}
			else
			{
				$msg="Image size is too big";
			}

			$fileName[$j]=$rand_name;
		}	
	}	

	$title = mysql_real_escape_string(trim($_POST['title']));
	$short_description = mysql_real_escape_string(trim($_POST['short_description']));
	$long_description = str_replace('\r\n', '', mysql_real_escape_string(trim($_POST['long_description'])));
	$category = mysql_real_escape_string(trim($_POST['category']));
	$tags = mysql_real_escape_string(trim($_POST['tags']));
	$page = mysql_real_escape_string(trim($_POST['page']));
	$f0 = $fileName[0];

	if ( !isset ( $error ) )
	{
		$result = mysql_query("UPDATE news SET title=".$db->qstr ($title).", short_description=".$db->qstr ($short_description).", long_description=".$db->qstr ( $long_description ).", category=".$db->qstr ( $category ).", tags=".$db->qstr ( $tags ).", page=".$db->qstr ( $page ).", image1='$f0' WHERE id='$_GET[id]'");

	$msg = 'The news has been updated!';
	}
	else
	{
		$msg = $error;
	}
}
}
}
?>

	  <div id="main">
    	  <?php include_once('menu.php');?>
    	  <div id="content">
          <?php	if ( isset ( $msg ) )	{ echo '<div id="msg">' .  $msg . '</div>'; } else { ?>
       	  <div id="title_header">Edit News</div>        
          <div id="form">
          <?php	if ( isset ( $error ) )	{ echo '<div id="error">' . $error . '</div>' ;	}	?>
          
          <form name="form1" enctype="multipart/form-data" action="<?php echo $PHP_SELF ?>" method="post">
      <input type="hidden" name="id" value="<? echo ($id) ?>">
          <input type="hidden" name="_submit_check" value="1"/>
          <input type="hidden" name="author" id="author" value="<?php if(isset( $_SESSION['user_id'])){echo ''. get_username ( $_SESSION['user_id'] ) .'';}?>"/>
          <input type="hidden" name="authors_email" id="authors_email" value="<?php if(isset( $_SESSION['user_id'])){echo ''. get_email ( $_SESSION['user_id'] ) .'';}?>"/>
          <input type="hidden" name="page" id="page" value="News">
          
          <label>Title*</label>
          <input type="text" name="title" id="title" class="titleInput" value="<? echo htmlspecialchars($title); ?>">
          <div class="spacer"></div>
    
          <label>Short Description*</label>
          <textarea name="short_description" id="mceNoEditor1" class="mceNoEditor" /><? echo stripslashes ($short_description); ?></textarea>
          <div id="counter_box"><span class="counter"></span></div>
    
          <label>Long Description*</label>
          <textarea name="long_description" id="long_description" class="textareaInput" /><? echo stripslashes ($long_description); ?></textarea>
          <div class="spacer"></div>
          
          <label>Category*</label>
          <select name="category" id="category" class="listInput">
          	<option selected value="" <?php if ($category == ''){ echo ' selected=selected'; } ?>></option>
            <option value="Psychopathic" <?php if ($category == 'Psychopathic'){ echo ' selected=selected'; } ?>>Psychopathic</option>
            <option value="Underground" <?php if ($category == 'Underground'){ echo ' selected=selected'; } ?>>Underground</option>
            <option value="Family" <?php if ($category == 'Family'){ echo ' selected=selected'; } ?>>Family</option>
            <option value="Other" <?php if ($category == 'Other'){ echo ' selected=selected'; } ?>>Other</option>
          </select>
          <div class="spacer"></div>
          
          <div id="image_container">
          <label>Image (W 200px x H 147px)</label>
          <?php if($image_01!='') {
	  echo '<div class="image_thumbnail"><img src="../images/news/thumbnails/'.$image_01.'" border="0"/></div><div class="image_details"><img onclick="h_del(1);" src="images/del_images.png" border="0" /></div><input type="hidden" name="userfile01" id="userfile01">';} else { echo '<input name="userfile01" type="file" id="userfile01">';} ?>
          </div>
          <div class="clear"></div>
          <div class="spacer"></div>
          
          <label>Tags (Seperate tags with commas)</label>
          <input type="text" name="tags" id="tags" class="titleInput" value="<? echo stripslashes ($tags); ?>">
          <div class="spacer"></div>
          
          <div class="required">* Marks required fields</div>
          <div id="button_box">
          	<input type="submit" onclick="h_upload()" value="SUBMIT">
          	<input type="hidden" name="act" /><input name="del"  type="hidden" />
          </div>
          <div class="clear"></div>

	<script language="JavaScript">
	function h_upload()
	{
		for(var i=1;i<=1;i++)
		{	
			if(document.getElementById("userfile0"+i).value!='')
			{
				str=document.getElementById("userfile0"+i).value;
				str=str.substr(str.length-3);
			}
		}

		document.form1.act.value='s';
		document.form1.submit();
	}
	function h_del(val)
	{
		var agree=confirm('Are you sure you want to delete?');
		if (agree)
		{
			document.form1.act.value='d';
			document.form1.del.value=val;
			document.form1.submit();
		}
		else
		{
			return false ;
		}
	}
	</script>
        </form>
        </div>
        <? } ?>
</div>
    <div class="clear"></div>
</div>
<?php include_once('footer.php');?>

Link to comment
Share on other sites

I didn't go through all of the code, but a couple things that were immediately noticeable and should be addressed:

 

There should be no need to use stripslashes() on data returned from a database query. If the data is still escaped when it's retrieved, it wasn't properly inserted to begin with.

 

That same database query is being executed with unsanitized data, and is wide open to SQL injection.

 

Dont' use $_SERVER['PHP_SELF'] as a form action as it presents a known XSS vulnerability. To submit a form to itself, use action="" instead.

 

As for your problem with retaining the values entered by the user, you ought to be able to just use a conditional to see if the $_POST var associated with the field is not empty, and echo it instead of the db value. So if $_POST['field_name'] is not empty, echo it as the field's value=, elseif the value from the db query is not empty, echo it as the field's value.

Link to comment
Share on other sites

Hi, thanks for the heads up on the unsanitized data, however i was told to use mysql_real_escape_string before submitting data to a database which adds the slashes. So when retrieving the data, i need to use stripslashes to output the data correctly?

 

"mysql_real_escape_string = this function must always (with few exceptions) be used to make data safe before sending a query to MySQL."

 

how would i properly insert data into the database to begin with so that slashes arent added?

Link to comment
Share on other sites

Hi Pikachu,

I solved the initial problem of this post thanks to your help!! Thankyou so much and incase anyone is reading this with the same problem, here is what I did, for example, in the title text input field, I replaced the following line from the value of that text field which was:

 

<? echo htmlspecialchars($title); ?>

 

and replaced it to this:

 

<?php if(isset($_POST['title'])){echo htmlspecialchars($_POST['title']);} else if (isset($title)) {echo htmlspecialchars($title);}?>

 

Works great, thankyou again pikachu!

 

 

Link to comment
Share on other sites

The slashes aren't actually inserted into the database. If the data in the database has slashes still in it, it would be because magic_quotes_gpc is on in the php.ini file (which it really shouldn't be). For code portability you should use a function to check for that and handle it accordingly. Numeric values don't need to be escaped, but do need to be validated, and cast as the proper type (int, float, etc.).

 

function STRING_SANITIZE($data) {
if( get_magic_quotes_gpc() ) {
	$data = mysql_real_escape_string(stripslashes($data));
} else {
	$data = mysql_real_escape_string($data);
}
return $data;
}
// usage
$var = STRING_SANITIZE($var);

Link to comment
Share on other sites

Okay im sorry to be a pain but i checked if magic quotes is disabled and it says it is, yet the following:

 

Hello "AJay"

 

is appearing in the database as:

 

Hello \"AJay\"

 

However when I enabled magic quotes, the text will appear in the database as:

 

Hello \\\"AJay\\\"

 

so with magic quotes disabled, i get one slash appearing before a quote symbol and with magic quotes enabled, i get three slashes... but either way, I am still getting slashes no matter if i enable or disable magic quotes?

 

 

Link to comment
Share on other sites

Hi, thanks for replying so fast,

nope ive never used addslashes anywhere. And yup thats what I see when i view the data in phpmyadmin. I turned off magic quotes using htaccess as i dont have acess to the php.ini file, maybe this is the problem?

Link to comment
Share on other sites

Yup i used that script and it says magic quotes is off but im still getting slashes. Nevermind, I have contacted the server admin as It says magic quotes is on in the php settings so im guessing thats why. I have asked him to turn off magic quotes in the php.ini file aswell so hopefully that will solve the problem. Thanks again.

Link to comment
Share on other sites

I have one last problem with the form remembering values... even though i posted a solution for remembering text input values, i have a problem getting this to work for drop down boxes!

 

Heres the code i am using which i presumed would work but if an error occurs, its showing the database value again.

 

<option value="Psychopathic" <?php if ((isset($_POST['category']))&&($_POST['category'] == 'Psychopathic')) { echo ' selected=selected'; } 
	  else if ((isset($category))&&($category == 'Psychopathic')) { echo ' selected=selected'; } ?>>Psychopathic</option>

 

If anybody can help me with this last problem with solving this issue, it would be appreciated!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.