I have a form that updates a users information upon submit. The current setup only allows the form to be submitted if all fields are filled out. I need to create if statements for each field that says if populated, update, if not, dont.
I have the password field listed below that describes what I want to do for each and every field, but I wasnt sure if I could list multiple variables inside the IF or do I have to write separate IF statements and select from the database every time
if($password != '') {
if($password != $password2) {
$error = '<div class="error_message">Attention! Your passwords did not match.</div>';
}
if(strlen($password) < 5) {
$error = '<div class="error_message">Attention! Your password must be at least 5 characters.</div>';
}
if($error == '') {
$sql = "UPDATE login_users
SET restricted = '$restrict',
company_name = '$company_name',
contact = '$contact',
email = '$email',
user_level = '$level',
password = MD5('$password')
WHERE user_id = '$id'";
$query = mysql_query($sql) or die("Fatal error: ".mysql_error());
echo "<h2>Updated</h2>";
echo "<div class='success_message'>User information (and password) updated for User ID <b>$id ($company_name)</b>.</div>";
echo "<h2>What to do now?</h2><br />";
echo "<a href='xxxxxxxx'>« Back to Admin Panel</a> | Go to the <a href='user_edit.php'>edit users</a> page.</li>";
}
Here is some more of my code
if(trim($id) == '1') {
$error = '<div class="error_message">Attention! You cannot edit the main Administrator, use database.</div>';
} else if(trim($company_name) == '') {
$error = '<div class="error_message">Attention! You must enter a company name.</div>';
} else if(trim($contact) == '') {
$error = '<div class="error_message">Attention! You must enter a contact name.</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Attention! You have entered an invalid e-mail address, try again.</div>';
} else if(trim($level) == '') {
$error = '<div class="error_message">Attention! No user level has been selected.</div>';
}
I need to create if statements for
each field that says if populated,
update, if not, dont.
You can build your SQL statement as you go. Something along the lines of:
$sqlCols = '';
$error = '';
// Password
if ($password != '') {
if ($password == $password2) {
if (strlen($password) > 4) {
$sqlCols .= "password = MD5('".mysql_real_escape_string($password)."'), ";
} else {
$error .= '<div class="error_message">Attention! Your password must be at least 5 characters.</div>';
}
} else {
$error .= '<div class="error_message">Attention! Your passwords did not match.</div>';
}
}
// Email
if ($email != '') {
if (isValidEmail($email)) {
$sqlCols .= "email ='".mysql_real_escape_string($password)."', ";
} else {
$error .= '<div class="error_message">Attention! Your email is invalid.</div>';
}
}
if ($error == '') {
$sql = "UPDATE login_users
SET ".trim($sqlCols, ', ')."
WHERE user_id = '$id'";
// etc...
}
In the near future, switch over to PDO for improved performance and better protection against SQL injection.
It depends on what kind of user feedback you want, but here's a simple approach that collects the fields that pass validation, and uses them for the query.
$errors = array();
$fields = array();
if( ($password != $password2) {
$errors[] = "Passwords didn't match";
$fields['password'] = $password;
}
if(empty($email)) {
$errors[] = "Email is empty";
$fields['email'] = $email;
}
if($something > $nothing) { //
$errors[] = "More errors";
$fields['something'] = $something;
}
//and so on...
if(!count($errors)) {
$str = '';
foreach($fields as $field => $val ) {
$str .= $field. "= '" .$val."', ";
}
$str = substr($str,0,1); //removes last , (comma)
$sql = "UPDATE login_users
SET $str
WHERE user_id = '$id'";
//do query..
}
Related
i have two variables mobile and email now i want to validate both but i want the user to leave blank one of the fields if user does not have one for ex if a user does not want to register with his email then he can go to mobile number for registration and vice versa this is my validation code
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$mobileerror = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$mobile = strip_tags($_POST['mobile']);
$fullname_valid = $email_valid = $mobile_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
if ($mobile) {
$query4 = "SELECT mobile FROM users WHERE mobile = '$mobile'";
$fire4 = mysqli_query($con, $query4) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire4) > 0) {
$mobileerror = "is already taken please try another one<br> ";
} else {
$mobile_valid = true;
}
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && ($email_valid || $mobile_valid )&& $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs how to solve this problem
Use one more flag
$isValid_email_mobile = FALSE;
When control flow enters into if (filter_var($email, FILTER_VALIDATE_EMAIL)) then on SUCCESS just set $isValid_email_mobile = TRUE; It will be same if control enters in condition if ($mobile) again on SUCCESS , set it as $isValid_email_mobile = TRUE;
When $isValid_email_mobile = FALSE; becomes TRUE then you know that of the field/variable has passed your requirement and its ready for DB INSERT
Then
In your last IF condition when you try to INSERT just change IF condition to the following
IF ($fullname_valid && $isValid_email_mobile && $password_valid && $username_valid)
One more thing whenever you are using Flag logic always set your flag to some default value before using it.
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs
you have:
if (!empty($fullname)) {}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {}
if ($mobile) {}
if (!empty($username)) {}
if (!empty($password)) {}
To remove the error, try adding
if (!empty($mobile)) {
Also, I would suggest to wrap the statements a bit more. You only need one to fail in order to stop input. You could do something like this:
$mobileOrEmail = false;
if (!empty($fullname) && !empty($username) && !empty($password) {
//check fullname, username and password
if (!empty($mobile) {
//check mobile, if it passes
$mobileOrEmail = true;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//check email, if it passes
$mobileOrEmail = true;
}
if (!$mobileOrEmail) $errors++;
} else {
//missing input values
$errors++;
}
Personally, I would create a function for each input field.
function checkUsername($username){
//check username
return true;
}
function checkEmail($email) {
//check email
return true;
}
....
then you can run
if (checkUsername($username) && checkPassword($password)
&& checkFullname($fullname) && (checkEmail($email) || checkEmail($email)) {
//user input correct
} else {
//user input failed
}
Just to give it more structure
Is it possible to split the Username or Email already exists into specific error messages?
I'm working on this user registration script, if you have any tips about the rest of code given would be much appreciated
if(isset($_POST['register'])){
if(
// check if posts not empty
empty($_POST['username']) ||
empty($_POST['email']) ||
empty($_POST['password']) ||
empty($_POST['re_password']) ||
$_POST['password'] != $_POST['re_password']
){
// if a field is empty, or the passwords don't match make a message
error = '<p>';
if(empty($_POST['username'])){
$error .= 'No username given<br>';
}
if(empty($_POST['email'])){
$error .= 'No email given<br>';
}
if(empty($_POST['password'])){
$error .= 'No password given<br>';
}
if(empty($_POST['re_password'])){
$error .= 'You must re-type your password<br>';
}
if($_POST['password'] != $_POST['re_password']){
$error .= 'Passwords don\'t match<br>';
}
$error .= '</p>';
}
else{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = $_POST['re_password'];
$query = mysqli_query(
$conn,"SELECT * FROM members WHERE username = '". $username ."' OR email = '". $email ."'");
if(mysqli_num_rows($query) > 0){
echo "Username or Email already exist";
}
else {
$sql = "INSERT INTO members (username, password, email)
VALUES
('$_POST[username]',
'$_POST[email]',
'$_POST[password]')";
if (mysqli_query($conn, $sql)) {
echo "Registered";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
}
}
if(isset($error)){
echo $error;
unset($error);
}
You need to change here only:--
if(mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)){
if(isset($row['username']) && !empty($row['username']) && $_POST['username'] ==$row['username'] )){
echo "Username already exist";
}
if(isset($row['password']) && !empty($row['password']) && $_POST['password'] ==$row['password'] )){
echo "Password already exist";
}
}
}
Note:- if your password have some encryption then you need to change password part condition accordingly (just third part of it). Also if i missed any wher indexes in writing let me know.
I wrote the following code in baby steps, working with each thoroughly until it's worked. The last step was checking that a username/email does not exist and if true, inserting everything into a database. I got the code to send an email if there are not errors up until [5], but I cannot test anything beyond sending an email. When form is completed and sent, the page is cleared after the heading and does not proceed to the next page.
I have gone over the code as thoroughly as I possibly could, pulling up multiple sources and checking over general syntax with php validation tools. I don't have anything that comes up.
Connection:
$con = mysqli_connect('$db_host', '$db_user', '$db_pass', '$db_name');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Body:
if (isset($_POST['process'])) {
$birthday = $_POST['year'].$dash.$_POST['month'].$dash.$_POST['day'];
$user_name = htmlspecialchars($_POST['user']);
$email = htmlspecialchars($_POST['email']);
$pass = htmlspecialchars($_POST['pass']);
$confirm = htmlspecialchars($_POST['confirm']);
if ($_POST['user'] == '') {
$errors[1] = 'Please enter your username.';
} else if (!preg_match('/^[a-zA-Z0-9]{4,25}$/', $_POST['user'])) {
$errors[1] = 'Usernames must contain 4 to 25 alphanumeric characters.';
} else {
$errors[1] = '';
}
if ($_POST['email'] == '') {
$errors[2] = 'Please enter your email.';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[2] = 'Email must be valid.';
} else {
$errors[2] = '';
}
if ($_POST['pass'] == '') {
$errors[3] = 'Please enter your password.';
} else if (!preg_match('$\S*(?=\S{6,})\S*$', $_POST['pass'])) {
$errors[3] = 'Passwords must be at least six characters long.';
} else {
$errors[3] = '';
}
if ($_POST['confirm'] == '') {
$errors[4] = 'Please confirm your password.';
} else if ($_POST['confirm'] != $_POST['pass']) {
$errors[4] = 'Passwords do not match.';
} else {
$errors[4] = '';
$hash = password_hash ('$pass', PASSWORD_DEFAULT);
}
if (time() < strtotime('+13 years', strtotime($birthday))) {
$errors[5] = 'You are not at least thirteen years old.';
} else {
$errors[5] = '';
}
$to = $email;
$subject = 'Rabbit Showing and Breeding Association Registration Confirmation';
$header = 'From: RSBA Registration <registration#rsba.net>';
$message = 'Hello ' . $user_name . '!
You are receiving this email because you recently registered at Rabbit Showing and Breeding Association at http://rsba.net
Your confirmation code is: ' . $confirm_code . '
Please copy and paste the code into the account confirmation page or follow the following link to get started:
http://rsba.net/registration/confirmation.php?confirm_code=' . $confirm_code . '
Please disregard this email if you did not sign up for RSBA.
Thank-you,
Rabbit Showing and Breeding Association
This is an automated message. Do not reply.';
if ($errors[1] == '' && $errors[2] == '' && $errors[3] == '' && $errors[4] == '' && $errors[5] == '') {
$sentmail = mail($to,$subject,$message,$header);
}
if($sentmail){
include_once "../connect_info.php";
$result = mysqli_query($con,"SELECT * FROM users WHERE user_name = '" . $user_name . "'");
$row = mysqli_fetch_array($result);
if ($row['user_name']) {
$errors[6] = 'This username already exists.';
}
$result = mysqli_query($con,"SELECT * FROM users WHERE email = '" . $email . "'");
$row = mysqli_fetch_array($result);
if ($row['email']) {
$errors[7] = 'A user is already registered with this email.';
}
if ($errors[6] == '' && $errors[7] == '') {
$result = "INSERT INTO users (user_name, email, hash, birthday, confirm_code, access_level)
VALUES ('$user_name', '$email', '$hash', '$birthday', '$confirm_code', '0')";
if (mysqli_query($con, $result)) {
header('Location:sent');
} else {
$error[8] = '<span class="error">You cannot be registered.</span>';
}
}
}
mysqli_close($con);
}
I am currently programming php, and enjoying it.
I know how to code a script that will update a user's email address or password in different processes. I need to update them in one form. Here's a screenshot:
I need to update one of them, if he didn't enter a password then update the email, if he didn't enter the email update the password, if he entered both update both..
the script I am currently coding has been twirling around my mind and I have lost myself over and over and over...
update_settings_process.php: (I have Updated the script!!)
<?php
error_reporting(1);
session_start();
include("../common/config.php");
include("../common/conn.php");
$case = '';
$error_str = '';
//email:
$email = stripslashes($_REQUEST['email_address']);
//password:
$old_password = trim($_REQUEST['old_password']);
$password = trim($_REQUEST['password']);
$conf_password = trim($_REQUEST['conf_password']);
$get_users_qry = "Select password From users where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."' AND password = '".md5($old_password)."' AND status = 1";
$get_users = $db->get_row($get_users_qry,ARRAY_A);
$qry = "Select email from users where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
echo 'Email:' . $email;
echo '<p>';
echo 'Old Password: '. $old_password;
echo '<p>';
echo 'Password:' . $password;
echo '<p>';
echo 'Confrim Password:' . $conf_password;
echo '<p>';
if(filter_var($email, FILTER_VALIDATE_EMAIL) && (strlen($password) > 5) && $get_users && !mysql_num_rows($res))
{
//update email and password
$update_password = mysql_query("UPDATE users
SET
password='".md5($password)."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo 'Email and Password Has been Updated!';
die();
}
if ($email == '' && (strlen($password) == 0))
{
$error_str .= "There is nothing to update";
echo $error_str;
die();
}
if ($email == '' && (strlen($password) == 0))
{
$error_str .= "Use a secure Password";
echo $error_str;
$case = 0;
die();
}
else
{
if($email == '' && (strlen($password) < 5))
{
$error_str .= "Password must be atleast 5 characters";
echo $error_str;
$case = 0;
die();
}
else
{
if ($email == '' && $password != $conf_password)
{
$error_str .= "Passwords Do not Match";
echo $error_str;
$case = 0;
die();
}
else
{
if($email == '' && !$get_users)
{
$error_str .= "Please enter correct old password <br>";
echo $error_str;
$case = 0;
die();
}
else
{
//update password only!
if(strlen($password) == 0)
{
die();
}
else
{
$update_password = mysql_query("UPDATE users
SET
password='".md5($password)."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Password changed successfully";
exit();
}
}
}
}
}
if(strlen($password) == 0)
{
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error_str .="Invalid Email <br>";
echo $error_str;
$case = 0;
die();
}
else
{
$qry = "Select email from tbl_admin where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
if(mysql_num_rows($res))
{
$error_str = "$email already exist<br>";
$case = 0;
}
else
{
//update email only!
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Email address changed successfully";
die();
}
}
}
if($case = 0)
{
echo $error_str;
die();
}
?>
I have really lost myself in there, and I couldn't figure out why because of that..
I have updated the script:
it can update password and email at the same time
it can update password only
it can not update email only.. <-- im stuck here
here's the update email only part:
if(strlen($password) == 0)
{
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error_str .="Invalid Email <br>";
echo $error_str;
$case = 0;
die();
}
else
{
$qry = "Select email from tbl_admin where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
if(mysql_num_rows($res))
{
$error_str = "$email already exist<br>";
$case = 0;
}
else
{
//update email only!
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Email address changed successfully";
die();
}
}
}
There are some mistakes in your if-clauses. Try changing them to something like this:
$email == ''
1) = is the assignment operator, == is the comparison operator, which you weirdly used correctly with the strlen($password) comparison. The mnemonic is "Twice is for T(w)sets, Once is for Owssignment" (works best in a North English accent).
2) You're doing something rather odd with the strlen() function. strlen() always returns an integer (until someone invents half-letters). Consequently, strlen == '' is a bad, bad test. What you would want that line to look like is this:
if ($email = '' && (strlen($password) == 0))
(though why you didn't use strlen() both times puzzles me!)
3) Do not, not even jokingly, use the word 'retard' in code, or at least be bright enough not to post it publicly. It's ableist and, frankly, stupid. There are loads of people on this board who are extremely experienced and would, were they not better (wo)men, think you to be one for using a single = to test. Never call your users, or indeed anyone, a 'retard'. It's not funny.
I have a form in a file register.php, and it posts to registerPost.php. Inside registerPost.php, I check against a few validation rules, then if any of them are flagged, I return to the first page and print the errors. In theory, that should work. But the validation goes through with no problems, even when I leave everything blank.
Here's the code in question:
$_SESSION["a"] = "";
$_SESSION["b"] = "";
$_SESSION["c"] = "";
$_SESSION["d"] = "";
$_SESSION["e"] = "";
$_SESSION["f"] = "";
$_SESSION["g"] = "";
if(empty($userEmail))
{
$_SESSION["a"] = "You must enter your email.";
}
if(!validEmail($userEmail))
{
$_SESSION["a"] = "Improper Email Format";
}
if(empty($password))
{
$_SESSION["b"] = "You must enter a password.";
}
if(strlen($password) < 5 || strlen($password) > 0)
{
$_SESSION["b"] = "Password must be at least 5 characters.";
}
if($password != $confPassword)
{
$_SESSION["c"] = "Passwords do not match";
}
if(empty($firstName))
{
$_SESSION["d"] = "First Name Required";
}
if(empty($lastName))
{
$_SESSION["e"] = "Last Name Required";
}
if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE email = '$email'")) > 0)
{
$_SESSION["f"] = "This email address already exists in our database.";
}
if(!empty($_SESSION["a"]) || !empty($_SESSION["b"]) || !empty($_SESSION["c"]) || !empty($_SESSION["d"]) || !empty($_SESSION["e"]) || !empty($_SESSION["f"]))
{
header('Location: register.php');
}
Perhaps there is a more straightforward way to do this?
I like this way of registering all errors:
$errors = array();
if (empty($foo1))
$errors[] = "foo1 can't be left blank!";
else if (!preg_match(' ... ', $foo1))
$errors[] = "foo1 was not filled out correctly!";
if (empty($foo2))
$errors[] = "foo2 can't be left blank!";
// ...
if (empty($errors)) {
// do what you need
} else {
// notify the user of the problems detected
}
Do you really need to change the page by header?
I tried your code and it works for me.
Guessing from $username,$email and so on, I think you're doing some sanitizing on the $_POST data. If so, you should dump the $username, etc. to see, if that procedure is putting something in these variables.
Anyway, I like this way of validation better:
$errors = array();
if(empty($username))
{
$errors['username'] = 'Username cannot be empty!';
}
...
$_SESSION['errors'] = $errors;
if(count($errors) > 0) //Redirect...