I’m trying to make a form that will check if the NRIC that is keyed exists in the database before it will insert the value into the database. However, I can’t seem to make it warn the user that there is already a duplicate entry. How do I go about doing it ?
Form:
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("first_name", "last_name", "nric", "address", "birthdate", "phone", "doctor");
validate_presences($required_fields);
$fields_with_max_lengths = array("phone" => 8);
validate_max_lengths($fields_with_max_lengths);
if( verify_nric($_POST['nric'])) {
$errors[] = 'This NRIC exists already.';
}
if( !isValid( 'phone', $_POST['phone'] ) ) {
$errors[] = 'Please enter a valid phone number';
}
if( !isValid( 'nric', $_POST['nric'] ) ) {
$errors[] = 'Please enter a valid nric number';
}
if (empty($errors)) {
// perform Create
$name = mysql_prep($_POST["name"]);
$age = (int) $_POST["age"];
$nric = mysql_prep($_POST["nric"]);
$birthdate = mysql_prep($_POST["birthdate"]);
$allergy = mysql_prep($_POST["medical_allergy"]);
$history = mysql_prep($_POST["medical_history"]);
$phone = (int)$_POST["phone"];
$address = mysql_prep($_POST["address"]);
$doctor = mysql_prep($_POST["doctor"]);
//escape content
// 2. Perform database query
$query = "INSERT INTO patients (";
$query .= " name, age, nric, birthdate, medical_allergies, medical_history,
phone, address, doctor_assigned";
$query .= ") VALUES (";
$query .= " '{$name}', {$age}, '{$nric}', '{$birthdate}',
'{$allergy}', '{$history}', {$phone}, '{$address}', '{$doctor}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Record Created.";
}else {
// Failure
$_SESSION["message"] = "Record creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<link rel="stylesheet" type="text/css" href="css/dashboard-icons.css" />
<link rel="stylesheet" type="text/css" href="css/dashboard-component.css" />
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Patient</h2>
<form action="create_patient.php" method="post">
<p>First Name:
<input type="text" name="first_name" value="" />
</p>
<p>Last Name:
<input type="text" name="last_name" value="" />
</p>
<p> NRIC/ Foreign ID/ Passport:
<input type="text" name="nric" value="" />
</p>
<p>Date Of Birth:<br />
<input type="text" name="birthdate" value="" />
</p>
<p>Contact Number:
<input type="text" name="phone" value="" />
</p>
<p>Address:
<textarea name="address" rows="1" cols="40" align="right"></textarea>
</p>
<p>Dentist Assigned:<br />
<input type="text" name="doctor" value="" />
</p>
<div id="limit">
<p>Medical Allergies:<br />
<textarea name="medical_allergy" rows="15" cols="40"></textarea>
</div>
<p>Medical History:<br />
<textarea name="medical_history" rows="15" cols="40"></textarea>
<input type="submit" name="submit" value="submit" />
</form>
<br />
Cancel
</div>
Validation Function:
function verify_nric($nric){
global $connection;
$query = "SELECT nric ";
$query .= "FROM patients ";
$query .= "ORDER BY nric ASC";
$nric_set = mysqli_query($connection, $query);
confirm_query($nric_set);
if ($nric == $nric_set) {
return $nric_set;
}
}
function isValid( $what, $data ) {
switch( $what ) {
// validate a phone number
case 'phone':
$pattern = "/^[0-9-+()\s]+$/";
break;
case 'nric':
$pattern = "/^(A-Z)?[0-9]{7}[A-Z]$/i";
break;
default:
return false;
break;
}
return preg_match($pattern, $data) ? true : false;
}
confirm_query
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: ".
mysqli_connect_error() .
" (" . mysqli_connect_errno(). ")"
);
}
}
Not sure what confirm_query() does but you could change your function to:
function verify_nric($nric){
global $connection;
$query = "SELECT nric ";
$query .= "FROM patients ";
$query .= "WHERE nric='".mysqli_real_escape_string($connection,$nric)."'"; //changed your query a little here
$nric_set = mysqli_query($connection, $query);
confirm_query($nric_set); // you haven't mentioned what this function does so I'm going to leave it that way.
$nric_found=false; //Added
if(mysqli_num_rows($nric_set)>0){ //
$nric_found=true; //These
} //
return $nric_found; //Lines
}
Now to explain where you went wrong:
Your select query returned all the nric but you weren't fetching the
values and checking against $nric. You need to use
mysqli_fetch_array() to get the values from the resultset
$nric_set
$nric == $nric_set is invalid because you are
comparing a resultset($nric_set) with a value $nric
Related
code:
<?php
session_start();
if(isset($_POST['insert']) && !empty($_POST['insert']))
{
extract($_POST);
$query = "select * from enquires2 where email = '$email'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
if($row > 0 )
{
$msg .="<h5 style='text-align:center;color:red;'>EmailId already exists please login with different emailid</h5>";
}
else
{
if(!empty($_POST['captcha_code']))
{
$captchaCode = $_SESSION['captchaCode'];
$enteredcaptchaCode = $_POST['captcha_code'];
$sql = "insert into enquires2(name,email,phone,message)values('$name','$email','$phone','$message')";
$result=mysqli_query($link,$sql);
if($result == true)
{
$msg .="<h4 style='text-align:center;color:green;'>Your Data Has Been Submitted.</h4>";
}
else
{
$errMsg = 'Captcha code not matched, please try again.';
}
}
else
{
$msg .="<h4 style='text-align:center;color:red;'>Error</h4>";
}
}
}
?>
html code:
<?php echo $msg; ?>
<?php if(!empty($errMsg)) echo '<p style="color:#EA4335;">'.$errMsg.'</p>';?>
<?php if(!empty($succMsg)) echo '<p style="color:#34A853;">'.$succMsg.'</p>';?>
<form method="post">
<input type="text" name="name" id="name" placeholder="Enter Your Name">
<input type="text" name="email" id="email" placeholder="Enter Your Email">
<input type="text" name="phone" id="phone" placeholder="Enter Your Phone">
<input type="text" name="message" id="message" placeholder="Enter Your Message" >
<input name="captcha_code" type="text" value="" placeholder="Enter the code" >
<img src="captcha.php" id="capImage"/>
<br/>Can't read the image? click here to refresh.
<input type="submit" name="insert" value="Submit" placeholder="Enter Your Message" >
</form>
When I click on submit button it shows data has been submitted successfully while captcha code is right or worng it insert form value into database. So, how can I fix this problem ?
Thank You
Please use this code:
<?php
session_start();
if(isset($_POST['insert']) && !empty($_POST['insert']))
{
extract($_POST);
$query = "select * from enquires2 where email = '$email'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
if($row > 0 )
{
$msg .="<h5 style='text-align:center;color:red;'>EmailId already exists please login with different emailid</h5>";
}
else
{
if(!empty($_POST['captcha_code']))
{
$captchaCode = $_SESSION['captchaCode'];
$enteredcaptchaCode = $_POST['captcha_code'];
if($captchaCode == $enteredcaptchaCode)
{
$sql = "insert into enquires2(name,email,phone,message)values('$name','$email','$phone','$message')";
$result=mysqli_query($link,$sql);
if($result == true)
{
$msg .="<h4 style='text-align:center;color:green;'>Your Data Has Been Submitted.</h4>";
}
else
{
$msg .= "<h4 style='text-align:center;color:green;'>Your Data Has Not Been Submitted.</h4>";
}
}
else
{
$errMsg = 'Captcha code not matched, please try again.';
}
}
else
{
$msg .="<h4 style='text-align:center;color:red;'>Error</h4>";
}
}
}
?>
I am wanting to populate a drop down list from another mysql table and then assign the values from two of the columns into variables - i.e. "select name, eid, perc from employee". "John Doe" would be $eid = 1234 and $perc = 20.
Any help with this would be greatly appreciated!
Thank you - Matt
Here is the code I have been working with:
PHP
<?php
//session_start();
$page_title = 'New invoice';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('mysqli_connect.php'); // Connect to the db.
/*$errors = array(); // Initialize an error array. */
// Invoice number is automatic
if (empty($_POST['op1'])) {
$errors[] = 'Operation needs to be entered.';
} else {
$op1 = mysqli_real_escape_string($dbc, trim($_POST['op1']));
}
// Amount:
if (empty($_POST['amount1'])) {
$errors[] = 'Amount to be charged.';
} else {
$amount1 = mysqli_real_escape_string($dbc, trim($_POST['amount1']));
}
// percentage:
if (empty($_POST['perc'])) {
$errors[] = 'Select a percentage.';
} else {
$perc = mysqli_real_escape_string($dbc, trim($_POST['perc']));
}
// eid:
if (empty($_POST['eid'])) {
$errors[] = 'Enter a techician.';
} else {
$eid = mysqli_real_escape_string($dbc, trim($_POST['eid']));
}
// Stocknum:
if (empty($_POST['stocknum'])) {
$errors[] = 'Need a stock number.';
} else {
$stocknum = mysqli_real_escape_string($dbc, trim($_POST['stocknum']));
}
// Stocknum:
if (empty($_POST['myear'])) {
$errors[] = 'Enter vehicle year.';
} else {
$myear = mysqli_real_escape_string($dbc, trim($_POST['myear']));
}
if (empty($_POST['make'])) {
$errors[] = 'Enter vehicle make.';
} else {
$make = mysqli_real_escape_string($dbc, trim($_POST['make']));
}
if (empty($_POST['model'])) {
$errors[] = 'Enter vehicle model.';
} else {
$model = mysqli_real_escape_string($dbc, trim($_POST['model']));
}
if (empty($_POST['vin'])) {
$errors[] = 'Enter last 6 of the VIN.';
} else {
$vin = mysqli_real_escape_string($dbc, trim($_POST['vin']));
}
if (empty($_POST['mileage'])) {
$errors[] = 'Enter current mileage.';
} else {
$mileage = mysqli_real_escape_string($dbc, trim($_POST['mileage']));
}
if (empty($errors)) { // If everything's OK.
$q = "INSERT INTO `mwcc`.`wp` (`tdate`, `stocknum`, `myear`, `make`, `model`,`vin`, `eid`, `op1`, `amount1`,`mileage`,`ecomm`) VALUES (CURRENT_DATE(), '$stocknum', '$myear', '$make', '$model','$vin', '$eid', '$op1', '$amount1','$mileage', ($amount1*$perc));";
$r = #mysqli_query ($dbc, $q); // Run the query.
//echo ($q);
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Success!</h1>
<p>Invoice has been created!<br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">Uh oh. There has been an error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbc); // Close the database connection.
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} // End of the main Submit conditional.
?>
HTML :
<form action="newinv.php" method="post">
<p>Stock #
<input type="text" name="stocknum" size="15" maxlength="20" value="<?php if (isset($_POST['stocknum'])) echo $_POST['stocknum']; ?>" />
Last 6 of VIN
<input type="text" name="vin" size="15" maxlength="6" value="<?php if (isset($_GET['vin'])) echo $_POST['vin']; ?>" /> </p>
<p>Year
<input type="text" name="myear" size="4" maxlength="4" value="<?php if (isset($_POST['myear'])) echo $_POST['myear']; ?>" />
Make
<input type="text" name="make" size="30" maxlength="20" value="<?php if (isset($_POST['make'])) echo $_POST['make']; ?>" />
Model
<input type="text" name="model" size="30" maxlength="20" value="<?php if (isset($_POST['model'])) echo $_POST['model']; ?>" /></p>
Mileage
<input type="text" name="mileage" sizesize="15" maxlength="6" value="<?php if (isset($_POST['mileage'])) echo $_POST['mileage']; ?>" /> </p>
<p>Operation <input type="text" name="op1" size="60" maxlength="250" value="<?php if (isset($_POST['op1'])) echo $_POST['op1']; ?>" />
Amount <input type="text" name="amount1" size="8" maxlength="20" value="<?php if (isset($_POST['amount1'])) echo $_POST['amount1']; ?>" /></p>
<br>
<input type="radio" name="eid" value="1767">Alex H<br>
<input type="radio" name="eid" value="1688">Blake S<br>
<input type="radio" name="eid" value="1506">Brian M<br>
<input type="radio" name="eid" value="1898">Chris V<br>
<input type="radio" name="eid" value="3000">Kim R<br>
<input type="radio" name="eid" value="1916">Jorden U<br>
<input type="radio" name="eid" value="1931">Tina M<br>
<input type="radio" name="eid" value="1506">Tanner C<br>
<br>
<input type="radio" name="perc" value=".35">35%
<br>
<input type="radio" name="perc" value=".40">40%
<p><input type="submit" name="submit" value="Add" /></p>
</form>
My understanding from your question.
Get query result as you mentioned.select name, eid, perc from employee
For Front End if you want pass both values in single select then use some unique separator like i'm using double underscore __
<?php foreach($result as $user): ?>
<select name="eid__perc" >
<option value="<?php $user->eid . '__' . $user->perc?>">
<?php $user->name; //in array case $user['name'];?>
<option>
<select>
<?php endforeach;?>
And when you save information use same separator to explode data like
list($eid, $perc) = explode('__', $_POST['eid__per'])
You need to use WHERE condition for that:
SELECT name, eid, perc FROM employee WHERE eid = ? AND perc = ?
Than use mysqli_stmt_bind_param($stmt, 'ss', $eid, $perc); to bind parameters.
I'm working on a signup form in PHP. The form is a div which opens when you click on a button. Here's my code:
if(!$fieldsFilled){
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
This all executes after my form is submitted:
if (isset($_POST['signUp']))
Full PHP code:
<?php require 'dbconnect.php'; ?>
<?php
//Error message variable declarations
$unmatchedPasswordsError = "";
$unfilledFormsError = "";
$emailError = "";
//If sign up submit POST recieved
if (isset($_POST['signUp']))
{
//Start session
session_start();
$email = $connection->real_escape_string($_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
if ($result->num_rows)
{
$emailInUse = true;
}
else
{
$emailInUse = false;
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suVerifyPassword', 'suDisplayName');
$fieldsFilled = true;
foreach($required as $field)
{
if (empty($_POST[$field]))
{
$fieldsFilled = false;
}
else
{
$fieldsFilled = true;
}
}
if ($emailInUse)
{
$emailError = "The email is already in use.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
if(!$fieldsFilled)
{
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "The email is not valid.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Check for unverified password
if ($_POST['suPassword']!= $_POST['suConfirmPassword'])
{
$unmatchedPasswordsError = "The passwords do not match.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Variable declaration for sign up POST values
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//Insert POST values into database
$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
//Redirect to 'email sent' webpage
header('Location: emailSent.php');
}
}
}
}
}
//If log in submit POST recieved
if (isset($_POST['logIn']))
{
//Variable declaration for log in POST values
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//Search for log in credentials in dabase
$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
//TODO: CHECK FOR REMEMBER ME CHECK
session_start();
$_SESSION['userID'] = $row['userID'];
}?>
HTML sign up div/form code:
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<?php
echo '<br><font class="text-error" id="email-error">',$emailError,'</font>';
?>
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<?php
echo '<br><font class="text-error" id="passwords-unmatched-error">',$unmatchedPasswordsError,'</font>';
?>
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<?php
echo $unfilledFormsError;
?>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
The "test passed" does log to the console, however the div is not showing after the page refresh (due to form submission). Any help is appreciated! Thank you so much!
I have customized as your requirement and database connection i have used
Mysqli replace whatever you want also change database credentials.
Full code will be in same page. Try and comment if you don't understand anything.
<?php
session_start();
//require 'dbconnect.php';
$connection=mysqli_connect("localhost","root","","test"); // I have use it for testing
$errors = array();
if (isset($_POST['signUp'])) {
$email = mysqli_real_escape_string($connection, $_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
//email check
if(mysqli_num_rows($result)>0){
$errors[] = "The email is already in use.";
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "The email is not valid.";
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suConfirmPassword', 'suDisplayName');
foreach($required as $field){
if (empty($_POST[$field])){
$errors[] = $field." Cannot be empty.";
}
}
if(count($errors)==0){
if($_POST['suPassword']!=$_POST['suConfirmPassword']){
$errors[] = "The passwords do not match.";
}else{
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
$sql = mysqli_query($connection, "INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
if($sql){
header('Location: emailSent.php');
}else{
$errors[] = "Failed to insert.";
}
}
}
}
if (isset($_POST['logIn'])){
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$result = mysqli_query($connection, "select * from users where email = '$liEmail' AND password = '$liPassword'");
if($result){
$row = mysqli_fetch_assoc($result);
$_SESSION['userID'] = $row['userID'];
}
}
?>
<?php
if(!empty($errors)){
foreach ($errors as $value) {
echo "<span style='color:red;'>".$value."</span><br>";
}
}
?>
<button type="button" id="showSignup">Show Sign-up</button><br><br>
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
<?php if(isset($_POST['signUp']) && count($errors)>0){ ?>
$('#home-sign-up-box').show();
<?php }elseif(isset($_POST['signUp']) && count($errors)==0){ ?>
//$('#home-sign-up-box').hide();
<?php }else{?>
//$('#home-sign-up-box').show();
<?php }?>
$("#showSignup").click(function(){
$('#home-sign-up-box').toggle();
visible_check();
});
visible_check();
});
function visible_check(){
var isVisible = $( "#home-sign-up-box" ).is( ":visible" );
if(isVisible){
$("#showSignup").html("Hide Sign-up");
}else{
$("#showSignup").html("Show Sign-up");
}
}
</script>
I am doing a project to add, update, delete, etc records from a p2pmyadmin database.
I am working on the current code. When update is hit, all the fields update in the database, except the 'Surname' field. I cannot figure out why... Can anyone advise?
$dirtyPassword = $_POST['frmPassword1'];
if (isset($_POST['formName']) && $_POST['formName'] == "addUser") {
if ( ($_POST['frmSurname'] != '') &&
($_POST['frmEmail'] != '') &&
($_POST['frmPassword1'] != '') ) {
if ($_POST['frmPassword1'] != $_POST['frmPassword2'] ) {
echo "Passwords do not match!";
//Clean form values
$cleanFirstName = mysqli_real_escape_string($db, $_POST['frmName']);
$cleanSurname = mysqli_real_escape_string($db, $_POST['frmSurname']);
$cleanEmail = mysqli_real_escape_string($db, $_POST['frmEmail']);
//Clean password
$password = sha1(mysqli_real_escape_string($db, $_POST['frmPassword1']));
// Build username
$username = strtolower($cleanFirstName.substr($cleanSurname,0,1));
$dateTime = date('Y-m-d g:i:s',time());
// Check email is unique
$QryEmail = "SELECT *
FROM registeredUsers
WHERE EmailAddress = '$cleanEmail'";
$chkEmail = mysqli_query($db,$QryEmail);
$numChkRowsE = mysqli_num_rows($chkEmail);
// Check Username is unique
$QryID = "SELECT *
FROM registeredUsers
WHERE UserName = '$username'";
$ChkID = mysqli_query($db,$QryID);
$numChkRowsI = mysqli_num_rows($chkID);
//check that zero records returned (no duplicates)
if ($numChkRowsE == 0 && $numChkRowsI == 0){
//Query
$query = "INSERT INTO registeredUsers VALUES(NULL, '$username', '$cleanFirstName', '$cleanSurname', '$cleanEmail', '$password', '$dateTime', 0) ";
$insQry = mysqli_query($db,$query);
if ($insQry) {
/* SUCCESS */
$_SESSION['success'] = 'Registration successful';
header("Location:project-users-manage.php");
exit;
} else {
/* FAIL */
}
}
}
?>
<fieldset style =width:30%>
<form method="post" action="">
<p>
First Name : <input type="text" name="frmName" value="" placeholder='First Name'><br>
Surname: <input type="text" name="frmSurname" value="" placeholder='Surname'><br>
Email Address: <input type="text" name="frmEmail" value="" placeholder='Email Address'><br>
Password: <input type="password" name="frmPassword1" value="" placeholder='Password'><br>
Repeat Password: <input type="password" name="frmPassword2" value="" placeholder='Password Again'><br>
<input type="submit" name="Register" value="Register">
<input type='hidden' name='formName' value='addUser' />
</p>
</form>
<br>
<a href='project-users-manage.php'>User Management</a>
<a href=''>Logout</a>
I'm working on an HTML form, which is connected to MySQL database. Database is updating with new data every time, when I reload the page and also when a failed submit occur.
This is my code, Anyone please help me to add session to this page and please give me a solution
<body>
<?php
// define variables and set to empty values
$email_id = $first_name = $last_name = $district = $city = $address = $mobile_no = $password = "";
$email_idErr = $first_nameErr = $last_nameErr = $districtErr = $cityErr = $addressErr = $mobile_noErr = $passwordErr = "";
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//First name validation
if(empty($_POST["first_name"]))
{$first_nameErr="First name is required";}
else
{$first_name = test_input($_POST["first_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$first_name))
{$first_nameErr="Only letters and white spaces allowed";}
}
//Second name validation
if(empty($_POST["last_name"]))
{$last_nameErr="Last name is required";}
else
{$last_name = test_input($_POST["last_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$last_name))
{$last_nameErr="Only letters and white spaces allowed";}
}
//E-mail validation
if(empty($_POST["email_id"]))
{$email_idErr="E-mail id is required";}
else
{$email_id = test_input($_POST["email_id"]);
//checking email format
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email_id))
{$email_idErr="Invalid email format";}
}
//District is required
if(empty($_POST["district"]))
{ $districtErr="District is required";}
else
{ $district = test_input($_POST["district"]);
if(!preg_match("/^[a-zA-Z]*$/",$district))
{$districtErr="Only letters and white spaces allowed";}
}
$city = test_input($_POST["city"]);
$address = test_input($_POST["address"]);
//Mobile number validation
if(empty($_POST["mobile_no"]))
{$mobile_noErr="Mobile number is required";}
else
{$mobile_no = test_input($_POST["mobile_no"]);
if(!preg_match("/^[0-9]*$/",$mobile_no))
{$mobile_noErr="Invalid Mobile number";}
}
//Password validation
if(empty($_POST["password"]))
{$passwordErr="Password is required";}
else
{ $password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
$con=mysqli_connect("localhost","root","","ashlyn");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{echo "Connection Established";}
$sql="INSERT INTO user_details (email_id, first_name, last_name, district, city, address, mobile_no, password)
VALUES ('$email_id', '$first_name', '$last_name', '$district', '$city', '$address', '$mobile_no', '$password')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "You are successfully registered..";
mysqli_close($con);
?>
<section class="container">
<div class="login">
<h1>User Login Page</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);>">
<p><input type="text" name="first_name" value="" placeholder="First Name"><span class="error">* <?php echo $first_nameErr;?></span></p>
<p><input type="text" name="last_name" value="" placeholder="Last Name"> <span class="error">* <?php echo $last_nameErr;?></span>
</p>
<p><input type="text" name="email_id" value="" placeholder="Email"><span class="error">* <?php echo $email_idErr;?></span>
</p>
<p><input type="text" name="district" value="" placeholder="District"><span class="error">* <?php echo $districtErr;?></span></p>
<p><input type="text" name="city" value="" placeholder="City">
</p>
<p><input type="text" name="address" value="" placeholder="Address">
</p>
<p><input type="text" name="mobile_no" value="" placeholder="Mobile Number"> <span class="error">* <?php echo $mobile_noErr;?></span>
</p>
<p><input type="password" name="password" value="" placeholder="Password"> <span class="error">* <?php echo $passwordErr;?></span>
</p>
<p class="submit"><input type="submit" name="submit" value="Submit"></p>
</form>
what you need is
<?php session_start();
on the first line bevor any output
https://stackoverflow.com/a/8084900/1792420