i have create a page to add user and i user "insert into" as my sql code, and i want to make validation to add the user, i mean it show the error if curtain column is empty when add user.. this my code
HTML page
adminadduser.html
<body>
<div>
<!--head-->
<div class= "kepala">
<span class="foundicon-smiley"></span>ADMIN
</div>
<div class= "content">
<div class="menu">
<div class="menu_box_list">
<ul>
<li><a action="php/display_user.php" href="adminMuser.php"><span class="foundicon1-person"></span> Manage user <i class="manageuser"> </i><div class="clear"></div></a></li>
<li><span> </span> vehicle manager <i class="vehicle manager"> </i><div class="clear"></div> </li>
<li><span class= "foundicon-page"></span> report <i class="Report"> </i><div class="clear"></div> </li>
<li><span class= "foundicon-settings"></span> log out<i class="settings"> </i><div class="clear"></div> </li>
</ul>
<div class="clear"></div>
</div>
</div>
</div>
<div class="1st_menu">
<form id="form1" name="form1" method="POST" action="php/saveuser2.php">
<div class="table5">
<font style="font-weight:bold">REGISTER USER</font>
<ul>
<p>
Nama: <input type="text" name="name" />*
<?php echo $name;?>
</p>
<p>
Matric No: <input type="text" name="matric" />*
<?php echo $matricErr;?>
</p>
<p>
Password: <input type="text" name="pass" />*
<?php echo $passErr;?>
</p>
<p>
User Category: <select name="cat" id="user_category">
<option>Staff</option>
<option>Student</option>
</select>*
<?php echo $catErr;?>
</p>
<div class="buttn1">
<p>
<input name="add" type="submit" onClick="Adduser()" value="Add" />
</p>
</div>
</ul>
</div>
</form>
</div>
<div class= "Bfooter">
<h4></h4>
</div>
</div>
</body>
and this my PHP file
<?php
$con = mysql_connect("localhost","root","1234");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("vronline", $con);
$nameErr = $matricErr = $passErr = $catErr = "";
$name = $matric = $pass = $cat = "";
$sql="INSERT INTO user_information(user_id, user_password, name, user_category)
VALUES
('$_POST[user_id]','$_POST[user_password]','$_POST[name]','$_POST[user_category]')";
if ($sql["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_id"])) {
$matricErr = "Please insert matric no!";
} else {
$matric = $_POST[user_id];
}
if (empty($_POST["user_password"])) {
$passErr = "Please insert password!";
}else {
$pass = $_POST[user_password];
}
if (empty($_POST["name"])) {
$name = "Please insert name!";
}else {
$name = $_POST[name];
}
if (empty($_POST["user_category"])) {
$catErr = "Please choose category";
} else{
$cat = $_POST[user_category];
}
}
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header("location:../adminMuser.php");
mysql_close($con)
?>
</body>
</html>
i cant make it work to show the error, which part i make it wrong?
Here is an approach, to validate using PHP
session_start();
$is_valid = false;
$error = array();
if (empty($_POST["user_id"]) || !isset($_POST["user_id"])) {
$error[] = "Please insert matric no!";
}
if (empty($_POST["user_password"]) || !isset($_POST["user_password"])) {
$error[] = "Please insert password!";
}
if (empty($_POST["name"]) || !isset($_POST["name"])) {
$error[] = "Please insert name";
}
if (empty($_POST["user_category"]) || !isset($_POST["user_category"])) {
$error[] = "Please choose category";
}
$is_valid = (count($error) == 0);
if($is_valid){
$con = mysql_connect("localhost","root","1234", "vronline");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$sql=sprintf("INSERT INTO user_information(user_id, user_password, name, user_category)
VALUES('%s','%s','%s','%s')",
$_POST['user_id'],$_POST['user_password'],$_POST['name'],$_POST['user_category']);
mysql_query($sql,$con) or die('Error: ' . mysql_error();
mysql_close($con)
header("location:../adminMuser.php");
}else{
$_SESSION['errors'] = $error;
//you can redirect back to the form to here
}
Then on your forms, you should check if the session is set, and print the errors if any:
session_start();
$errors = $_SESSION['errors'];
foreach($errors as $error){
echo "<p> Error = ".$error."</p>";
}
Please note:
While validation using PHP required, but you should validate on the client side as well.
Good practice wants you to validate using javascript or jquery.
It is a waste to send request to your server when they are not valid/complete.
Nowadays it is even easier with HTML5 validation attributes.
For example:
<input type="text" name="username" required>
Related
Hi i have a registration form in my website.if the particular field in the db is null then the form should not be displayed to the user.Here if the payment_category_upload field is empty then the form should not displayed to the user otherwise the form should be displayed.
<?php include 'includes/db.php';
$sql = "SELECT * FROM users WHERE username = '$_SESSION[user]' AND user_password = '$_SESSION[password]' AND payment_category_upload!='' ";
$oppointArr =array();
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0)
{
if(isset($_POST['submit_user'])|| isset($_POST['save_users']))
{
$formsubmitstatus = isset($_POST['submit_user'])?1:0;
if($_FILES["affidavits_upload"]["tmp_name"]!="")
{
$pname = rand(1000,10000)."-".str_replace("-"," ",$_FILES["affidavits_upload"]["name"]);
$affidavits_upload = $_FILES["affidavits_upload"]["tmp_name"];
$uploads_dir = '../admin/images/uploads';
move_uploaded_file($affidavits_upload, $uploads_dir.'/'.$pname);
}
else
{
$pname = $_POST['hid_affidavits_upload'];
}
$id= $_POST['users_id'];
$ins_sql = "UPDATE users set affidavits_upload='$pname',status='3',affidavitsupload_submit_status='$formsubmitstatus' WHERE users_id = $id";
$run_sql = mysqli_query($conn,$ins_sql);
$msg = 'Your Application successfully submitted. ';
$msgclass = 'bg-success';
}
else
{
$msg = 'Record Not Updated';
$msgclass = 'bg-danger';
}
}
else
{
echo "Please make the payment to enable Affidavits";
}
?>
FORM :
<form class="form-horizontal" action="affidavits.php" method="post" role="form" enctype="multipart/form-data" id="employeeeditform">
<?php if(isset($msg)) {?>
<div class="<?php echo $msgclass; ?>" id="mydiv" style="padding:5px;"><?php echo $msg; ?></div>
<?php } ?>
<input type='hidden' value='<?=$id;?>' name='users_id'>
<div class="form-group">
<label for="affidavits_upload" class="col-sm-4 control-label">Affidavits Upload</label>
<div class="col-sm-8">
<input type="hidden" value="<?php echo $oppointArr['affidavits_upload'];?>" name="hid_payment_category_upload">
<input type="file" name="affidavits_upload" id="affidavits_upload">
<?php if(!empty($oppointArr['affidavits_upload'])){?>
<div>
<?php echo $oppointArr['affidavits_upload'];?>
</div>
<?php }?>
<span class="text" style="color:red;">Please upload PDF Format Only</span>
</div>
</div>
<div class="col-sm-offset-2">
<?php if($oppointArr['affidavitsupload_submit_status'] == 0){ ?>
<button type="submit" class="btn btn-default" name="save_users" id="save_users">Save</button>
<button type="submit" class="btn btn-default" name="submit_user" id="subject">Submit Application</button>
<?php } ?>
</div>
</form>
//Add this Css class
.hiddenBlock {
display:none
}
<div class="<?php echo isset(test_field)?"":"hiddenBlock"; ?>">
<form>...<form>
</div>
You can do it like this for your field.
i am trying to make a simple login system, with password recovery option,, so i made a password reset link.
hwoever, it is not working, meaning that form2's button just leads back to form1 (leads back to username and email form && i have three different forms), so i separated it into three different if statements, for each button clicked, but the same issue keeps on happening.
please tell me what is happening and ho to fix it
thank you.
(code is below)
//not actually js, but is php
session_start();
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
header("Location: changepass.php");
}
if(($_SERVER["REQUEST_METHOD"] == "POST")) {
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "test";
$con = new mysqli($dbhost, $dbuser, $dbpass, $db) or die("Connection failed: %s\n". $con -> error);
$GLOBALS['email'] = $_POST['email'];
$GLOBALS['username'] = $_POST['username'];
$result = mysqli_query($con,"SELECT * FROM login WHERE email='" . htmlspecialchars($GLOBALS['email']) . "' and username = '". htmlspecialchars($GLOBALS['username'])."'");
$count = mysqli_num_rows($result);
//Part 1
if($_POST['submit1']) {
if($count==0) {
echo "<script>
document.getElementById('error').innerHTML += 'Invalid Username or Email.';
</script>";
} else {
echo "<script>
document.getElementById('main').style.display = 'none';
</script>";
echo "<script>
document.getElementById('next').style.display = 'inline-block';
</script>";
echo "<script>
document.getElementById('verify').innerHTML += 'A verification email has been sent to you. Copy the verification code and paste it above.';
</script>";
$GLOBALS['token'] = bin2hex(random_bytes(3));
echo $GLOBALS['token'];
$to = $GLOBALS['email'];
$subject = "Password Reset";
$msg = "Hello. Your token is <strong>" . $GLOBALS['token'] . "</strong>. <br>Good day.";
$msg = wordwrap($msg,70);
$headers = "From: email#example.com";
mail($to, $subject, $msg, $headers);
}
}
//Part 2
if($_POST['submit2']) {
if($_POST['code'] != $GLOBALS['token']) {
echo "<script>
document.getElementById('error2').innerHTML += 'Invalid verification code.';
</script>";
} else {
echo "<script>
document.getElementById('next').style.display = 'none';
</script>";
echo "<script>
document.getElementById('final').style.display = 'inline-block';
</script>";
}
}
//Part 3
if($_POST['submit3']) {
$np = $_POST['np'];
$cnp = $_POST['cnp'];
if($np != $cnp) {
echo "<script>
document.getElementById('error3').innerHTML += 'Passwords do not match.';
</script>";
} else {
$sql = "UPDATE login SET password='$cnp' WHERE email=" . $GLOBALS['email'];
$rs = mysqli_query($con, $sql);
if($rs) {
echo "Changed password successfully! Click <a href='login.php'>here</a> to sign in.";
} else {
echo "An unknown error occurred. Please try again.";
}
}
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reset Password</title>
</head>
<body>
<fieldset>
<legend>Reset Password</legend>
<form name="frmContact" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="main">
<label for="email">Email</label>
<input type="email" style="display:inline-block" name="email" id="email" required autofocus />
<br>
<br>
<label for="username">Username</label>
<input type="text" style="display:inline-block" name="username" id="username" required />
<br>
<p id="error" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit1" id="submit1" value="Reset Password" /> Create an Account Sign in
</p>
</div>
</form>
<form name="frmContact2" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="next" style="display:none;">
<p id="verify" style="color:green"></p>
<label for="code">Verification Code</label>
<input type="text" style="display:inline-block" maxlength="6" name="code" id="code" required autofocus /> <p style="color:red;display:inline-block" id="validatecode"></p>
<br>
<p id="error2" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit2" id="submit2" value="Reset Password" /> Create an Account Sign in
</p>
</div>
</form>
<form name="frmContact3" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="final" style="display:none;">
<label for="np">New Password</label>
<input type="text" style="display:inline-block" name="np" id="np" required autofocus /> <p style="color:red;display:inline-block" id="validatenp"></p>
<br>
<label for="cnp">Confirm New Password</label>
<input type="text" style="display:inline-block" name="cnp" id="cnp" required autofocus /> <p style="color:red;display:inline-block" id="validatecnp"></p>
<br>
<p id="error3" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit3" id="submit3" value="Reset Password" />
</p>
</div>
</form>
</fieldset>
</body>
</html>
Just for sake of debugging remove all extra stuff from that file and focus on 3 if statements
Also try using
if(isset($_POST['submit1']))
Always try to close in onto the problem at hand and remove extra stuff that is in there. It helps make simpler but better decisions.
I've got this wordpress site with a custom post type, called reviews, loop and a contact form on a page. When I click on the submit button on the contact page, reguardless if the form contents matches the regex, it redirects the page to /reviewa/random name
I've removed the "reviews" part of the website and the form works.
What I would like to happen is to have the form send the email, without redirecting the site to /reviews/randomName
$(function() {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
$('#contact-form').submit(function(e) {
$clientName = $("#contactName").val();
var valid = true;
// Remove any confirmation messages
$('p.confirmation').remove();
// Validate all fields that have a class of .required-field
$('.required-field').each(function() {
// Remove error class from all inputs and textareas and delete error messages before checking form again
$(this).removeClass('error').next('p').remove();
if ($(this).val().trim() === '' && $(this).attr('id') != 'email') {
$(this).addClass('error').parent().append('<p class="error">Please enter a ' + $(this).prev().html().toLowerCase() + '</p>');
valid = valid && false;
} else if ($(this).attr('id') === 'email') {
if (!$(this).val().trim().match(re)) {
$(this).addClass('error').parent().append('<p class="error">Please enter a valid email address</p>');
valid = valid && false;
}
}
});
if (valid) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function(data) {
$('#contact-form').before('<p class="confirmation">Thanks ' + $clientName + ', your email was successfully sent. We will be in touch soon.</p>');
_gaq.push(['_trackEvent', 'Contact form', 'Contact form submitted']);
});
}
e.preventDefault();
});
});
<div id="reviews">
<h2>Our reviews</h2>
<div id="slider" class="flex-container">
<div class="flexslider">
<ul class="slides">
<?php $new = new WP_Query('post_type=reviews& posts_per_page=-1');
while ($new->have_posts()) : $new->the_post(); ?>
<li>
<?php echo the_post_thumbnail('portfolio-thumb');?>
<span class="review"> <?php the_content(); ?></span>
<span class="name"> <?php the_title(); ?></span>
</li>
<?php endwhile;?>
</ul>
</div>
</div>
</div>
<div id="contact">
<h2>To contact the instructor, plese enter your details below</h2>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['submitted'])){
//Check name
if(trim($_POST['contactName']) === '') {
$nameError = true;
$hasError = true;
}else{
$name = trim($_POST['contactName']);
}
//Check company name
if(trim($_POST['companyName']) === '') {
$companyNameError = true;
$companyNameError = true;
}else{
$companyName = trim($_POST['companyName']);
}
//Check address
if(trim($_POST['address']) === '') {
$addressError = true;
$addressError = true;
}else{
$address = trim($_POST['address']);
}
// Check email address exists and is valid
if(trim($_POST['email']) === '') {
$emailError = 'Please enter your email address.';
$hasError = true;
}else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+.[A-Z]{2,4}$",trim($_POST['email']))){
$emailError = 'You entered an invalid email address.';
$hasError = true;
}else{
$email = trim($_POST['email']);
}
if(trim($_POST['telNumber']) === '') {
$telError = true;
$hasError = true;
}else{
$telephone = trim($_POST['telNumber']);
}
//Check message
if(trim($_POST['message']) === ''){
$messageError = true;
$hasError = true;
}else{
$message = stripslashes(trim($_POST['message']));
}
//If there is no error, send the email
if(!isset($hasError)){
$emailTo = 'randomEmail#mail.com';
$subject = 'Contact from the Contact Us page';
$body = "Name: $name \n Email: $email \n Telephone: $telephone \n Poxtcode: $address . \n Message:\n$message";
$headers = 'From: randomWebsite.com, <'.$emailTo.'>' . "\n" . "\n" .'Reply-To: ' . $email;
ssmtp($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php if($emailSent == true) { ?>
<p class="confirmation">Thanks,
<?php echo $name;?>, your email was successfully sent. We will be in touch soon.</p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contact-form" method="post" novalidate>
<ul>
<li>
<input type="text" placeholder="Name (required)" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])){echo $_POST['contactName'];} ?>" class="required-field" />
<?php if($nameError) { ?>
<p class="error">Please enter your name.</p>
<?php } ?>
</li>
<li>
<input type="text" placeholder="Postcode (required)" name="address" id="address" value="<?php if(isset($_POST['address'])){echo $_POST['address'];} ?>" class="required-field" />
<?php if($addressError) { ?>
<p class="error">Please enter your postcode.</p>
<?php } ?>
</li>
<li>
<input type="tel" placeholder="Mobile number (required)" name="telNumber" id="telNumber" value="<?php if(isset($_POST['telNumber'])){echo $_POST['telNumber'];} ?>" />
<?php if($telError) { ?>
<p class="error">Please enter your mobile number.</p>
<?php } ?>
</li>
<li>
<input type="email" placeholder="Email (required)" name="email" id="email" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" class="required-field" />
<?php if($emailError) { ?>
<p class="error">
<?php echo $emailError;?>
</p>
<?php } ?>
</li>
<li class="textarea">
<textarea name="message" placeholder="Message (required)" id="message" rows="20" cols="30" class="required-field"><?php if(isset($_POST['message'])){echo stripslashes($_POST['message']);} ?></textarea>
<?php if($messageError) { ?>
<p class="error">Please enter a message.</p>
<?php } ?>
</li>
<li>
<input type="hidden" id="submitted" name="submitted" />
<button class="button" ">Send</button>
</li>
</ul>
</form>
</div>
`
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
if (!preg_match("/^\w+$/",$username)) {
$error = true;
$username_error = "Username cant contain space and special characters";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
$result = mysqli_query($connection, "SELECT * FROM users WHERE username = '" . $username. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
if ($row['id'] == 1) {
header("Location: priv8/ididthis.php");
} else if ($row['id'] >= 1) {
header("Location: index.php");
} else {
$errormsg = "Incorrect username or Password!";
}
can u see what's wrong with my code ? the $errormsg doesn't showing when the username or the password is wrong..
`
<body>
<div class="layout">
<div class="layout-screen">
<div class="app-title">
<h1>Login</h1>
</div>
<div class="layout-form">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div class="control-group">
<input type="text" name="username" class="login-field" value="" placeholder="username" id="login-username">
<label class="login-field-icon fui-user" for="login-username"></label>
</div>
<div class="control-group">
<span><?php if (isset($username_error)) { echo $username_error; } ?></span>
</div>
<div class="control-group">
<input type="password" name="password" class="login-field" value="" placeholder="password" id="login-pass">
<label class="login-field-icon fui-lock" for="login-pass"></label>
</div>
<div class="control-group">
<span><?php if (isset($password_error)) { echo $password_error; } ?></span>
</div>
<div class="control-group">
<input class="btn btn-primary btn-large btn-block" type="submit" name="login" value="Sign in"/>
</div>
</form>
<span><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
<a class="layout-link" href="forgot.php">Lost your password?</a>
</div>
</div>
</div>
The problem is that your error message is inside this block
if ($row = mysqli_fetch_array($result)){
if ($row['id'] == 1) {...}
else if ($row['id'] >= 1) {...}
else {
$errormsg = "Incorrect username or Password!";
}
}
This means that the error message is never shown because row id will always be 1 or >=1. To fix, move the error message out, like this:
if ($row = mysqli_fetch_array($result)){
if ($row['id'] == 1) {...}
else($row['id'] >= 1) {...}
}
else {
$errormsg = "Incorrect username or Password!";
}
I make a login page like user login. if registered then login with email and password(navigate register.php to index.php page) or sign up if not registered. works good but i want to add update functionality in my index.php page concept is simple if user wants to update its record then he make updations in a form and submit. I make a update query here but its shows Notice: Undefined index: id in C:\wamp\www\LOginKodingMadSimple\index.php on line 34. Where i am wrong ?
index.php :
<?php
session_start();
include_once 'dbconnect.php';
?>
<?php
if (isset($_POST['UpdateUser']))
{
$name = mysqli_real_escape_string($con, $_POST['name']);
$id = mysqli_real_escape_string($con, $_POST['id']);
//------- name can contain only alpha characters and space -------
if (!preg_match("/^[a-zA-Z ]+$/",$name))
{
$error = true;
$name_error = "Name must contain only alphabets and space";
}
//------- Update users -------
if (!$error)
{
if(mysqli_query($con, "UPDATE users SET name='" . $name . "' WHERE id='" . $id . "'"))
{
$successmsg = "Successfully Updated! ";
}
else
{
$errormsg = "Error in Update...Please try again later!";
}
}
}
else
{
$errormsg = "Failed Please Try Again Later !";
}
?>
<div class="collapse navbar-collapse" id="navbar1">
<ul class="nav navbar-nav navbar-right">
<?php if (isset($_SESSION['usr_id'])) { ?>
<li>
<p class="navbar-text">Signed in as <?php echo $_SESSION['usr_name']; ?></p>
<a class="navbar-brand" href="updatephp.php">Update</a>
</li>
<li>
Log Out
</li>
<div style="border:1px dashed transparent;margin-top:400px;position:absolute;margin-left:-35%;">
<h1> Hello User <?php echo $_SESSION['usr_name']; ?> ! </h1>
<h1> Your Email is <?php echo $_SESSION['usr_email']; ?> ! </h1>
<form action="" method="post">
Name: <input type="text" name="name" placeholder="<?php echo $_SESSION['usr_name']; ?>"><br>
<input type="submit" value="Update" name="UpdateUser">
</form>
</div>
<?php } else { ?>
<li>Login</li>
<li>Sign Up</li>
<?php } ?>
</ul>
</div>
add input hidden field with id like.
<input type="hidden" name="id" value="<?php echo $_SESSION['usr_id'];?>">
[NOTE: You don't have any textbox named as id.]
Choose any way.
Way 1)
Change
$id = mysqli_real_escape_string($con, $_POST['id']);
To
$id = $_SESSION['usr_id'];
Updated Code:
<?php
if (isset($_POST['UpdateUser'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$id = $_SESSION['usr_id'];
Way 2)
Add one hidden input field having value session usr_id.
<form action="" method="post">
Name: <input type="text" name="name" placeholder="<?php echo $_SESSION['usr_name']; ?>"><br>
<input type='hidden' value="<?php echo $_SESSION['usr_id'];?>" name='id'>
<input type="submit" value="Update" name="UpdateUser">
</form>
In this way, your submitting form code will be same as you are having.
Use below function to hide the error notice :
error_reporting(0);