How to store data from user in php using wampserver? - php

I have a college assignment in which I have to design a website and I have to store details from the user. I did a google search and I have a found a script which works fine for my registration page So I copied that script for my index.php page and I have created a table contact in phpymadmin using wampserver and inserted 3 columns Username, Email, Message. But now when I'm trying to enter some details and clicking on submit button the page is getting refreshed and data is not getting stored in the database.
<form role="form" method="post" action="index.php">
<!-- Name -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your name" name="name">
</div>
</div>
<!-- E-Mail -->
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name="email">
</div>
</div>
</div>
<!-- Message Area -->
<div class="form-group">
<textarea class="form-control" name="message" placeholder="Write you message here..." style="height:232px;"></textarea>
</div>
<!-- Subtmit Button -->
<button type="submit" class="btn btn-send" value="register">
Send message
</button>
</form>
<?php
include("contact.php");//make connection here
if(isset($_POST['register']))
{
$Username=$_POST['name'];//here getting result from the post array after submitting the form.
$Email=$_POST['email'];//same
$Message=$_POST['message'];//same
if($Username=='')
{
//javascript use for input checking
echo"<script>alert('Please enter the name')</script>";
exit();//this use if first is not work then other will not show
}
if($Email=='')
{
echo"<script>alert('Please enter the email')</script>";
exit();
}
if($Message=='')
{
echo"<script>alert('Please enter the message')</script>";
exit();
}
//here query check weather if user already registered so can't register again.
$check_email_query="select * from contact WHERE Email='$Email'";
$run_query=mysqli_query($dbcon,$check_email_query);
if(mysqli_num_rows($run_query)>0)
{
echo "<script>alert('Email $user_email is already exist in our database, Please try another one!')</script>";
exit();
}
//insert the user into the database.
$insert_user="insert into contact (Username,Email,Message) VALUE ('$Username','$Email','$Message')";
if(mysqli_query($dbcon,$insert_user))
{
echo"<script>alert('Thank you for contacting us')</script>";
}
}
?>

1) Add name='register' in <button>. Because, you are using isset($_POST['register']) And, there is no need of value="register", as you have declared Send Message as value there in button.
<button type="submit" class="btn btn-send" name="register">
Send message
</button>
2) Change VALUE to VALUES in this query.
$insert_user="insert into contact (Username,Email,Message) VALUES ('$Username','$Email','$Message')";

Related

How do I use sweetalert2 inside a php condition in a different file?

I have a sample log in/log out module. It's inside a form that accesses a separate php file for verification and database access. I want to use sweetalert2 to display the success or denied modal. How can I do that?
HTML:
<div class="modal-body">
<div class="text-danger"><?php echo isset($_GET['error']) ? $_GET['error']: "" ?></div>
<form action="login.php" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" placeholder="Enter email" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password" required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="submit_btn btn btn-primary">Submit</button>
</div>
</form>
</div>
As you can see, it's accessing a separate php file. Don't worry about ^this modal, it can be closed. How do I replace this modal with another modal made of sweetalert2 when the php is in another file?
PHP: (login.php)
if (empty($email)) {
header("Location: index.php?error = You need to enter your email.");
} else if (empty($password)) {
header("Location: index.php?error = You need to enter your password.");
A sample of my php code. I know it's bad form to just...redirect like that, but the main problem here is how to pass that error into a sweetalert2. I've tried calling swwetalert2 inside the login.php file, but it doesn't work.

Login page using php,ajax,jquery

Hello i am trying to build login page.
There are two pages login.php and login2.php
login.php has a form which accepts email and password from the user which are sent to login2.php using $.post()
login2.php checks email and password in DB and a message is sent to login.php which is supposed to be displayed in having id="msg"
Problem is that message is printed but after that the page is refreshed and the message is gone
login.php
<form>
<input type="radio" name="role" value="tbl_staff_details" checked>Institute/Branch
<input type="radio" name="role" value="tbl_student_details">Student/Parent
</br></br>
<div id="msg" style="color: red"></div>
<div class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Email" id="mail">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" id="pwd">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
<label>
<input type="checkbox"> Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat" id="signin">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
<script>
$(function(){
$("#signin").click(function(){
var mail = $("#mail").val();
var pwd = $("#pwd").val();
var role = $("input[name='role']:checked").val();
$.post("login2.php",
{
mail: mail,
pwd: pwd,
role: role
},
function(data,status){
$("#msg").text(data);
});
});
});
</script>
login2.php
<?php
$email=$_POST['mail'];
$pwd=$_POST['pwd'];
$table=$_POST['role'];
include_once 'conf.php';
if ($table=="tbl_staff_details") {
$q="select * from ".$table." where email=".$email." and pwd=".$pwd;
}
else{
$q="select * from ".$table." where stud_email='".$email."' and stud_pwd='".$pwd."' or stud_email='".$email."' and parent_pwd='".$pwd."'";
}
$r=mysqli_query($con,$q);
$ro=mysqli_num_rows($r);
if ($ro>0) {
echo "Success";
//header('location:test.php');
}
else{
echo "Email or password is wrong";
}
?>
Make sure to take into account what the comments are saying about vulnerabilities like plain text passwords and sql injections. But it looks like the issue you are having is related to the fact that the button you click to submit the form is type='submit'
Because of this when you click the button the browser will try to make a new request to the page specified in your form or if not specified, the page you are currently on to submit your request.
There are two ways to get around this:
Change the button to type='button' since you are already handling the on click event with jquery you don't need to submit
use preventDefault(); to stop the submit event from happening

Thank you message after Complete a Form

I have a Bootstrap form and after complete the form I want remain in the same page and display a thank you message just below the submit button.
Here my HTML code
<div id="form">
<div class="row">
<div class="col-md-12"><h3>RESTA IN CONTATTO</h3>
<form id="form_members" role="form" data-toggle="validator" novalidate action="form-data.php" method="POST">
<div class="form-group">
<label for="firstname" class="control-label">Nome</label>
<input type="text" class="form-control" name="firstname" id="name" placeholder="Inserisci il Nome" required>
</div>
<div class="form-group">
<label for="lastname" class="control-label">Cognome</label>
<input type="text" class="form-control" name="lastname" id="lastname" placeholder="Inserisci il Cognome" required>
</div>
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Enter the Email" data-error="Inserire email valida" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" id="terms" required data-error="Devi essere d'accordo con i termini di condizione d'uso">Privacy
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="submit" id="submit" onclick="this.form.clear()" value="submitmessage">Registrati</button>
</div>
</form>
<div id="submitmessage"></div>
and Here my php Code
<?php
$link = mysqli_connect("","","") or die("failed to connect to server !!");
mysqli_select_db($link,"");
if(isset($_POST['submit']))
{
$errorMessage = "";
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
// Validation will be added here
if ($errorMessage != "" ) {
echo "<p class='message'>" .$errorMessage. "</p>" ;
}
else{
//Inserting record in table using INSERT query
$insqDbtb="INSERT INTO `test`.`members`
(`firstname`, `lastname`, `email`) VALUES ('$firstname', '$lastname', '$email')";
mysqli_query($link,$insqDbtb) or die(mysqli_error($link));
}
}
?>
First check if your insert actually happen by assigning result to a variable, ie:
$res=mysqli_query($link,$insqDbtb);
Now, below your form you can add the following php code and you can use this variable in an if statement to echo different things:
if($_POST && $res)
{/*this code is executed if form is submitted and insert worked*/
echo ' <div class="alert alert-success" role="alert">
Grazie per esserti registrato!
</div>';
}
elseif ($_POST && !$res)
{ /*you can write a different message if insert did not happen*/
echo '<div class="alert alert-danger" role="alert">
<strong>Oh no!</strong> Provaci ancora
</div>';
}
Note that this might only work if you use php to process the form and scripts are on the same page so you would also need to modify your form like this:
<form action="register.php" method="post" accept-charset="utf-8">
(where register.php stands in for the name of your file)
and the submit button like this:
<input type="submit" name="submit" value="Submit" id="submit_button" class="btn btn-primary" />
Then at the top of your page, after you have set the parameters for the connection you put the following statement:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
and you can put all the form validation here. What happens is the first time you go to the file it will be through a GET so nothing happens, after you submit the form you access the same file but with a POST so the submission is validated.
To submit the form and stay on the same page you have two possibilites:
A) As other people have suggested you use Ajax
B) The other possibility which has the same visible result for the user is that when you submit your form you go back to the same page, so the user will see the same page but different things will be displayed depending on weather he has already submitted the form or not
To achieve this second solution you can do the following:
1)In your head you establish the connection (the php you have is improvable but as a first attempt should do the job)
2) In your page you put your form with the following modification:
<form action="FILNAME.php" method="post" accept-charset="utf-8">
and
<input type="submit" name="submit" value="Submit" id="submit" class="btn btn-default" />
THis way when a user clicks the button the form is submitted to the same page.
3) Now you need to check if your page is beening accessed for the first time (ie thoruh a GET) or after the form has been submitted, so where you want your message to appear you put the following if statement:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
}
3) Within this bracket you put all your php to validate the form and after validation your insert command
$insqDbtb="INSERT INTO `test`.`members`(`firstname`, `lastname`, `email`) VALUES ('$firstname', '$lastname', '$email')";
$res = mysqli_query($link, $insqDbtb);
4) If the query created a new row you can write the thank you message:
if (mysqli_affected_rows($link) === 1) {echo '<div class="alert alert-success"><h3>Thanks!</h3><p>Thank you for registering! </p></div>';
If not you can write an alert instead
I learned this method from a book by Larry Ullman, you can find the scripts with examples for free
here

using php to login, when the user click the submit button it still directs the user to my connectivity.php

As the title states when the user clicks the submit button it will take the suer to a blank connectivity.php page. The problem is however it works perfectly if the user enters their username and password. If they leave it blank thats when i goes to the blank connectivity page. Im having problems throwing up an error message.
nav.php(nav bar)
<div id="Sign-In">
<form class="navbar-form navbar-right" method="POST" action="Login/connectivity.php">
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="user" side="40">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Password" name="pass" side="40">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" name="submit" value="Log-In">Log In</button>
</div>
</form>
</div>
nav.php cont
<?php
if ($_POST["submit"]) {
if(!$_POST["user"]) {
$error.="<br />Please enter your username";
}
if(!$_POST["pass"]) {
$error.="<br />Please enter your Password";
}
if($error){
$result ='<div class="alert alert-danger"><strong>There were error(s) in your form:</strong> '.$error.'</div>';
}
}
?>
I would like the div to pop up if its missing information. before it heads to connectivity.php
To better ask the question. I would like when the user presses to log-in button, the script at the top runs, IF the form is missing data the wont run UNTIL they add the missing information, THEN the will run.
Use
if(!isset($_POST['user']) and empty( $_POST['user']))
To check if form not empty.
You need client side validation to prevent redirecting to server add the word required at the end of input tag

PHP multi-step registration process

I am working on a registration system which comprises of 3 total steps.
Step 1 - user enters a username, system searches the database for the
username. IF the username is found, it checks the account status (ie:
no password created, complete but not verified, registered and
verified).
If user is not found, user is directed to Step 2.
If status = no password created, the user is directed to Step 3.
If status = complete but not verified / registered and verified, Display error message.
Step 2 - user enters personal details.
The page stores user inputs
Step 3 - user creates a password, the system connects to the database and INSERTs user info to the user table. A success message is
displayed.
I have managed to figure out and complete the coding for the first 2 steps, by displaying a new form when the previous form has been submitted.
Problem: However, I have just realised that I am unable to retrieve data from the previous form (ie: at step 3 I am unable to retrieve the Username from Step 1). I have tried using the 'header('location: ?user=$uname');' approach however this doest work because the URL gets reset when I submit the new form and I lose the username again. How do I create a proper multi-step form using ONLY PHP and how do I store the input values so I could use them at the last step. Below is my code:
<?php
include 'includes/session_info.php';
if(isset($_SESSION['user_id'])){
header('Location: index.php');
}
$errors = array();
if(empty($_POST['user_info']) === false){
require ('core/dbcon.php');
$usr_email = mysqli_real_escape_string($con, $_POST['email']);
$usr_joined = mysqli_real_escape_string($con, $_POST['joined']);
$usr_recruited = mysqli_real_escape_string($con, $_POST['recruited']);
if($usr_email){
//direct user to password form
}else{
$errors[] = 'Please complete all fields marked with a Red Asterisk.';
}
$form2 = $usr_email.'<br>'.$usr_joined.'<br>'.$usr_recruited;
}
if(empty($_POST['username_chck']) === false){
require ('core/dbcon.php');
$username = mysqli_real_escape_string($con, $_POST['uname']);
$rpt_uname = mysqli_real_escape_string($con, $_POST['r_uname']);
if($username && $rpt_uname){
if($username == $rpt_uname){
$query = mysqli_query($con, "SELECT status FROM users WHERE username = '$username'") or die(mysqli_error($con));
// Display registration form if Username is not found.
if(mysqli_num_rows($query) == 0){
$form1;
}
// Actions performed If username entered already exists in the database.
elseif(mysqli_num_rows($query) == 1){
$status = mysqli_fetch_assoc($query);
if($status['status'] == 0){
$errors[] = '<b>'.$username.'</b> is already registered and awaiting to be verified by our admins. Feel free to contact an Admin via the website or in-game to get verified.';
}elseif($status['status'] == 1){
//header("Location:?create_pwd&user=$username");
}elseif($status['status'] > 1){
$errors[] = '<b>'.$username.'</b> is already registered and verified by our Admins. Please log in to access you account.
If you have forgotten your password you can rest your password <a class="navbar-link error_link" id="intext-link" href="login.php?fp"><b>here</b></a>.';
}
}elseif(mysqli_num_rows($query) > 1){
$errors[] = 'An error has occurred. Looks like a there is more than one member with that username. Please contact the Administrator for assistance.';
}
}else{
$errors[] = 'Please ensure that the username entered in both fields match.';
}
}else{
$errors[] = 'Please complete all required fields.';
}
}
?>
<html>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<?php
if(empty($_POST['username_chck']) === false){
if(empty ($errors) === false){
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Username: </label><br>
<input type="text" name="uname" class="form-control" placeholder="Please enter your Runescape username." id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" placeholder="Please re-enter your Runescape username." required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
<?php
}else{ echo $reg_uname;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Email: </label>
<input type="email" name="email" class="form-control" id="Email" <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<div class="form-group">
<label for="Joined">Date Joined: </label><br>
<small class="notice">If you do not remember the exact date please select the first day of the month and year you joined (eg: 01/02/2001).</small><br>
<input type="date" name="joined" class="form-control" id="Joined" <?php if (isset($_POST['joined'])=== true){echo 'value="', strip_tags($_POST['joined']),'"';}?>>
</div>
<div class="form-group">
<label for="recruited">Recruited by: </label>
<select name="recruited" class="form-control" id="recruited">
<option value="" selected disabled>Select a Member</option>
<?php
require ('core/dbcon.php');
$usr_qry = mysqli_query($con, "SELECT user_id, username FROM users")or die(mysqli_error($con));
while($usr = mysqli_fetch_array($usr_qry)){
echo '<option value="'.$usr['user_id'].'">'.$usr['username'].'</option>';
}
?>
</select>
</div>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
</form>
<?php
}
}elseif(empty($_POST['user_info']) === false){
if(empty ($errors) === false){
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Email: </label>
<input type="email" name="email" class="form-control" id="Email" <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<div class="form-group">
<label for="Joined">Date Joined: </label><br>
<small class="notice">If you do not remember the exact date please select the first day of the month and year you joined (eg: 01/02/2001).</small><br>
<input type="date" name="joined" class="form-control" id="Joined" <?php if (isset($_POST['joined'])=== true){echo 'value="', strip_tags($_POST['joined']),'"';}?>>
</div>
<div class="form-group">
<label for="recruited">Recruited by: </label>
<select name="recruited" class="form-control" id="recruited">
<option value="" selected disabled>Select a Member</option>
<?php
require ('core/dbcon.php');
$usr_qry = mysqli_query($con, "SELECT user_id, username FROM users")or die(mysqli_error($con));
while($usr = mysqli_fetch_array($usr_qry)){
echo '<option value="'.$usr['user_id'].'">'.$usr['username'].'</option>';
}
?>
</select>
</div>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
</form>
<?php
}else
echo $reg_uname.'<br>'. $reg_email.'<br>'.$reg_joined.'<br>'.$reg_recruited.'<br>';
}else{
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Username: </label><br>
<input type="text" name="uname" class="form-control" placeholder="Please enter your Runescape username." id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname"><span class="glyphicon glyphicon-asterisk required" aria-hidden="true"></span> Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" placeholder="Please re-enter your Runescape username." required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
<?php
}
?>
</div>
</div>
</html>
Ps. I have looked into creating a session which gets destroyed when the user navigates away from the page Destroy PHP session on page leaving. However I find that it's not very user friendly as it doesn't work properly if the user has multiple tabs open. I understand that I need to implement a javascript function to make it work properly. I do not know how to code in javascript and would really appreciate your assistance on making a better multi-step registration process.
As mentioned above, store the POST data from each step in the session variable.
// Step 1 submit
$_SESSION['steps'][1] = $_POST;
// Step 2 submit
$_SESSION['steps'][2] = $_POST;
// Step 3 submit
$_SESSION['steps'][3] = $_POST;
You can then use something like currentStep in the session to determine where they last were.
$currentStep = $_POST['step'];
And compare to what data you need available, or just use it directly from the array.
I opted to follow the 'hidden variable' method where I store the values form the previous form in hidden inputs of the current form. Thus enabling me to pass the values on to the next form. A sort of snowball effect, if you will. Below is an example:
Form 1
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Uname">Username: </label><br>
<input type="text" name="uname" class="form-control" id="Uname" required>
</div>
<div class="form-group">
<label for="repeat_Uname">Repeat Username: </label><br>
<input type="text" name="r_uname" class="form-control" id="repeat_Uname" required>
</div>
<input type="submit" name="username_chck" class="btn btn-default" value ="Next">
</form>
Form 2
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="Email">Email: </label>
<input type="email" name="email" class="form-control" id="Email" required <?php if (isset($_POST['email'])=== true){echo 'value="', strip_tags($_POST['email']),'"';}?>>
</div>
<input type="hidden" name="username" <?php if (isset($_POST['username'])=== true){echo 'value="', strip_tags($_POST['username']),'"';}else{echo "value=\"$username\"";}?>>
<input type="submit" name="user_info" class="btn btn-default" value ="Next">
Explanation
Below is a skeleton of my code which should help you understand how I have displayed the forms
if(empty($_POST['form1'])=== false){
$username = mysqli_real_escape_string($con, $_POST['username']);
// display form 2
}elseif(empty($_POST['form2'])=== false){
//display form 3
}
Note the hidden input type before the submit button in the second form.
While I have opted to include the if statements within the tags for the sake of this example, you could alternatively choose to process the forms at the top of your page (before the tag).

Categories