INSERT from and HTML form

<!-------------------------------->
<!-------------------------------->
<!----- ADD TO DATABASE FORM ----->
<!-------------------------------->
<!-------------------------------->
<h2>Add To Database</h2>
<?php
if ( (isset($_POST['action'])) && ($_POST['action'] == "add_to_database") )
{
	$field1 = mysqli_real_escape_string($dblink, $_POST['field1']);
	$field2 = mysqli_real_escape_string($dblink, $_POST['field2']);
	
	//$field1 = trim($field1);
	//$field1 = ucwords($field1);
	
	$field_checkbox = 0;
	if(isset($_POST['field_checkbox']) && $_POST['field_checkbox'] == 'Yes')
		$field_checkbox = 1;
	

	$query1 = mysqli_query("SELECT * FROM my_table WHERE field1 = '$field1'");
	if (mysqli_num_rows($query1))
	{
		echo "VALUE ALREADY EXISTS!<br />";
	}
	else if ( ($field1 == "") || ($field2 == "") )
	{
		echo "INVALID FORM CONTENTS!<br />";
	}
	else
	{
		$result = mysqli_query("INSERT INTO my_table (
																field1,
																field2,
																field_checkbox
														) VALUES (
																'$field1',
																'$field2',
																$field_checkbox
														)");

	
    //Reload page
    unset($_POST);
    header('Location: '.$_SERVER['PHP_SELF']);
    die;
  }
}
?>
<form action="myfile.php" method="POST">
  <input type="hidden" name="action" value="add_to_database" />
  <input type="hidden" name="some_id" value="<?php echo "$some_id";?>" />

  <label>Field 1:</label><br />
  <input type="text" name="field1" value="<?php echo "$field1";?>" size="80"  /><br />

  <label>Field 2:</label><br />
  <input type="text" name="field2" value="<?php echo "$field2";?>" size="80"  /><br />
  
  <label>FieldCheckbox:</label><br />
  <input type="checkbox" name="field_checkbox" value="Yes" /><br />

  <input type="submit" value="Store" />
</form>
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *