Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

CornerBLUE, Inc. http://www.cornerblue.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 13 total  RSS 

PHP: Create a SELECT input field

Creates a SELECT input field with an optional parameter to preselect an item

   1  
   2  function selectfield($optionsarray, $selected = "") {
   3    $returnval = "";
   4    foreach ($optionsarray as $field=>$value) {
   5      if ($field == $selected) {
   6        $returnval .= "<option selected value='" . $field . "'>" . $value . "</option>\n";
   7      } else {
   8        $returnval .= "<option value='" . $field . "'>" . $value . "</option>\n";
   9      }
  10    }
  11    
  12    return $returnval;
  13  }

SQL SERVER: Delete Duplicate Rows with Primary Id

Deletes duplicates (leaving one instance) where the table has a primary key. Good for tables with Id, DupColumn, DupColumn...

(This is MS-SQL specific)

   1  
   2  DELETE
   3  FROM 	TableName
   4  WHERE 	Id NOT IN
   5  	(SELECT 	MAX(Id)
   6          FROM   		TableName
   7          GROUP BY 	DuplicateColumName1, DuplicateColumName2)

PHP: Insert Data Into MySQL Table Using An Array

Inserts the values of an array into a table. Also supports specifying if a specific field needs to be encoded using PASSWORD()
Parameters:
Table: Name of table to insert into
Data: array of $field->$value of new data
Password Field: Which field in the data array needs to be surrounded with PASSWORD() (optional)

   1  
   2  function mysql_insert_array($table, $data, $password_field = "") {
   3  	foreach ($data as $field=>$value) {
   4  		$fields[] = '`' . $field . '`';
   5  		
   6  		if ($field == $password_field) {
   7  			$values[] = "PASSWORD('" . mysql_real_escape_string($value) . "')";
   8  		} else {
   9  			$values[] = "'" . mysql_real_escape_string($value) . "'";
  10  		}
  11  	}
  12  	$field_list = join(',', $fields);
  13  	$value_list = join(', ', $values);
  14  	
  15  	$query = "INSERT INTO `" . $table . "` (" . $field_list . ") VALUES (" . $value_list . ")";
  16  	
  17  	return $query;
  18  }

PHP: Update MySQL Table Using An Array

Parameters:
Table: Name of table to update
Data: array of $field->$value with new values
Id Field: Name of field to use as ID field
Id Value: Value of ID field

   1  
   2  function mysql_update_array($table, $data, $id_field, $id_value) {
   3  	foreach ($data as $field=>$value) {
   4  		$fields[] = sprintf("`%s` = '%s'", $field, mysql_real_escape_string($value));
   5  	}
   6  	$field_list = join(',', $fields);
   7  	
   8  	$query = sprintf("UPDATE `%s` SET %s WHERE `%s` = %s", $table, $field_list, $id_field, intval($id_value));
   9  	
  10  	return $query;
  11  }

PHP: Print List of States For A Select Field And Preselect A Value

Prints a list of US states for a <select> field and selects a predefined value. Use like this:
echo "<select name='billing_state'>";
state_list($_POST['billing_state']);
echo "</select>";

You can also convert this function to return a value instead of directly outputting

   1  
   2  function state_list($sel='') {
   3  	echo "<option value='AL'".($sel=='AL'?' selected':'').">Alabama</option>";
   4  	echo "<option value='AK'".($sel=='AK'?' selected':'').">Alaska</option>";
   5  	echo "<option value='AZ'".($sel=='AZ'?' selected':'').">Arizona</option>";
   6  	echo "<option value='AR'".($sel=='AR'?' selected':'').">Arkansas</option>";
   7  	echo "<option value='CA'".($sel=='CA'?' selected':'').">California</option>";
   8  	echo "<option value='CO'".($sel=='CO'?' selected':'').">Colorado</option>";
   9  	echo "<option value='CT'".($sel=='CT'?' selected':'').">Connecticut</option>";
  10  	echo "<option value='DE'".($sel=='DE'?' selected':'').">Delaware</option>";
  11  	echo "<option value='DC'".($sel=='DC'?' selected':'').">District of Columbia</option>";
  12  	echo "<option value='FL'".($sel=='FL'?' selected':'').">Florida</option>";
  13  	echo "<option value='GA'".($sel=='GA'?' selected':'').">Georgia</option>";
  14  	echo "<option value='GU'".($sel=='GU'?' selected':'').">Guam</option>";
  15  	echo "<option value='HI'".($sel=='HI'?' selected':'').">Hawaii</option>";
  16  	echo "<option value='ID'".($sel=='ID'?' selected':'').">Idaho</option>";
  17  	echo "<option value='IL'".($sel=='IL'?' selected':'').">Illinois</option>";
  18  	echo "<option value='IN'".($sel=='IN'?' selected':'').">Indiana</option>";
  19  	echo "<option value='IA'".($sel=='IA'?' selected':'').">Iowa</option>";
  20  	echo "<option value='KS'".($sel=='KS'?' selected':'').">Kansas</option>";
  21  	echo "<option value='KY'".($sel=='KY'?' selected':'').">Kentucky</option>";
  22  	echo "<option value='LA'".($sel=='LA'?' selected':'').">Louisiana</option>";
  23  	echo "<option value='ME'".($sel=='ME'?' selected':'').">Maine</option>";
  24  	echo "<option value='MD'".($sel=='MD'?' selected':'').">Maryland</option>";
  25  	echo "<option value='MA'".($sel=='MA'?' selected':'').">Massachusetts</option>";
  26  	echo "<option value='MI'".($sel=='MI'?' selected':'').">Michigan</option>";
  27  	echo "<option value='MN'".($sel=='MN'?' selected':'').">Minnesota</option>";
  28  	echo "<option value='MS'".($sel=='MS'?' selected':'').">Mississippi</option>";
  29  	echo "<option value='MO'".($sel=='MO'?' selected':'').">Missouri</option>";
  30  	echo "<option value='MT'".($sel=='MT'?' selected':'').">Montana</option>";
  31  	echo "<option value='NE'".($sel=='NE'?' selected':'').">Nebraska</option>";
  32  	echo "<option value='NV'".($sel=='NV'?' selected':'').">Nevada</option>";
  33  	echo "<option value='NH'".($sel=='NH'?' selected':'').">New Hampshire</option>";
  34  	echo "<option value='NJ'".($sel=='NJ'?' selected':'').">New Jersey</option>";
  35  	echo "<option value='NM'".($sel=='NM'?' selected':'').">New Mexico</option>";
  36  	echo "<option value='NY'".($sel=='NY'?' selected':'').">New York</option>";
  37  	echo "<option value='NC'".($sel=='NC'?' selected':'').">North Carolina</option>";
  38  	echo "<option value='ND'".($sel=='ND'?' selected':'').">North Dakota</option>";
  39  	echo "<option value='OH'".($sel=='OH'?' selected':'').">Ohio</option>";
  40  	echo "<option value='OK'".($sel=='OK'?' selected':'').">Oklahoma</option>";
  41  	echo "<option value='OR'".($sel=='OR'?' selected':'').">Oregon</option>";
  42  	echo "<option value='PW'".($sel=='PW'?' selected':'').">Palau</option>";
  43  	echo "<option value='PA'".($sel=='PA'?' selected':'').">Pennsylvania</option>";
  44  	echo "<option value='PR'".($sel=='PR'?' selected':'').">Puerto Rico</option>";
  45  	echo "<option value='RI'".($sel=='RI'?' selected':'').">Rhode Island</option>";
  46  	echo "<option value='SC'".($sel=='SC'?' selected':'').">South Carolina</option>";
  47  	echo "<option value='SD'".($sel=='SD'?' selected':'').">South Dakota</option>";
  48  	echo "<option value='TN'".($sel=='TN'?' selected':'').">Tennessee</option>";
  49  	echo "<option value='TX'".($sel=='TX'?' selected':'').">Texas</option>";
  50  	echo "<option value='UT'".($sel=='UT'?' selected':'').">Utah</option>";
  51  	echo "<option value='VT'".($sel=='VT'?' selected':'').">Vermont</option>";
  52  	echo "<option value='VI'".($sel=='VI'?' selected':'').">Virgin Islands</option>";
  53  	echo "<option value='VA'".($sel=='VA'?' selected':'').">Virginia</option>";
  54  	echo "<option value='WA'".($sel=='WA'?' selected':'').">Washington</option>";
  55  	echo "<option value='WV'".($sel=='WV'?' selected':'').">West Virginia</option>";
  56  	echo "<option value='WI'".($sel=='WI'?' selected':'').">Wisconsin</option>";
  57  	echo "<option value='WY'".($sel=='WY'?' selected':'').">Wyoming</option>";
  58  }

PHP: Email All Form Values

If you need a very basic contact form and don't want to write extra code for putting the value of each field into the email, you can use this basic email. It works best if you name your form fields something legible, such as First_Name

   1  
   2  if (isset($_POST['Submit'])) {
   3  	// Prepare message
   4  	$msg = "Time: " . date("m/d/y g:ia", time()) . "\n";
   5  	foreach ($_POST as $field=>$value) {
   6  		if ($field != "submit") $msg .= $field . ": " . $value . "\n";
   7  	}
   8  	
   9  	if (mail("TOEMAIL", "SUBJECT", $msg, "From: FROM_NAME <FROM@ADDRESS.com>")) {
  10  		// Email was sent
  11  	} else {
  12  		// Erro sending email
  13  	}
  14  }

PHP: Pass On Values For A Multi-Page Form

While the best way to do this involves saving the data into a database and passing an encrypted reference to the next page, this method will suffice for non-critical uses.

   1  
   2  foreach ($_POST as $field=>$value) {
   3  	echo "<input type=\"hidden\" name=\"" . $field . "\" value=\"" . $value . "\" />";
   4  }

C#: Resize An Image While Maintaining Aspect Ratio and Maximum Height

// This allows us to resize the image. It prevents skewed images and
// also vertically long images caused by trying to maintain the aspect
// ratio on images who's height is larger than their width

   1  
   2  public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
   3  {
   4  	System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);
   5  
   6  	// Prevent using images internal thumbnail
   7  	FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
   8  	FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
   9  
  10  	if (OnlyResizeIfWider)
  11  	{
  12  		if (FullsizeImage.Width <= NewWidth)
  13  		{
  14  			NewWidth = FullsizeImage.Width;
  15  		}
  16  	}
  17  
  18  	int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
  19  	if (NewHeight > MaxHeight)
  20  	{
  21  		// Resize with height instead
  22  		NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
  23  		NewHeight = MaxHeight;
  24  	}
  25  
  26  	System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
  27  
  28  	// Clear handle to original file so that we can overwrite it if necessary
  29  	FullsizeImage.Dispose();
  30  
  31  	// Save resized picture
  32  	NewImage.Save(NewFile);
  33  }

C#: Break Long Strings of Text That Don't Contain A Space

Long strings of text with no spaces breaks most tables since the browser doesn't know where to start a new line. This function breaks a string after a number of characters so that they can be properly displayed in tables

   1  
   2  // Put this at the top
   3  using System.Text.RegularExpressions;
   4  //
   5  
   6  public string BreakLongString(string SubjectString, int CharsToBreakAfter)
   7  {
   8  	string Pattern = "\\S{" + CharsToBreakAfter + ",}";
   9  	int Counter = 0;
  10  	bool IsMatching = Regex.IsMatch(SubjectString, Pattern);
  11  	while (IsMatching)
  12  	{
  13  
  14  		Counter++;
  15  		string MatchedString = Regex.Match(SubjectString, Pattern).Value;
  16  		SubjectString = SubjectString.Replace(MatchedString.Substring(0, (CharsToBreakAfter - 1)), MatchedString.Substring(0, (CharsToBreakAfter - 1)) + " ");
  17  
  18  		// Prevent endless loops
  19  		if (Counter > 20) break;
  20  
  21  		// Check if we still have long strings
  22  		IsMatching = Regex.IsMatch(SubjectString, Pattern);
  23  	}
  24  
  25  	return SubjectString;
  26  }
  27  

C#: Log A Message To A File

   1  
   2  // Put this at the top
   3  using System.IO;
   4  //
   5  
   6  public static void Log(string Message)
   7  {
   8  	File.AppendAllText(HttpContext.Current.Server.MapPath("~") + "/log.txt", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + Message + Environment.NewLine);
   9  }
« Newer Snippets
Older Snippets »
Showing 1-10 of 13 total  RSS