This is an effort to create a PHP page to add data to a table. I am getting a parsing error on line 79 so I have been fiddling with it for a while:
Parse error: syntax error, unexpected T_STRING in /home/sharah19/dev.rahmaninet.org/new.php on line 79
Also I have another question: Whats the easiest way to make this page secure? So only users who are authenticated through the login page can add a record?
The contents of new.php:
<?php
/*
NEW.PHP
Allows user to create a new entry in the database
*/
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($first, $last,$email, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Add a New Record</title>
<link href="rahmani.css" rel="stylesheet">
</head>
<body>
<div id="main">
<h1>RahmaniNET CRM System</h1>
<?php include("header.php"); ?>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name: *</strong> <input type="text" name="first_name" value="<?php echo $first_name; ?>" /><br/>
<strong>Last Name: *</strong> <input type="text" name="last_name" value="<?php echo $last_name; ?>" /><br/>
<strong>email: *</strong> <input type="text" name="email" value="<?php echo $email; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$first_name = mysql_real_escape_string(htmlspecialchars($_POST['first_name']));
$last_name = mysql_real_escape_string(htmlspecialchars($_POST['last_name']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
// check to make sure both fields are entered
if ($first_name == '' || $last_name == ''|| $email == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($first_name, $last_name, $email, $error);
}
else
{
// save the data to the database
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email' )
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('$first', '$last','$email', $error);
}
?>
The error comes from the lack of a closing quote on your MySQL query:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email') or die(mysql_error());
It should be:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email'") or die(mysql_error());
Also you ask:
Also I have another question: Whats the easiest way to make this page
secure? So only users who are authenticated through the login page can
add a record?
If you are using Apache then you should you use Apache AuthType Basic. More details are here. Details under “Getting it working.”
You are missing a double quote in your sql string:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email' )
Related
If for example a username isn't filled in the user is given an error stating so, but after pressing submit they're thrown to another page with the error.
How would I go around keeping the error on the same page as the registration form and keeping all the text entered by the user after submit?
Registration PHP:
<?php
require 'db_connect.php';
$count = 0;
if (isset($_POST['username']))
{
$username = $_POST['username'];
if (!empty($username))
{
$count++;
}
else
{
echo 'Please enter a username';
echo "<br>";
}
}
if (isset($_POST['email']))
{
$email = $_POST['email'];
if (!empty($email))
{
$count++;
}
else
{
echo 'Please enter an email';
echo "<br>";
}
}
if (isset($_POST['password']))
{
$password = $_POST['password'];
if (!empty($password))
{
$count++;
}
else
{
echo 'Please enter a password';
echo "<br>";
}
}
if(strlen($username) > 25)
header('Location: registration.php');
$hashword = password_hash($password,PASSWORD_DEFAULT);
if($count == 3 )
{
$query = "INSERT INTO member ( username, password, email)
VALUES ( '$username', '$hashword', '$email');";
header('Location: login.html');
}
else {
echo '<b>You will be redirected shortly</b>';
echo "<br>";
echo '<b>Please enter ALL details correctly</b>';
header( "refresh:5;url=registration.php" );
}
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
?>
Registration Form:
<!doctype html>
<html lang="en">
<head>
<title>Gumby template file</title>
<meta charset="utf-8" />
<script data-touch="gumby/js/libs" src="gumby/js/libs/gumby.min.js"></script>
<script src="gumby/js/libs/jquery-2.0.2.min.js"></script>
<link rel="stylesheet" href="gumby/css/gumby.css">
<script src="gumby/js/libs/modernizr-2.6.2.min.js"></script>
<link rel="stylesheet" href="forumhomepage_style.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
<body>
<form name="register" action="register.php" method="post">
<tr>
<td>Username: </td>
<td><input type="text" name="username" maxlength="25" /></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
</form>
</body>
</html>
It depends on at what level do you want to do this.
Validating that the different data is not empty and has information that makes sense (like the password is at least 7 chars long) can be done via javascript before sending the form data, this way you can stop the form to be sent. You can use jQuery Plugin Validator to help you do this.
But other validations like the insert has failed only can be done at server side, if you need also not to redirect in this case then you have to use ajax to load the data and then refresh the website info without reloading it.
I prefer to only do an initial check with javascript and send the user to the results page. But I also keep the validations as this one of the password length in the php because, even though now a days it's really strange, a user can disable javascript and I don't wana have surprises when checking the database values. But, another example, if you have lots of users you could check that the user does not exist to warn the user at the very first moment before the form is sent and this can only be done performing an ajax call.
You should know how to do both things and decide depending on what you want to do on your projects.
In your case, I would leave the php validations as they are now and check the same (non empty values) in javascript on the form submit event calling event.preventDefault() if an error has been detected.
$('form[name="register"]').submit(function( event ) {
if ($('input[name="username"]').is(":empty")) {
// append a "Username can not be empty message somewhere on your page
event.preventDefault();
}
// I let you finish the jquery code...
});
This example uses jQuery lib. but you can do it without it with just javascript if you want.
There are several ways to do this. The first step is using the required attribute in your input elements:
<input type="text" name="username" required>
This will force the user to at least put something inside the input element. Then there's Javascript or jQuery for client side validation. You can create a custom event handler to catch the form submit and validate the input like so:
document.getElementById("your_form_id_here").addEventListener("submit", function(e){
// Your Javascript validation code here, for example:
var x = document.forms["your_form_id_here"]["username"].value;
if (x == "") {
alert("Username must be filled out");
e.preventDefault();
}
});
You can also put the form handler on the same file as the form and display the errors / values in case something goes wrong. For example:
<?php
if(!empty($_POST['submit'])){
$error = false;
if($_POST['username'] === ''){
$usernameEmpty = 'The username was empty. Please enter a username!';
$error = true;
}
if(!$error){
// No errors found so proceed with the registration
}
}
?>
<form id="myForm" method="post" action="" accept-charset="utf-8">
<?php if(!empty($usernameEmpty)){ echo $usernameEmpty . '<br/>'; } ?>
Username: <input type="text" name="username" value="<?php if(!empty($_POST['username'])){ echo $_POST['username']; } ?>"/>
<input type="submit" name="submit" value="Register"/>
</form>
Lastly there's of course Ajax which will allow you to send the form towards PHP without reloading your page. You could have PHP send the errors back and use Javascript to show the errors inside the DOM.
without ajax you will need ro lead your page with some conditional logic. This will look and see if any fields are filled in and fill them in again, along with setting any error messages to return to the user.
something like:
<?php
//example fields
$username = '';
$field2 = '';
$field3 = '';
if(isset($errorToShow)){
// echo your error message here
}
if($_POST["submit"]){
foreach($_POST as $k=>$v){
$$k = $v;
}
}
// your form can be here.
of course there are other considerations and ajax is a better solution, but this type of thing can work just fine.
You may use ajax
Or if you don't know ajax
You can put all your code in one page and call $_POST indexes into the value of every input.
for ex.
<input type="text" name="username" maxlength="25" value="<?=$_POST['usename'];?>"/>
Or you may use "PHP $_SESSION"
Just store $_POST into $_SESSION
then call it from the html page
for ex.
<input type="text" name="username" maxlength="25" value="<?=$_SESSION['usename'];?>"/>
And the same idea for errors.
I had been researching a while and even got a hold of my hosting company for help but I have run into a problem with my PHP code and my database through my website. While the code that I have does hash the password that I enter, when I attempt to use the regular word password it comes up as incorrect. But if I copy and paste the hashed password, it works.
<?php
/* NEW.PHP
Allows user to create a new entry in the database
*/
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($email, $pass, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New User</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '') {
echo '<div style="padding:4px; border:1px soluser_id red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>Update User Info <br><br><br><br><br>Email: *</strong>
<input type="text" name="email" value="<?php echo $email; ?>" /><br/>
<strong>Password: *</strong> <input type="password" name="pass" value="<?php echo $pass; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit"> <br><br>Back to home?</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
// get form data, making sure it is valuser_id
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$pass = mysql_real_escape_string(htmlspecialchars($_POST['pass']));
// check to make sure both fields are entered
if ($email == '' || $pass == '') {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($email, $pass, $error);
} else {
// save the data to the database
mysql_query("INSERT users SET email='$email', pass=MD5('$pass')")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the form hasn't been submitted, display the form
renderForm('','','');
}
?>
As you can see it does hash it when I enter it into the database, but when I try to use the password the way it was originally spelled, it tells me it's the wrong one.
I would do the MD5 hashing on the PHP side. Print it before it goes into the database and try to compare it with the input given on the login form.
Also the htmlspecialchars is not needed in this case. Since your escaping is fine. If it would contain weird chars, it would match them against the database.
Also make sure your encoding type is set on both pages and make sure they're the same.
Without seeing your SELECT query in the login form I'd ask if you're MD5 hashing it when you select it as well?
mysql_query("SELECT * FROM users WHERE email='$email' AND pass=MD5('$pass')")
or die(mysql_error());
However, I agree that you shouldn't be using MD5 for password hashing. Check out http://php.net/manual/en/function.password-hash.php
I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php
My problem: even if form fields are empty, the variables are still being inserted into the database.
I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.
I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.
I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist
Login.php:
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<?php
session_start();
$passworderr='';
if(isset($_SESSION["passworderr"])) {
$passworderr=$_SESSION["passworderr"];
}
?>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Form.php:
<?php
session_start();
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if(!isset($_POST["username"])) {
$_SESSION["usernameerr"]="UserName is required";
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if(!isset($_POST["password"])) {
$_SESSION["passworderr"]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if(!isset($_POST["phone"])) {
$_SESSION["phoneerr"]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if(!isset($_POST["mailid"])) {
$_SESSION["mailiderr"]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if(!isset($_POST["city"])) {
$_SESSION["cityerr"]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty.
One way to do that is to use the strlen function.
So an example for you is:
if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {
NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.
You may want to consider using a helper function to do the determination. Basically something like this:
function DoesPostFormFieldHaveValue($formFieldName) {
return(
isset($_POST[$formFieldName])
&& strlen($_POST[$formFieldName]) > 0
);
}
First of all, session_start should always be the first line of the php page you need to use sessions on.
Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.
Here's your updated form :-
<?php
session_start();
if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
{
echo "Please fix the following errors";
foreach($_SESSION['errors'] as $error) //loop through the array
{
echo $error;
}
}
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Backend processing file :-
<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if((!isset($_POST["username"])) || (empty($_POST['username']))) {
$_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if((!isset($_POST["password"])) || (empty($_POST['password']))) {
$_SESSION["errors"][]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
$_SESSION["errors"][]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
$_SESSION["errors"][]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if((!isset($_POST["city"])) || (empty($_POST['city']))) {
$_SESSION["errors"][]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.
Now the solution is to change all your isset() to empty() and that should solve your problem!
[Note] There is no need to use both isset() and empty() like this:
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
because empty() is doing everything that isset() does.
check like this:
if(!isset($_POST["username"]) && $_POST["username"]!="")
Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank.
To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).
Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.
Instead of doing that:
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
Do something like this:
if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))
Should work.
Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.
Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of:
$_SESSION['cityerr']
to:
$_SESSION['errors']['cityerr']
So afterwards, you can clean the specific form error session in one command, like that:
unset($_SESSION['errors']);
Hope it helped ;)
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']
}else
{
unset($_POST['field_name'])
}
I'm new to PHP. I want to display a message that the database is updated after each time I redirect it after entering the data.
$sql = "INSERT INTO incoming (recipt, userid, username, money)
VALUES ('$recipt', '$userid', '$username', '$money')";
if ($conn->query($sql) === TRUE) {
echo "<script>window.open('incoming2.php','_self')</script>";
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
2 methods
1-you can redirect to any page adding message in get variable and check at that page if that variable is set then display it as message
//redirect to index.php with msg as
header('location:index.php?msg=2 records updated');
//at index page where you want to display message
if(isset($_GET['msg']) && !empty($_GET['msg'])){
echo '<p class="myMsg">'.$_GET['msg'].'</p>'
}
2- second method is to save the message to session variable and access it at page but you will have to unset that variable as below
//sending message assuming session_start() is written at to of all pages
$_SESSION['msg']="2 records updated or what ever your message is";
//where you want to display message
if(isset($_SESSION['msg']) && !empty($_SESSION['msg'])){
echo '<p class="myMsg">'.$_SESSION['msg'].'</p>'
unset($_SESSION['msg']);
}
Pass the message to your url:
echo "<script>window.open('incoming2.php?message=New+record+created+successfully','_self')</script>";
Then you can get the message in incoming2.php:
echo urldecode($_GET['message']);
Be careful: sanatize your input!
Use header("Location: incoming2.php"); instead of echoing JS.
Also, check your SQL statement for SQL injection vulnerabilities.
If you are posting the data on the same page you could do the following:
<?php
if(isset($_REQUEST["submit"])){
// mySQL code here
// return either success or failed
$confirmation="success";
}
?>
<html>
<head>
<title>Feedback</title>
</head>
<body>
<div>
<?php
if(isset($confirmation)){
echo $confirmation;
}
?>
</div>
<form method="post" action="">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" Value="Submit">
</form>
</body>
</html>
If you are sending the data to a separate page:
On the receiving page:
<?php
// mySQL code here
// return either success or failed
//redirect to index.php with confirmation as true or false
header('location:index.php?confirmation=success');
?>
and on the page that you Sent the data from:
<html>
<head>
<title>Feedback</title>
</head>
<body>
<div>
<?php
//at index page where you want to display message
if(isset($_GET['confirmation']) && !empty($_GET['confirmation'])){
echo $_GET['confirmation'];
}
?>
</div>
<form method="post" action="uploaddata.php">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" Value="Submit">
</form>
</body>
</html>
You can then use CSS3 animations to fade the message in and out for a better user experience :-)
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style1.css">
</head>
<body>
<?php
$name;
$college;
if(empty($_POST["name"])){
$nameerr="NAME IS REQUIRED";
}
else{
$name=$_POST["name"];
}
$course=$_POST["course"];
if(empty($_POST["college"])){
$collegeerr="NAME OF COLLEGE IS REQUIRED";
}else{
$college=$_POST["college"];
}
$email=$_POST["email"];
$abc=mysqli_connect('localhost','root','','generalinfo') or die('ERROR:COULD NOT CONNECT TO DATABASE');
$query="INSERT INTO studentinfo VALUES ('$name','$course','$college','$email')";
$final=mysqli_query($abc,$query) or die('ERROR ENTERING THE DATA IN DATABASE');
mysqli_close($abc);
echo'THANKYOU FOR SUBMITTING THE FORM';
?>
<div id="b">
<form action="" method="post">
<label for="name"><div id="a">name</div></label>
<input type="text" name="name"></br>
<div id="c"><?php echo $nameerr; ?></div>
<label for="course"><div id="a">course</div></label>
<input type="text" name="course"></br>
<label for="email"><div id="a">email</div></label>
<input type="text" name="email"></br>
<label for="college"><div id="a">college</div></label>
<input type="text" name="college"></br>
<div id="d"><?php echo $collegeerr; ?></div>
<input type="submit" value="submit" name="sub"></br>
</form>
</div>
</body>
</html>
After i press the submit button nothing happens..no error message comes up if i don't fill out the name or college field..also the filled the out information is not recieved in the database ...any kind of help will be appreciated ..thanks in advance
you should add an action
<form action="form.php" method="post">
And then include the form.php in you website's folder.
i think the issue your having rather than the action="" if it is all on the same page is that your query isn't saying where you want each value to go
$query="INSERT INTO studentinfo (name, course, college, email) VALUES ('$name','$course','$college','$email')";
try changing your query to that but make sure the field names are correct i just guessed using your variables
You should first check that the $_POST is empty or not.Then you should save the data.So, use thid code:
<?php
$collegeerr = $nameerr = '';
if(isset($_POST) && !empty($_POST)) {
$name = '';
$college = '';
if(empty($_POST["name"])){
$nameerr="NAME IS REQUIRED";
}
else{
$name=$_POST["name"];
}
$course=$_POST["course"];
if(empty($_POST["college"])){
$collegeerr="NAME OF COLLEGE IS REQUIRED";
}else{
$college=$_POST["college"];
}
$email=$_POST["email"];
$abc=mysqli_connect('localhost','root','','generalinfo') or die('ERROR:COULD NOT CONNECT TO DATABASE');
$query="INSERT INTO studentinfo(name, course, college, email) VALUES ('$name','$course','$college','$email')";
$final=mysqli_query($abc,$query) or die('ERROR ENTERING THE DATA IN DATABASE');
mysqli_close($abc);
echo'THANKYOU FOR SUBMITTING THE FORM';
}
?>
There are lot of issues with this code.
you can do the following things to get it resolved
1. Wrap the post specific code inside a condition
You are executing the post handling code block even when the page is not posted. the code for handling post action has to be wrapped under an if condition which checks if the POST array is empy or not
2. Show the error variables only when they are set
Error vraibales used in side the form like $nameerr and $collegeerr are not set when the page is not posted. So you have to show them only when they are set. wrap them under a if(isset()) condition.
3. Remove unwanted lines which serve no purpose
As barmer says in the comments, lines like $name;$college; are of no use. They doesnt serve the purpose of variable declarations. You can remove them.
4. Turn error_reporting on
You are not seeing these errors because you might have turned your error reporting off in php.ini. Its better to turn it on as it helps a lot in debugging the code. You can do this by going to php.ini and setting display_errors property on.
code
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style1.css">
</head>
<body>
<?php
if(!empty($_POST)) {
if(empty($_POST["name"])){
$nameerr="NAME IS REQUIRED";
}
else{
$name=$_POST["name"];
}
$course=$_POST["course"];
if(empty($_POST["college"])){
$collegeerr="NAME OF COLLEGE IS REQUIRED";
}else{
$college=$_POST["college"];
}
if(!isset($nameerr) && !isset($collegeerr)){
$email=$_POST["email"];
$abc=mysqli_connect('localhost','root','','test') or die('ERROR:COULD NOT CONNECT TO DATABASE');
$query="INSERT INTO studentinfo VALUES ('$name','$course','$college','$email')";
$final=mysqli_query($abc,$query) or die('ERROR ENTERING THE DATA IN DATABASE');
mysqli_close($abc);
echo 'THANKYOU FOR SUBMITTING THE FORM';
}
}
?>
<div id="b">
<form action="" method="post">
<label for="name"><div id="a">name</div></label>
<input type="text" name="name"></br>
<div id="c"><?php if(isset($nameerr)) echo $nameerr; ?></div>
<label for="course"><div id="a">course</div></label>
<input type="text" name="course"></br>
<label for="email"><div id="a">email</div></label>
<input type="text" name="email"></br>
<label for="college"><div id="a">college</div></label>
<input type="text" name="college"></br>
<div id="d"><?php if(isset($collegeerr)) echo $collegeerr; ?></div>
<input type="submit" value="submit" name="sub"></br>
</form>
</div>
</body>
</html>