Hello Guys,
I wrote this PHP script which validates the from and addes the data to the database.
I used CSS to display error messages and highlight the from if no data or incorrect data is entered.
Can someone please check and let me know if its correct and is there anything i should change??
Please let me know
Thanks
Karen G.
[php]
my php form<body>
<?php
// DATABASE CONNECTION
$user = "root";
$pass = 12345;
$database ="a_database";
$server ="localhost";
if( !mysql_connect($server, $user, $pass) || !mysql_select_db($database)){
die(mysql_error());
}
// FORM VALIDATION
if(isset($_POST['submit'])){
if(empty($_POST['food'])){
//echo"<p style='text-align:center; color:red;'>please enter food name</p>";
echo"<style type=\"text/css\">
.changeFood input{
border:1px solid red;
}
p.changeFood:after{
padding-left:10px;
color:red;
content:\"please enter food name\";
}
</style>";
}
if(empty($_POST['calories'])){
//echo"<p style='text-align:center; color:red;'>please enter calories</p>";
echo"<style type=\"text/css\">
.changeCal input{
border:1px solid red;
}
p.changeCal:after{
padding-left:10px;
color:red;
content:\"please enter calories. \";
}
</style>";
}else if(isset($_POST['calories']) && !ctype_digit($_POST['calories']) ){
//echo"<p style='text-align:center; color:red;'>CALORIES field must contain numbers only </p>";
echo"<style type=\"text/css\">
.changeCal2 input{
border:1px solid red;
}
p.changeCal2:after{
padding-left:10px;
color:red;
content:\"CALORIES field must contain numbers only\";
}
</style>";
}
if(empty($_POST['h_u'])){
//echo"<p style='text-align:center; color:red;'>please enter (H) if the food is healty and (U) if it is unhealthy</p>";
echo"<style type=\"text/css\">
.changeHeal input{
border:1px solid red;
}
p.changeHeal:after{
padding-left:10px;
color:red;
content:\"please enter (H) if the food is healty and (U) if it is unhealthy\";
}
</style>";
}
}
$displayForm = true; // SET DISPLAYFORM TO TRUE - TO HIDE THE FORM
// IF EVERYTHING OK THEN ADD DATA TO THE DATABASE AND SHOW THANK YOU MESSAGE
if( !empty($_POST['food']) && !empty($_POST['calories']) && !empty($_POST['h_u']) && ctype_digit($_POST['calories'])){
mysql_query("INSERT INTO food(food, calories, h_u)
VALUES('$_POST[food]', '$_POST[calories]', '$_POST[h_u]')")
or die(mysql_error());
echo"<p style='text-align:center; color:green;'>Thank you. Your data has been added</p>";
// HIDE THE FORM IF DATA HAS BEEN ADDED TO THE DATABASE
$displayForm = false;
}
if( $displayForm){
?>
<center><form action="" method="post">
<p class="changeFood">food:<input type="text" name="food" value="<?php echo @htmlspecialchars($_POST["food"]);?>"></p>
<p class="changeCal changeCal2">Calories:<input type="text" name="calories" value="<?php echo @htmlspecialchars($_POST["calories"]);?>"></p>
<p class="changeHeal">Healthy_H-U:<input type="text" name="h_u" value="<?php echo @htmlspecialchars($_POST["h_u"]); ?>"></p>
<input type="submit" name="submit" value="Add">
</form></center>
<?php
}
?>
</body>
[/php]