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>
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Why does this PDO statement silently fail?
(2 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I hope someone can shed some light on this issue. I have created a registration form that submits to a second page for validation. there are various checks to catch errors and unwanted user input and is failing on checking for empty fields.. even if all the fields have data in them, it is still being returned as empty
here is my form - note it does include a hidden field to which it was suggested to use a /> instead of the usual > tag - either way makes no difference
<form id="registersocial" class="SRF" name="registersocial" action="php.includes/rasocial.inc.php" method="POST">
<div id="formheaders"><strong>Personal Details</strong></div>
<br/>
<fieldset>
<lable><strong>First Name</strong><br/>
<input type="text" name="firstname" id="firstname" class="SRF" onKeyup="restrict('firstname')" placeholder="First Name" >
<span id="Errmsg-first"></span>
</lable>
<br/>
<lable><strong>Last Name</strong><br/>
<input type="text" name="lastname" id="lastname" class="SRF" onKeyup="restrict('lastname')" placeholder="Last Name" >
<span id="Errmsg-last"></span>
</lable>
<br/>
</fieldset>
<fieldset>
<lable><strong>Date of Birth</strong><br/>
<select name="birthmonth" id="birthmonth" class="SRF">
<?php require("php.includes/month.inc.php"); ?>
</select>
<span id="Errmsg-mob"></span>
<input type="text" name="birthday" id="birthday" class="SRF" maxlength="2" placeholder="Day">
<span id="Errmsg-dob"></span>
<input type="text" name="birthyear" id="birthyear" class="SRF" maxlength="4" placeholder="Year">
<span id="Errmsg-yob"></span>
</lable>
<br/>
</fieldset>
<fieldset>
<lable><strong>Location</strong><br/>
<select name="country" id="country">
<?php require("php.includes/countrylist.php"); ?>
</select>
<span id="Errmsg-country"></span>
</lable>
<br/>
</fieldset>
<hr class="SRF">
<div id="formheaders"><strong >Account Information</strong></div>
<br/>
<fieldset>
<input type="hidden" name="accounttype" id="accounttype" class="SRF" value="Social"/>
<lable><strong>Create a Username</strong><br/>
<input type="text" name="username" id="username" class="SRF" onKeyup="restrict('username')" onblur="checkusername()" placeholder="Username" >
<span id="Errmsg-username"></span>
</lable>
<br/>
<lable><strong>Your Current Email</strong><br/>
<input type="email" name="email" id="email" class="SRF" onKeyup="restrict('email')" placeholder="Your Email" >
<span id="Errmsg-email"></span>
</lable>
<br/>
<lable><strong>Create a Password</strong><br/>
<input type="password" name="pwd" id="pwd" class="SRF" placeholder="Password" >
<span id="Errmsg-password"></span>
</lable>
<br/>
<br/>
<input type="submit" id="submit" name="submit" value="submit">
</fieldset>
<br/>
<span id="status"></span>
<br/>
</form>
below is the file that gets the posted data and runs through validation file name is rasocial.inc.php - again my issue is that upon completing the form, I am getting a empty error in the url - I am sure it is simple but cannot see it for the life of me
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
include_once("ctb.inc.php");
$fn = mysqli_real_escape_string($pdo, $_POST['firstname']);
$ln = mysqli_real_escape_string($pdo, $_POST['lastname']);
$bm = mysqli_real_escape_string($pdo, $_POST['birthmonth']);
$bd = mysqli_real_escape_string($pdo, $_POST['birthday']);
$by = mysqli_real_escape_string($pdo, $_POST['birthyear']);
$co = mysqli_real_escape_string($pdo, $_POST['country']);
$at = mysqli_real_escape_string($pdo, $_POST['accounttype']);
$un = mysqli_real_escape_string($pdo, $_POST['username']);
$em = mysqli_real_escape_string($pdo, $_POST['email']);
$pwd = mysqli_real_escape_string($pdo, $_POST['pwd']);
var_dump($fn, $ln, $bm, $bd, $by, $co, $at, $un, $em, $pwd);
//Error Handlers
//Check for empty fields
if (empty($fn) || empty($ln) || empty($bm) || empty($bd) || empty($by) || empty($co) || empty($at) || empty($un) || empty($em) || empty($pwd)) {
header("Location: ../registersocial.php?registersocial=empty");
exit();
} else {
//Check firstname and lastname for valid chars
if (!preg_match("/^[a-zA-Z]*$/", $fn) || !preg_match("/^[a-zA-Z]*$/", $ln)) {
header("Location: ../registersocial.php?registersocial=invalidcharacters");
exit();
} else {
//Check birth month has been selected
if ($_POST['birthmonth'] == '0') {
header("Location: ../registersocial.php?registersocial=birthmonth");
exit();
} else {
//Check birth day is numbers only
if (!preg_match("/^[0-9]*$/", $bd)) {
header("Location: ../registersocial.php?registersocial=birthday");
exit();
} else {
//Check the birth day length is 2 characters
if (strlen($bd) != 2 ) {
header("Location: ../registersocial.php?registersocial=birthdaylength");
exit();
} else {
//Check birth year is numbers only
if (!preg_match("/^[0-9]*$/", $by)) {
header("Location: ../registersocial.php?registersocial=birthyear");
exit();
} else {
//Check birth year is 4 characters
if (strlen($by) != 4 ) {
header("Location: ../registersocial.php?registersocial=birthyearlength");
exit();
} else {
//Check country has been selected
if ($_POST['country'] == '0') {
header("Location: ../registersocial.php?registersocial=country");
exit();
} else {
//Check if accounttype has been modified
if (!preg_match("/^[a-zA-Z]*$/", $at) || $_POST['accounttype'] != 'Social') {
header("Location: ../registersocial.php?registersocial=accounttype");
exit();
} else {
//Check username isnt taken
if (!preg_match("/^[a-zA-Z0-9]*$", $un)) {
header("Location: ../registersocial.php?registersocial=invalidusername");
exit();
} else {
//Check username is not taken in db
$stmt = $pdo->prepare('SELECT * FROM sh_userdata WHERE username =?');
$stmt->execute($un);
$usernamecheck = $stmt->fetch();
if ($usernamecheck > 0 ) {
header("Location: ../registersocial.php?registersocial=usernametaken");
exit();
} else {
//Check email is valid
if (!filter_var($em, FILTER_VALIDATE_EMAIL) ) {
header("Location: ../registersocial.php?registersocial=invalidemail");
exit();
} else {
//Check if email exists in db
$stmt = $pdo->prepare('SELECT * FROM sh_userdata WHERE email =?');
$stmt->execute($em);
$emailcheck = $stmt->fetch();
if ($emailcheck > 0 ) {
header("Location: ../registersocial.php?registersocial=emailtaken");
exit();
//add dob fields to make date of birth
$dob = new DateTime($by.'-'.$bm.'-'.$bd);
$dob->format('Y-m-d');
//hash password
$hashedpwd = password_hash($pwd, PASSWORD_DEFAULT);
//insert user into db
$stmt = $pdo->prepare("INSERT INTO sh_userdata (username, email, password, accounttype, signupdate, lastlogindate) VALUES (?,?,?,?,NOW(),NOW())");
$stmt->execute(array("$un","$em","$hashedpwd","$at"));
header("Location: ../registersocial.php?registersocial=sucess");
exit();
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
header("Location: ../registersocial.php?registersocial=nopost");
exit();
}
any help or suggestions would be really appreciated
I am new to server mysql database, i just hosted my server with godaddy, connected to the database, my select query is working fine. After several trouble shooting i decided to use pdo transactions but am getting this error
My php registration script for insertion into database which is not working is show below:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors','1');
require_once('dbh.php');
require_once'config.php';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['f_name']) && isset($_POST['u_name']) && ($_POST['f_name']) !="" && ($_POST['u_name']) !="" && ($_POST['Email']) !="" && ($_POST['phonenumber']) !="" ) {
/* id should be an auto-increment field in the db */
$f_name = isset($_POST['f_name']) ? $_POST['f_name'] : false;
$u_name = isset($_POST['u_name']) ? $_POST['u_name'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$password1 = isset($_POST['password1']) ? $_POST['password1'] : false;
$Email = isset($_POST['Email']) ? $_POST['Email'] : false;
$phonenumber = isset($_POST['phonenumber']) ? $_POST['phonenumber'] : false;
$sponsor = isset($_GET['sponsor']) ? $_GET['sponsor'] : false;
echo $sponsor;
$error_fname = "";
$eror_fname = "";
$errror_fname = "";
$eror_uname = "";
$errror_uname = "";
$error_uname = "";
$eror_password = "";
$errror_password = "";
$error_password = "";
$eror_email = "";
$error_email = "";
$errror_email = "";
$eror_phonenumber = "";
$error_phonenumber = "";
$errror_phonenumber = "";
$error_captcha = "";
$error_sponsor = "";
$errorSmt = "";
if(isset($_POST['f_name']) && isset($_POST['u_name']) && isset(($_POST['Email'])) && isset($_POST['phonenumber']) ) {
$errror_fname = $f_name.' is OK';
//check for duplicate username
$con= new PDO("mysql:host=$serverhost;dbname=silverhub;" , $serverusername, $serverpassword);
$query = $con->prepare("SELECT userid FROM users WHERE u_name=? LIMIT 1");
$u_Check = $query->bindParam(1, $u_name, PDO::PARAM_STR);
$u_Check = $query->execute();
$u_Check = $query->rowCount();
if( $u_Check=$query->rowCount() > 0) {
$eror_uname = ' Sorry'.$u_name.' already taken, please choose another';
}else{
$errror_uname = $u_name.' is OK';
}
//check for duplicate referral
$query = $con->prepare("SELECT sponsor FROM users WHERE userid=? LIMIT 1");
$s_Check = $query->bindParam(1, $userid, PDO::PARAM_INT);
$s_Check = $query->execute();
$s_Check= $query ->fetch(PDO::FETCH_ASSOC);
if( $s_Check['sponsor'] == $u_name) {
$error_sponsor = 'Sorry, user cannot refer himself';
}
//check referral Email
$query = $con->prepare("SELECT userid FROM users WHERE Email=? LIMIT 1");
$e_Check = $query->bindParam(1, $Email, PDO::PARAM_STR);
$e_Check = $query->execute();
$e_Check = $query->rowCount();
if( $p_Check=$query->rowCount() > 0) {
$eror_email = $Email.' already taken, please choose another';
}else{
$errror_email = $Email. ' is OK';
}
//check for duplicate phonenumber
$query = $con->prepare("SELECT userid FROM users WHERE phonenumber=? LIMIT 1");
$p_Check = $query->bindParam(1, $phonenumber, PDO::PARAM_STR);
$p_Check = $query->execute();
$p_Check = $query->rowCount();
if( $al_Check=$query->rowCount() > 0) {
$eror_phonenumber = $phonenumber.' already taken, please choose another';
}else{
$errror_phonenumber = $phonenumber. ' is OK';
}
}
// if(!preg_match("/^[a-zA-Z0-9]*$/",$f_name) && strip_tags(trim($f_name))) {
// $error_fname = 'invalid, fullname must be alphanumerics with no whitespace';
// echo 'invalid, fullname must be alphanumerics with no whitespace';
// }
if(!preg_match("/^[a-zA-Z0-9]*$/",$u_name) && strip_tags(trim($u_name))) {
$error_uname = 'invalid, username must be alphanumerics with no whitespace';
}
if(strlen($u_name) < 3 || strlen($u_name) > 16) {
$error_uname = 'Username must be between 3 - 16 characters';
}
if($password !== $password1) {
$error_password = 'Password and RepeatPassword do not match';
}
if(strlen($password) < 5) {
$error_password = 'Weak password, Password must be more than 5 characters';
}
if(strlen($phonenumber) > 11 && trim(htmlentities($phonenumber))) {
$error_phonenumber = 'Phonenumbers must be an 11 digit number';
}
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$error_email = ' invalid email address, please verify your email address';
}
if(!preg_match("/^[a-zA-Z0-9]*$/",$sponsor) && strip_tags(trim($sponsor))) {
$error_sponsor = 'invalid sponsor name, must be alphanumeric ';
}
if(empty($_POST['recaptcha'])) {
$error_captcha = 'Enter the Verification Code Above';
}
elseif($_POST['recaptcha'] != $_SESSION['recaptcha']) {
$error_captcha = 'Verification Code did not match, try again';
}elseif($_POST['recaptcha'] == $_SESSION['recaptcha']) {
$error_captcha = 'Verification Matched, Click Register';
}
if($u_name && $eror_fname =="" && $error_fname =="" && $errror_fname !=="" && $eror_uname =="" && $error_uname =="" && $errror_uname !=="" && $error_password =="" && $eror_email == "" && $error_email == "" && $errror_email !== "" && $eror_phonenumber =="" && $error_phonenumber =="" && $errror_phonenumber !=="" ) {
class reg extends dbh {
public function userCheck($f_name, $u_name,$password,$Email,$phonenumber,$sponsor) {
try {
$con = new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$con->beginTransaction();
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$passenc = password_hash($password, PASSWORD_DEFAULT, array('cost'=>11));
$emailCode = rand().$phonenumber;
$smsCode = rand().$u_name;
$Active = 0;
$Has_reserved_person = 'NO';
$MainTime = time();
$con= new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$sql = "INSERT INTO users (f_name,u_name,password,Email,emailCode,phonenumber,smsCode,sponsor,Active,Has_reserved_person,MainTime) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
$insert = $con->prepare($sql);
$insert->bindParam(1,$f_name,PDO::PARAM_STR);
$insert->bindParam(2,$u_name,PDO::PARAM_STR);
$insert->bindParam(3,$passenc );
$insert->bindParam(4,$Email,PDO::PARAM_STR);
$insert->bindParam(5,$emailCode,PDO::PARAM_STR);
$insert->bindParam(6,$phonenumber,PDO::PARAM_STR);
$insert->bindParam(7,$smsCode,PDO::PARAM_STR);
$insert->bindParam(8,$sponsor,PDO::PARAM_STR);
$insert->bindParam(9,$Active);
$insert->bindParam(10,$Has_reserved_person);
$insert->bindParam(11,$MainTime);
$insert->execute();
$con->commit();
if($insert->execute()){
echo 'insert successfull';
}else{
echo "Execute query error, because:" . print_r($con->errorinfo());
return false;
}
} catch (PDOException $e){
throw $e;
}
}
}
$object = new reg();
$object->userCheck( $f_name, $u_name, $password, $Email, $phonenumber, $sponsor);
}
}
?>
Here is my HTML FORM input:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html !doctype>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div id="container">
<div id="sec">REGISTER WITH US</div>
<img src="images/images(33).jpg">
<form action='register.php' method='POST' class='ajax-reg'>
<!-- HOW does a user enter a value here if it is HIDDEN??? Removed `required` attribute -->
<div class='form-group'>
<p> Note!!! Fields with astericks must be filled</p>
<input type='hidden' class='form-control' name='userid' placeholder='enter your id' />
</div>
<br>
<div class='form-group'>
<label>fullname*</label>
<input type="text" class="form-control" onblur ="fnamecheck()" id="f_name" name="f_name" placeholder="Enter your fullname" value="<?php echo #$_POST['f_name']?>" /><span id ="fullnameStatus"></span>
</div>
<br>
<div class='form-group'>
<label>username*</label>
<input type="username" class="form-control" name="u_name" id ="u_name" onblur ="usernamecheck()" placeholder="Enter your username" value="<?php echo #$_POST['u_name']?>" /><span id ="usernameStatus"></span>
</div>
<br>
<div class='form-group' >
<label>password*</label>
<input type="password" class="form-control" name="password" id="password" onblur ="passcheck()" placeholder="type in your password" />
</div>
<br>
<div class='form-group' >
<label>RepeatPassword*</label>
<input type="password" class="form-control" name="password1" id ="password1" onblur ="passcheck()" placeholder= "Retype in your password" /><span id ="passwordStatus"></span>
</div>
<br>
<div class='form-group'>
<label>email*</label>
<input type="email" class="form-control" name="Email" id ="Email" onblur ="emailcheck()" placeholder="Enter your email" value="<?php echo #$_POST['Email']?>" /><span id ="emailStatus"></span>
</div>
<br>
<div class='form-group'>
<label>phonenumber*</label>
<input type="number" class="form-control" name="phonenumber" id = "phonenumber" onblur ="phcheck()" placeholder="Enter your phonenumber" value="<?php echo #$_POST['phonenumber']?>" /><span id ="phonenumberStatus"></span>
</div>
<br>
<div>
<?php if (isset($_GET['sponsor']) && $_GET['sponsor'] != "") {?>
<input type="hidden" class="form-control" name="sponsor" id ="sponsor" onblur ="usernamecheck()" placeholder="type in your sponsor username here" value="<?php $sponsor = $_GET['sponsor'];?>" />
<?php }?>
</div>
<br>
<div id="captcha"><img src="captcha.php"></div>
<br>
<div id="refresh"><p> Refresh To Change Code</p></div>
<div id="captcha">
<input type="text" class="form-control" name="recaptcha" id = "recaptcha" onblur ="recaptchacheck()" placeholder="Enter The Code Above" /><span><?php echo #$error_captcha?></span><span id ="recaptchaStatus"></span>
</div>
<div class='form-group'>
<!-- this checkbox needs a name!! Assign name `terms` -->
<input type="checkbox" name="terms" required />
</div>
<div id="terms"> </a><a href="terms.php" >I agree with terms and conditions</a></div>
<div>
<input type='submit' class='btn btn-success' name='submit_signup' value='REGISTER' />
</div>
<br>
</form>
<br>
<div></div>
</div>
<footer>
</footer>
<script lang="javascript" type="text/javascript" src="jqueryfunctions.js"></script>
<script lang="javascript" type="text/javascript" src="ajaxfiles.js">
</script>
</body>
</html>
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
<?php require 'header.inc.php';
require 'connect.inc.php'; ?>
<?php
$reg = #$_POST['reg'];
$fn = "";
$ln = "";
$un = "";
$em = "";
$pswd = "";
$d = "";
$u_check = "";
$fn = strip_tags(#$_POST['fname']);
$ln = strip_tags(#$_POST['lname']);
$un = strip_tags(#$_POST['uname']);
$em = strip_tags(#$_POST['email']);
$pswd = strip_tags(#$_POST[ 'pass']);
$d = date('Y-m-d');
if($reg){
if($fn&&$ln&&$un&&$em&&$pswd){
$u_check = mysql_query("SELECT uname FROM users WHERE uname='$un'");
$check = mysql_num_rows($u_check);
if ($check == 0) {
if (strlen($un)<4||strlen($fn)<4||strlen($ln)<4) {
if (strlen($un)>20||strlen($fn)>20||strlen($ln)>20) {
echo "<div id=\"errormsg\"> <p>username/first name/last should not be over 20 characters</p> </div>";
}else {
$pswd = md5($pswd);
$query = mysql_query("INSERT INTO users VALUES ('','$un','$fn','$ln','$em','pass')");
die("welcome to vydoo");
}
}else {
echo "<div id=\"errormsg\"> <p>username/first name/last should not be under 4 characters</p> </div>";
}
}else {
echo "<div id=\"errormsg\"> <p>Username is allready taken</p> </div>";
}
}else {
echo "<div id=\"errormsg\"> <p>Please fill in all fields</p> </div>";
}
}
?>
<div class="content">
<div class="infos">
<p class="w">Sign Up and discover the great community</p>
<p class="s">Sign up in few steps , its free and unlimited</p>
</div>
<form class="form" method="POST">
<input class="Firstname" type="text" name="fname" placeholder="Fisrt name">
<input class="Lastname" type="text" name="lname" placeholder="Last name">
<input class="username" type="text" name="uname" placeholder="Usename">
<input class="email" type="email" name="email" placeholder="Email">
<input class="pass" type="password" name="pass" placeholder="Password">
<input class="submit" type="submit" name="reg" valueenter code here="Sign In">
</form>
i does not send information to database ! where is the problem please , i corrected every signle mistake in there and i cant find where is the problem , i have allready asked this question but with a different code , now i dont find my wrong code
I'm working on a website with a register system. In the userCP you can change your password. I made this script for it but it doesnt work. Can somebody help me? When I change the password it doesnt give an error but it just doesnt update it.
PHP Code:
<?php
if (isset($_POST['updatePassBtn']))
{
$cpassword = $_POST['cpassword'];
$npassword = $_POST['npassword'];
$rpassword = $_POST['rpassword'];
if (!empty($cpassword) && !empty($npassword) && !empty($rpassword))
{
if ($npassword == $rpassword)
{
if (mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `username` = '".$_SESSION['username']."' AND `password` = '".SHA1($cpassword)."'")))
{
mysql_query("UPDATE `users` SET `password` = '".SHA1($npassword)."' WHERE `username` = '".$_SESSION['username']."' AND `ID` = '".$_SESSION['id']."'");
echo '<div class="nNote nSuccess hideit"><p><strong style="color:green;">SUCCESS: </strong>Password Has Been Updated</p></div>';
}
else
{
echo '<div class="nNote nFailure hideit"><p><strong style="color:red;">FAILURE: </strong>Current Password is incorrect.</p></div>';
}
}
else
{
echo '<div class="nNote nFailure hideit"><p><strong style="color:red;">FAILURE: </strong>New Passwords Did Not Match.</p></div>';
}
}
else
{
echo '<div class="nNote nFailure hideit"><p><strong style="color:red;">FAILURE: </strong>Please fill in all fields</p></div>';
}
}
?>
My form:
<form action="" class="form" method="POST">
<fieldset>
<label></label>
<input name="cpassword" type="text" value="Current Password" onfocus="this.value = (this.value=='Current Password')? '' : this.value;" onblur="if(this.value == ''){this.value='Current Password';}"/>
</fieldset>
<fieldset>
<label></label>
<input name="npassword" type="text" value="New Password" onfocus="this.value = (this.value=='New Password')? '' : this.value;" onblur="if(this.value == ''){this.value='New Password';}"/>
</fieldset>
<fieldset>
<label></label>
<input name="rpassword" type="text" value="Repeat Password" onfocus="this.value = (this.value=='Repeat Password')? '' : this.value;" onblur="if(this.value == ''){this.value='Repeat Password';}"/>
<input type="submit" value="Update" name="updatePassBtn"/>
</fieldset>
</form>
You count the number of rows that match the username and password, but then when you update you also have the condition that it has to match $_SESSION['id']. If your session doesn't contain the right 'id', then your update could match no rows.
You should check mysql_affected_rows() before reporting that the update was successful.
You should also check that the mysql functions return success (as #RocketHazmat suggests in a comment). Many return false on error.
mysql_query("UPDATE `users` SET `password` = '".SHA1($npassword)."' WHERE `username` = '".$_SESSION['username']."' AND `ID` = '".$_SESSION['id']."'");
You have the mysql_query set up but i dont see you executing it