Jump to content

Add record to a database


bscyb

Recommended Posts

Hello i have this PHP script with that via a form i can add a new record to a mysql database from my site

 

<?php

$con=mysql_connect("localhost","developer","javalab");
mysql_query("SET NAMES UTF8");
if(!$con)
{
   die('Δεν έγινε η σύνδεση με την βάση δεδομένων'.mysql_error());
}

mysql_select_db("cycladestravel", $con);
$tID = $_POST["tID"];
$tDestination = $_POST["tDestination"];
$tDestination = mysql_real_escape_string($tDestination);
$tDescription = $_POST["tDescription"];
$tDescription = mysql_real_escape_string($tDescription);
$tPrice = $_POST["tPrice"];
$sql="INSERT INTO travels(travel_id,travel_destination,travel_description,travel_price) VALUES
('$tID','$tDestination','$tDescription','$tPrice')";
if (!mysql_query($sql, $con))
{
   die('Σφάλμα: ' . mysql_error());
}

echo " 1 εγγραφή καταχωρήθηκε ";

mysql_close($con)

 

it works  good

but even if i put for example only the travel_id it adds the record to the database with the other columns values empty

i want that when i don't put all the columns i get an error for example when i not put travel_price it will give me an error -----> you don't put all the fields

 

i hope you understand what i write

Link to comment
Share on other sites

you will need to add some validation to check if the user has filled out all of the required fields.. something like this should work.

<?php

$con=mysql_connect("localhost","developer","javalab");
mysql_query("SET NAMES UTF8");
if(!$con)
{
   die('&#916;&#949;&#957; &#941;&#947;&#953;&#957;&#949; &#951; &#963;&#973;&#957;&#948;&#949;&#963;&#951; &#956;&#949; &#964;&#951;&#957; &#946;&#940;&#963;&#951; &#948;&#949;&#948;&#959;&#956;&#941;&#957;&#969;&#957;'.mysql_error());
}

mysql_select_db("cycladestravel", $con);
$tID = $_POST["tID"];
$tDestination = $_POST["tDestination"];
$tDestination = mysql_real_escape_string($tDestination);
$tDescription = $_POST["tDescription"];
$tDescription = mysql_real_escape_string($tDescription);
$tPrice = $_POST["tPrice"];

if(empty($tid) || empty($tDestination) || empty($tDescription) || empty($tPrice))
{
echo "Please fill out all of the required fields.";
exit();
} else
{
$sql="INSERT INTO travels(travel_id,travel_destination,travel_description,travel_price) VALUES
('$tID','$tDestination','$tDescription','$tPrice')";
$result = mysql_query($sql) or die(mysql_error());
}

echo " 1 &#949;&#947;&#947;&#961;&#945;&#966;&#942; &#954;&#945;&#964;&#945;&#967;&#969;&#961;&#942;&#952;&#951;&#954;&#949; ";

mysql_close($con)

Link to comment
Share on other sites

yes before i press topic solved i wanna ask something more

when i get the  Please fill out all of the required fields i wanna that it has a button with that i can return to the add page

 

i put this here:

if(empty($tID) || empty($tDestination) || empty($tDescription) || empty($tPrice))
{
echo "Please fill out all of the required fields";
exit();
?>
<br />
<input type="button" onclick="window.location='add.php'" value="return" 
title="return to add page" />

 

but it doesn't work

Link to comment
Share on other sites

Using exit() is a horrible way to present validation errors to a user. It's like slamming the door in your customer's face because they made a mistake, and it drives people away. You should validate each field individually and store any validation errors in an array, then check whether the array is empty. If it is empty, execute the database insert, or email, or whatever you need to do. If it's not empty, echo the errors, along with the presenting the form with the values the user entered already populated so the user can simply make the necessary corrections and resubmit the form.

 

Below is a rather basic example of the process, including using some CSS to highlight individual fields that have errors. I'm not saying to just copy it and use it as is, but look it over and see what it does so you have a better idea of how to handle errors in a manner that is effective and as user-friendly as possible.

 

<?php
if( isset($_POST['submitted']) && $_POST['submitted'] == 'yes' ) { //check for hidden field value to indicate form has been submitted
$errors = array(); // initialize an array to hold validation errors
$_POST = array_map('trim', $_POST); // trim all $_POST array values

if( !empty($_POST['name']) ) { // validate the name field
	if( !ctype_alpha($_POST['name']) ) {
		$errors['name'][] = 'Name must be alphabetic characters only.'; // if name has non alpha chars, store error
	}
	if( strlen($_POST['name']) < 3 || strlen($_POST['name'] > 20) ) {
		$errors['name'][] = 'Name must be from 3 to 20 characters.'; // if name has too many/few chars, store error
	}
} else {
	$errors['name'][] = 'Name is a required field.'; // if name is empty, store error
}

if( !empty($_POST['number']) ) { // same validations as in name, above.
	if( !ctype_digit($_POST['number']) ) {
		$errors['number'][] = 'Number must be numeric.';
	}
	if( strlen($_POST['number']) < 5 || strlen($_POST['number']) > 10 )  {
		$error = 'Number must be from 3 to 20 digits. It is currently ' . strlen($_POST['number']) . ' digit';
		$error .= strlen($_POST['number']) == 1 ? '.' : 's.';
		$errors['number'][] = $error;
	}
} else {
	$errors['number'][] = 'Number is a required field.';
}
if( !empty($errors) ) {  // if the $errors array is not empty, display the errors to allow the user to correct them and resubmit the form
	$echo = array();
	foreach( $errors as $v ) {
		if( is_array($v) ) {
			$echo[] = implode('<br>', $v );
		} else {
			$echo[] = $v;
		}
	}
	$err_echo ="<font color=\"red\">The following errors were detected:<br>";
	$err_echo .= implode("<br>\n", $echo);
	$err_echo .= '</font>';
}
}
if( (isset($_POST['submitted']) && !empty($errors)) || !isset($_POST['submitted']) ) {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css" media="screen">
body {
font-family: helvetica, arial, sans-serif;
font-size: 0.85em;
line-height: 1.25em;
letter-spacing: -0.5px;
}
input {
border: 1px solid #336699;
padding: 0.1em;
margin: 5px;
color: #113366;
}
input.error {
background-color: #F2BDCA;
color: #850310;
border: 1px solid red;
}
input.good {
background-color: #D3F5D3;
border: 1px solid #156B15;
color: #156B15;
}
input.submit {
background-color: #CCCCCC;
border: 1px solid #888888;	color: #333333;
padding: 2px;
margin: 0;
font: 0.9em helvetica, arial sans-serif;
}
</style>
<title> Work In Progress</title>
</head>
<body>
<?php
echo !empty($err_echo) ? $err_echo : '';
?>
<form method="post" action="">
Name (3-20 letters):
<input type="text"
class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['name']) ? 'error' : 'good'; } ?>"
name="name"
value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
<br>
Number (5-10 numbers):
<input type="text"
class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['number']) ? 'error' : 'good'; } ?>"
name="number" value="<?php echo isset($_POST['number']) ? $_POST['number'] : ''; ?>">
<br>
<input type="hidden" name="submitted" value="yes">
<input class="submit" type="submit" name="submit" value="
<?php echo !empty($errors) ? 'Re-Submit' : 'Submit'; ?>
">
</form>
<?php
} else {
// Form was submitted, and validated with no errors. OK to run db insert, display success message, etc.
echo "Successful submission!";
}
?>
</body>
</html>

Link to comment
Share on other sites

Using exit() is a horrible way to present validation errors to a user. It's like slamming the door in your customer's face because they made a mistake, and it drives people away. You should validate each field individually and store any validation errors in an array, then check whether the array is empty. If it is empty, execute the database insert, or email, or whatever you need to do. If it's not empty, echo the errors, along with the presenting the form with the values the user entered already populated so the user can simply make the necessary corrections and resubmit the form.

 

Below is a rather basic example of the process, including using some CSS to highlight individual fields that have errors. I'm not saying to just copy it and use it as is, but look it over and see what it does so you have a better idea of how to handle errors in a manner that is effective and as user-friendly as possible.

 

<?php
if( isset($_POST['submitted']) && $_POST['submitted'] == 'yes' ) { //check for hidden field value to indicate form has been submitted
$errors = array(); // initialize an array to hold validation errors
$_POST = array_map('trim', $_POST); // trim all $_POST array values

if( !empty($_POST['name']) ) { // validate the name field
	if( !ctype_alpha($_POST['name']) ) {
		$errors['name'][] = 'Name must be alphabetic characters only.'; // if name has non alpha chars, store error
	}
	if( strlen($_POST['name']) < 3 || strlen($_POST['name'] > 20) ) {
		$errors['name'][] = 'Name must be from 3 to 20 characters.'; // if name has too many/few chars, store error
	}
} else {
	$errors['name'][] = 'Name is a required field.'; // if name is empty, store error
}

if( !empty($_POST['number']) ) { // same validations as in name, above.
	if( !ctype_digit($_POST['number']) ) {
		$errors['number'][] = 'Number must be numeric.';
	}
	if( strlen($_POST['number']) < 5 || strlen($_POST['number']) > 10 )  {
		$error = 'Number must be from 3 to 20 digits. It is currently ' . strlen($_POST['number']) . ' digit';
		$error .= strlen($_POST['number']) == 1 ? '.' : 's.';
		$errors['number'][] = $error;
	}
} else {
	$errors['number'][] = 'Number is a required field.';
}
if( !empty($errors) ) {  // if the $errors array is not empty, display the errors to allow the user to correct them and resubmit the form
	$echo = array();
	foreach( $errors as $v ) {
		if( is_array($v) ) {
			$echo[] = implode('<br>', $v );
		} else {
			$echo[] = $v;
		}
	}
	$err_echo ="<font color=\"red\">The following errors were detected:<br>";
	$err_echo .= implode("<br>\n", $echo);
	$err_echo .= '</font>';
}
}
if( (isset($_POST['submitted']) && !empty($errors)) || !isset($_POST['submitted']) ) {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css" media="screen">
body {
font-family: helvetica, arial, sans-serif;
font-size: 0.85em;
line-height: 1.25em;
letter-spacing: -0.5px;
}
input {
border: 1px solid #336699;
padding: 0.1em;
margin: 5px;
color: #113366;
}
input.error {
background-color: #F2BDCA;
color: #850310;
border: 1px solid red;
}
input.good {
background-color: #D3F5D3;
border: 1px solid #156B15;
color: #156B15;
}
input.submit {
background-color: #CCCCCC;
border: 1px solid #888888;	color: #333333;
padding: 2px;
margin: 0;
font: 0.9em helvetica, arial sans-serif;
}
</style>
<title> Work In Progress</title>
</head>
<body>
<?php
echo !empty($err_echo) ? $err_echo : '';
?>
<form method="post" action="">
Name (3-20 letters):
<input type="text"
class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['name']) ? 'error' : 'good'; } ?>"
name="name"
value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
<br>
Number (5-10 numbers):
<input type="text"
class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['number']) ? 'error' : 'good'; } ?>"
name="number" value="<?php echo isset($_POST['number']) ? $_POST['number'] : ''; ?>">
<br>
<input type="hidden" name="submitted" value="yes">
<input class="submit" type="submit" name="submit" value="
<?php echo !empty($errors) ? 'Re-Submit' : 'Submit'; ?>
">
</form>
<?php
} else {
// Form was submitted, and validated with no errors. OK to run db insert, display success message, etc.
echo "Successful submission!";
}
?>
</body>
</html>

now that i look over my quick code i provided. you are right in that it will shut the door in the user face and not allow them to even correct the input. also, it is absolutely better to validate each input separately. I simply through something together quick without thinking properly. thanks for correcting my errors pikachu. bscyb, try to incorporate the code that pikachu listed and post your results please.

Link to comment
Share on other sites

yes i now that javascript is not good for validation but the site i create is just a exercise for my university

so its not a problem to use js for validation and because im now more that 10 hours on pc and try to finish

this site im to tired to make the validation with PHP maybe i will also leave as the 1st you gave me fugix

with the exit()

Link to comment
Share on other sites

yes i now that javascript is not good for validation but the site i create is just a exercise for my university

so its not a problem to use js for validation and because im now more that 10 hours on pc and try to finish

this site im to tired to make the validation with PHP maybe i will also leave as the 1st you gave me fugix

with the exit()

very well, since its not for an actual site. just as long as you are informed i am satisfied

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.