Undefined Variable on this tutorial on PHP with Bootstrap - php

Please help me fix this undefined variable I copy and pasted this code on my create.php and when i hit the create button on the home page i get this:
Notice: Undefined variable: fnameError in
C:\xampp\htdocs\TestCRUD\create.php on line 70
Notice: Undefined variable: lnameError in
C:\xampp\htdocs\TestCRUD\create.php on line 75
Notice: Undefined variable: ageError in
C:\xampp\htdocs\TestCRUD\create.php on line 80
Notice: Undefined variable: genderError in C:\xampp\htdocs\TestCRUD\create.php on line 89
<?php
if ( !empty($_POST)) {
require 'db.php';
// validation errors
$fnameError = null;
$lnameError = null;
$ageError = null;
$genderError = null;
// post values
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$gender = $_POST['gender'];
// validate input
$valid = true;
if(empty($fname)) {
$fnameError = 'Please enter First Name';
$valid = false;
}
if(empty($lname)) {
$lnameError = 'Please enter Last Name';
$valid = false;
}
if(empty($age)) {
$ageError = 'Please enter Age';
$valid = false;
}
if(empty($gender)) {
$genderError = 'Please select Gender';
$valid = false;
}
// insert data
if ($valid) {
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (fname,lname,age,gender) values(?, ?, ?, ?)";
$stmt = $PDO->prepare($sql);
$stmt->execute(array($fname,$lname,$age,$gender));
$PDO = null;
header("Location: index.php");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="row">
<h3>Create a User</h3>
</div>
<form method="POST" action="">
<div class="form-group <?php echo !empty($fnameError)?'has-error':'';?>">
<label for="inputFName">First Name</label>
<input type="text" class="form-control" required="required" id="inputFName" value="<?php echo !empty($fname)?$fname:'';?>" name="fname" placeholder="First Name">
<span class="help-block"><?php echo $fnameError;?></span>
</div>
<div class="form-group <?php echo !empty($lnameError)?'has-error':'';?>">
<label for="inputLName">Last Name</label>
<input type="text" class="form-control" required="required" id="inputLName" value="<?php echo !empty($lname)?$lname:'';?>" name="lname" placeholder="Last Name">
<span class="help-block"><?php echo $lnameError;?></span>
</div>
<div class="form-group <?php echo !empty($ageError)?'has-error':'';?>">
<label for="inputAge">Age</label>
<input type="number" required="required" class="form-control" id="inputAge" value="<?php echo !empty($age)?$age:'';?>" name="age" placeholder="Age">
<span class="help-block"><?php echo $ageError;?></span>
</div>
<div class="form-group <?php echo !empty($genderError)?'has-error':'';?>">
<label for="inputGender">Gender</label>
<select class="form-control" required="required" id="inputGender" name="gender" >
<option></option>
<option value="male" <?php echo $gender == 'male'?'selected':'';?>>Male</option>
<option value="female" <?php echo $gender == 'female'?'selected':'';?>>Female</option>
</select>
<span class="help-block"><?php echo $genderError;?></span>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn btn-default" href="index.php">Back</a>
</div>
</form>
</div> <!-- /row -->
</div> <!-- /container -->
</body>
</html>

You're displaying errors even when the variables haven't been set. That brings up the notice you see. You can avoid them by checking if they are set first using isset or empty
<?= isset($someError) ? $someError : '' ?>

use isset();
// post values
$fname = isset($_POST['fname']);
$lname = isset($_POST['lname']);
$age = isset($_POST['age']);
$gender = isset($_POST['gender']);

On the lines like the following, you need to check that the variables have a value before trying to use them. So the following code...
<span class="help-block"><? echo $fnameError; ?></span>
...should be changed to this:
<span class="help-block"><?= isset($fnameError) ? $fnameError : ''; ?></span>
To prevent these errors being picked up and displayed you could also turn PHP error reporting off but fixing the problem is preferable:
<?php
error_reporting('off');
ini_set('display_errors', 'off');

You can added a hidden type input to form for process after send parameters:
PHP:
<?php
if (isset($_POST['h'])) {
....//your process
}
?>
HTML:
<form action="" method="POST">
.....<!--your input-->
<input type="hidden" name="h" value="true">
<button type="submit"> submit </button>
</form>

Related

How to return errors array from a function to form page

I have created a function to register users in my application. which processes the form. validate inputs etc. but I'm having a problem displaying errors in the form. I'm not able to return $errors array to the form to display errors. can someone help with this? please!
Form
<?php register_user(); ?>
<form action="signup.php" method="post">
<div class="form-group mb-3">
<input type="email" name="email" value="<?php if (isset($email)) echo $email; ?>" placeholder="Enter your email" class="form-control form-control-lg <?php echo isset($errors['email']) ? 'is-invalid' : '' ?>" required>
<div class="invalid-feedback"><?php echo $errors['email'] ?? ''; ?></div>
</div>
<div class="form-group mb-3">
<input type="text" name="username" value="<?php if (isset($username)) echo $username; ?>" placeholder="Choose a Username" maxlength="15" class="form-control form-control-lg <?php echo isset($errors['username']) ? 'is-invalid' : '' ?>" required>
<div class="invalid-feedback"><?php echo $errors['username'] ?? ''; ?></div>
</div>
<div class="form-group mb-3">
<input type="password" name="password" placeholder="Choose a Password" class="form-control form-control-lg <?php echo isset($errors['password']) ? 'is-invalid' : '' ?>" required>
<div class="invalid-feedback"><?php echo $errors['password'] ?? ''; ?></div>
</div>
<div class="form-group mb-3">
<?php $countries = find_all('countries'); ?>
<select name="country" class="form-control" required>
<option value="">Select a country...</option>
<?php while($country = mysqli_fetch_assoc($countries)) { ?>
<option value="<?php echo h($country['country_id']); ?>"><?php echo h($country['name']); ?></option>
<?php } ?>
</select>
<div class="invalid-feedback"><?php echo $errors['country'] ?? ''; ?></div>
</div>
<p class="splash-description mt-3">By joining, you agree to Cointerr's Terms of Service.</p>
<input type="submit" value="Join" name="signup-submit" class="btn btn-block btn-primary">
</form>
Register Function
function register_user() {
if (is_post_request() && isset($_POST['signup-submit'])) {
if(isset($_POST['email'])) $email = $_POST['email'];
if(isset($_POST['username'])) $username = $_POST['username'];
if(isset($_POST['password'])) $password = $_POST['password'];
if(isset($_POST['country'])) $country = $_POST['country'];
// validate
if (is_blank($email) || !has_valid_email_format($email)) $errors['email'] = 'Looks like this email is incomplete.';
if (is_blank($username)) $errors['username'] = 'Username must begin with a letter and can include numbers and underscores.';
if (!has_length_exactly($username, 6)) $errors['username'] = 'Username must include at least 6 characters.';
if (is_blank($password) || !has_length_exactly($password, 8)) $errors['password'] = 'Password must be min 8 characters.';
if (is_blank($country)) $errors['country'] = 'Please select your country!';
if (!empty($errors)) {
return $errors;
} else {
// Register user
}
}
}
You are returning the errors:
return $errors;
However, the code on the page is ignoring that result:
<?php register_user(); ?>
Set the result to a variable that you can use:
<?php $errors = register_user(); ?>
Which you then already later attempt to use:
<?php echo $errors['email'] ?? ''; ?>
Assign registerUser() to a variable:
<?php $errors = registerUser(); ?>
You should also check that the error key exists in the errors array.

when click php in my domain [duplicate]

This question already has answers here:
Apache is downloading php files instead of displaying them
(27 answers)
Closed 5 years ago.
i'm having a problem to my website when i'm clicking it , its just downloading and not even loading for the next page. what can i do? what should i change? i'm just a newbie in html and php , by the way the file i was click is a php file that i made and it is not directing to next page the file was downloading when i click that php file. i was wondering if someone help me here , thanks in advance for someone who might help me. it is just for my project. http://itweb.bitballoon.com/
this is the website when i'm clicking the sign and register it will download the file of php i dont know how to solve this problem i search already in youtube and google. i cant see a single answer. someone help me please thanks.
codes of register.php
<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';
$error = false;
if ( isset($_POST['btn-signup']) ) {
// clean user inputs to prevent sql injections
$firstname = trim($_POST['firstname']);
$firstname = strip_tags($firstname);
$firstname = htmlspecialchars($firstname);
$middlename = trim($_POST['middlename']);
$middlename = strip_tags($middlename);
$middlename = htmlspecialchars($middlename);
$lastname = trim($_POST['lastname']);
$lastname = strip_tags($lastname);
$lastname = htmlspecialchars($lastname);
$student_number = trim($_POST['student_number']);
$student_number = strip_tags($student_number);
$student_number = htmlspecialchars($student_number);
$course = $_POST['course'];
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// basic name validation
if (empty($firstname)) {
$error = true;
$firstnameError = "Please enter your firstname.";
} else if (strlen($firstname) < 2) {
$error = true;
$firstnameError = "Firstname must have atleat 2 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$firstname)) {
$error = true;
$firstnameError = "Firstname must not contain numbers or special characters.";
}
if (!empty($middlename) && !preg_match("/^[a-zA-Z ]+$/",$middlename)) {
$error = true;
$middlenameError = "Middlename must not contain numbers or special characters.";
}
if (empty($lastname)) {
$error = true;
$lastnameError = "Please enter your lastname.";
} else if (strlen($lastname) < 2) {
$error = true;
$lastnameError = "Lastname must have atleat 2 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$lastname)) {
$error = true;
$lastnameError = "Lastname must not contain numbers or special characters.";
}
if (empty($course)) {
$error = true;
$courseError = "Please select a course.";
}
if (empty($student_number)) {
$error = true;
$student_numberError = "Please enter your student number.";
} else if (!(strlen($student_number) >= 12 && strlen($student_number) <= 13)) {
$error = true;
$student_numberError = "Student number must have atleat 12 characters.";
} else if (!preg_match("/^PM-[0-9]{2}-[0-9]{4,5}-[AB]$/", $student_number)) {
$error = true;
$student_numberError = "Invalid student number format.";
} else {
//check if student number exists
$result = mysql_query("SELECT * FROM users WHERE student_number = '$student_number'");
$rowCount = mysql_num_rows($result);
if ($rowCount == 1) {
$error = true;
$student_numberError = "Student number is already taken.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}
// password encrypt using SHA256();
$password = hash('sha256', $pass);
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO users(student_number,userPass,user_role,firstname,middlename,lastname,course) VALUES('$student_number','$password',2,'$firstname','$middlename','$lastname',$course)";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now.";
unset($firstname);
unset($middlename);
unset($lastname);
unset($course);
unset($student_number);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="assets/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#course').change(function () {
if ($(this).val() == '') {
$(this).css('color', '#999');
}
else {
$(this).css('color', '#000');
}
$('option').css('color', '#000');
});
$('#course').trigger('change');
});
</script>
</head>
<body>
<div class="container">
<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<div class="col-md-12">
<div class="form-group">
<h2 class="">Sign Up.</h2>
</div>
<div class="form-group">
<hr />
</div>
<?php
if ( isset($errMSG) ) {
?>
<div class="form-group">
<div class="alert alert-<?php echo ($errTyp=="success") ? "success" : $errTyp; ?>">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
</div>
</div>
<?php
}
?>
<div class="form-group">
<div class="input-group ">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="firstname" class="form-control" placeholder="Firstname" maxlength="50" value="<?php echo $firstname ?>" />
</div>
<span class="text-danger"><?php echo $firstnameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="middlename" class="form-control" placeholder="Middlename" maxlength="50" value="<?php echo $middlename ?>" />
</div>
<span class="text-danger"><?php echo $middlenameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="lastname" class="form-control" placeholder="Lastname" maxlength="50" value="<?php echo $lastname ?>" />
</div>
<span class="text-danger"><?php echo $lastnameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-book"></span></span>
<select id="course" name="course" class="form-control">
<option <?php echo $course == "1" ? "selected" : "" ?> value="1">BSIT</option>
<option <?php echo $course == "2" ? "selected" : "" ?> value="2">BSBA</option>
<option <?php echo $course == "3" ? "selected" : "" ?> value="3">BSTM</option>
<option <?php echo $course == "4" ? "selected" : "" ?> value="4">BSHRM</option>
<option <?php echo $course == "5" ? "selected" : "" ?> value="5">BSN</option>
<option <?php echo $course == "6" ? "selected" : "" ?> value="6">BSC</option>
<option <?php echo $course == "7" ? "selected" : "" ?> value="7">BSA</option>
<option <?php echo $course == "8" ? "selected" : "" ?> value="8">BSE</option>
<option <?php echo $course == "9" ? "selected" : "" ?> value="9">ABMC</option>
<option <?php echo $course == "10" ? "selected" : "" ?> value="10">BSP</option>
<option <?php echo $course == "11" ? "selected" : "" ?> value="11">BAPA</option>
</select>
</div>
<span class="text-danger"><?php echo $courseError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="student_number" class="form-control" placeholder="Student Number" maxlength="50" value="<?php echo $student_number ?>" />
</div>
<span class="text-danger"><?php echo $student_numberError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" name="pass" class="form-control" placeholder="Password" maxlength="15" />
</div>
<span class="text-danger"><?php echo $passError; ?></span>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-signup">Sign Up</button>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
Sign in Here...
</div>
</div>
</form>
</div>
</div>
</body>
</html>
<?php ob_end_flush(); ?>
Sign in codes :
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if ( isset($_SESSION['user'])!="" ) {
header("Location: home.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$student_number = trim($_POST['student_number']);
$student_number = strip_tags($student_number);
$student_number = htmlspecialchars($student_number);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($student_number)){
$error = true;
$student_number_Error = "Please enter your student number.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT student_number, userPass, user_role, firstname, middlename, lastname, course FROM users WHERE student_number = '$student_number'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['student_number'];
header("Location: home.php");
echo $_GET['id'];
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="container">
<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<div class="col-md-12">
<div class="form-group">
<h2 class="">Sign In.</h2>
</div>
<div class="form-group">
<hr />
</div>
<?php
if ( isset($errMSG) ) {
?>
<div class="form-group">
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
</div>
</div>
<?php
}
?>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="student_number" class="form-control" placeholder="Student Number" value="<?php echo $student_number; function a(){$student_number=$idc;}?>" maxlength="15" />
</div>
<span class="text-danger"><?php echo $student_number_Error; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" name="pass" class="form-control" placeholder="Password" maxlength="30" />
</div>
<span class="text-danger"><?php echo $passError; ?></span>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
Sign Up Here...
</div>
</div>
</form>
</div>
</div>
</body>
</html>
<?php ob_end_flush(); ?>
Error message is: Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /storage/ssd5/266/3359266/public_html/dbconnect.php:11 Stack trace: #0 /storage/ssd5/266/3359266/public_html/login.php(4): require_once() #1 {main} thrown in /storage/ssd5/266/3359266/public_html/dbconnect.php on line 11
You need to check with the website hosting server whether it support PHP. And check is it configured correctly in the server.

How to add another column for php without getting undefined index error?

Whenever I try to add additional code for additional column, I still got the error of undefined index, although I got it once..The second try was a fail, and it took me a really long time to figure this one out..I did add the column in the database first..For instance, I need to add the keyword column.
<?php
require 'database.php';
if (isset($_GET)) {
// keep track validation errors
$titleError = null;
$authorError = null;
$date_createdError = null;
$abstractError = null;
// keep track post values
$title = $_POST['title'];
$author = $_POST['author'];
$date_created = $_POST['date_created'];
$abstract = $_POST['abstract'];
// validate input
$valid = true;
if (empty($title)) {
$titleError = 'Please enter title';
$valid = false;
}
if (empty($author)) {
$authorError = 'Please enter author name(s)';
$valid = false;
}
if (empty($date_created)) {
$date_createdError = 'Please enter the Date';
$valid = false;
}
if (empty($abstract)) {
$abstractError = 'Please enter the research study abstract';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO archives (title,author,date_created,abstract) values(?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($title,$author,$date_created,$abstract));
Database::disconnect();
header("Location: main.php");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="span10 offset1">
<div class="row">
<h3>Add New Reserch Study</h3>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class="control-group <?php echo !empty($titleError)?'error':'';?>">
<label class="control-label">Title</label>
<div class="controls">
<span class="resizable-input">
<input name="title" type="text" id="inp" placeholder="Copy & paste complete research title here" value="<?php echo !empty($title)?$title:'';?>">
</span>
<?php if (!empty($titleError)): ?>
<span class="help-inline"><?php echo $titleError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($authorError)?'error':'';?>">
<label class="control-label">Author(s)</label>
<div class="controls">
<span class="resizable-input">
<input name="author" type="text" id="inp" placeholder="Copy & paste complete name(s) here..." value="<?php echo !empty($author)?$author:'';?>">
</span>
<?php if (!empty($authorError)): ?>
<span class="help-inline"><?php echo $authorError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($date_createdError)?'error':'';?>">
<label class="control-label">Date Received</label>
<div class="controls">
<input name="date_created" type="date" id="inp" placeholder="YYYY-MM-DD format only" value="<?php echo !empty($date_created)?$date_created:'';?>">
<?php if (!empty($date_createdError)): ?>
<span class="help-inline"><?php echo $date_createdError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($abstractError)?'error':'';?>">
<label class="control-label">Abstract</label>
<div class="controls">
<span class="resizable-input">
<input name="abstract" maxlength="2000" type="text" placeholder="Copy & paste the abstract here.." id="inp" value="<?php echo !empty($abstract)?$abstract:'';?>">
</span>
<?php if (!empty($abstractError)): ?>
<span class="help-inline"><?php echo $abstractError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="main.php">Back</a>
Sign Out
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>

How to update or delete data in php mysql

I created a table to view records from database, i am unable to update or delete, nothing happens if I click on the buttons they are just redirected without the changes..what can be done to fix this.
update.php
<?php
include 'includes/db.php';
//$student_id = null;
if ( !empty($_GET['student_id'])) {
$student_id = $_REQUEST['student_id'];
}
if ( null==$student_id ) {
header("Location: addstudent.php");
}
if ( !empty($_POST)) {
// keep track valstudent_idation errors
$first_nameError = null;
$middle_nameError = null;
$last_nameError = null;
$emailError = null;
$idcodeError = null;
// keep track post values
$first_name = $_POST['first_name'];
$middle_name = $_POST['middle_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$idcode = $_POST['idcode'];
// validate input
$valstudent_id = true;
if (empty($first_name)) {
$nameError = 'Please enter Name';
$valstudent_id = false;
}
$valstudent_id = true;
if (empty($middle_name)) {
$nameError = 'Please enter Name';
$valstudent_id = false;
}
$valstudent_id = true;
if (empty($last_name)) {
$nameError = 'Please enter Name';
$valstudent_id = false;
}
if (empty($email)) {
$emailError = 'Please enter Email Address';
$valstudent_id = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Please enter a valid Email Address';
$valstudent_id = false;
}
if (empty($idcode)) {
$idcodeError = 'Please enter IDCODE';
$valstudent_id = false;
}
// update data
if ($valstudent_id) {
$first_name=$_POST['first_name'];
$middle_name=$_POST['middle_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$idcode=$_POST["idcode"];
$sql = "UPDATE student SET first_name=:first_name, middle_name=:middle_name, last_name=:last_name, idcode=:idcode, email=:email WHERE student_id=:student_id";
$stmt = $pdo->prepare($sql);
//echo "<br/>Query: ".$stmt->query()."<br/>"
$stmt->bindValue(':first_name', $first_name);
$stmt->bindValue(':middle_name', $middle_name);
$stmt->bindValue(':last_name', $last_name);
$stmt->bindValue(':idcode', $idcode);
$stmt->bindValue(':email', $email);
$result= $stmt->execute();
//$result = execute(array($first_name,middle_name,last_name,$email,$idcode));
header("Location: table.php");
}
}
else {
$sql = "SELECT * FROM student where student_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($student_id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$first_name = $data['first_name'];
$middle_name = $data['middle_name'];
$last_name = $data['last_name'];
$idcode = $data['idcode'];
$email = $data['email'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update People</h3>
</div>
<form class="form-horizontal" action="update.php?student_id=<?php echo $student_id?>" method="post">
<div class="control-group <?php echo !empty($first_nameError)?'error':'';?>">
<label class="control-label">First Name</label>
<div class="controls">
<input name="first_name" type="text" placeholder="first_Name" value="<?php echo !empty($first_name)?$first_name:'';?>">
<?php if (!empty($first_nameError)): ?>
<span class="help-inline"><?php echo $middle_nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Middle Name</label>
<div class="controls">
<input name="middle_name" type="text" placeholder="middle_Name" value="<?php echo !empty($middle_name)?$middle_name:'';?>">
<?php if (!empty($middle_nameError)): ?>
<span class="help-inline"><?php echo $middle_nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Last Name</label>
<div class="controls">
<input name="last_name" type="text" placeholder="last_Name" value="<?php echo !empty($last_name)?$last_name:'';?>">
<?php if (!empty($last_nameError)): ?>
<span class="help-inline"><?php echo $lastnameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($emailError)?'error':'';?>">
<label class="control-label">Email Address</label>
<div class="controls">
<input name="email" type="text" placeholder="Email Address" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-inline"><?php echo $emailError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($idcodeError)?'error':'';?>">
<label class="control-label">IDCODE</label>
<div class="controls">
<input name="idcode" type="text" placeholder="IDCODE" value="<?php echo !empty($idcode)?$idcode:'';?>">
<?php if (!empty($idcodeError)): ?>
<span class="help-inline"><?php echo $idcodeError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="table.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
delete.php
<?php
error_reporting(1);
include 'includes/db.php';
$student_id = 0;
if ( !empty($_GET['student_id'])) {
$student_id = $_REQUEST['student_id'];
}
if ( !empty($_POST)) {
$id = $_POST['student_id'];
// delete data
$sql = "DELETE FROM people WHERE student_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($student_id));
header("Location: table.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Delete the Person</h3>
</div>
<form class="form-horizontal" action="delete.php" method="post">
<input type="hidden" name="student_id" value="<?php echo $student_id;?>"/>
<p class="alert alert-error">Are you sure to delete ?</p>
<div class="form-actions">
<button type="submit" class="btn btn-danger">Yes</button>
<a class="btn" href="table.php">No</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>

Bootstrap 'form-group has-error' not working with php codes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Inputs don't turn red and does not print the error messages when I'm submitting empty fields. How can I show the error messages and make the input boxes turn red when I'm sending empty fields with this code.
<?php
if ( !empty($_POST)) {
require 'db.php';
// validation errors
$fnameError = null;
$lnameError = null;
$ageError = null;
$genderError = null;
// post values
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$gender = $_POST['gender'];
// validate input
$valid = true;
if(empty($fname)) {
$fnameError = 'Please enter First Name';
$valid = false;
}
if(empty($lname)) {
$lnameError = 'Please enter Last Name';
$valid = false;
}
if(empty($age)) {
$ageError = 'Please enter Age';
$valid = false;
}
if(empty($gender)) {
$genderError = 'Please select Gender';
$valid = false;
}
// insert data
if ($valid) {
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (fname,lname,age,gender) values(?, ?, ?, ?)";
$stmt = $PDO->prepare($sql);
$stmt->execute(array($fname,$lname,$age,$gender));
$PDO = null;
header("Location: index.php");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="row">
<h3>Create a User</h3>
</div>
<form method="POST" action="create.php">
<div class="form-group <?php echo !empty($fnameError)?'has-error':'';?>">
<label for="inputFName">First Name</label>
<input type="text" class="form-control" required="required" id="inputFName" value="<?php echo isset($fname)?$fname:'';?>" name="fname" placeholder="First Name">
<span class="help-block"><?php echo isset($fnameError)?$fnameError:'';?></span>
</div>
<div class="form-group <?php echo !empty($lnameError)?'has-error':'';?>">
<label for="inputLName">Last Name</label>
<input type="text" class="form-control" required="required" id="inputLName" value="<?php echo isset($lname)?$lname:'';?>" name="lname" placeholder="Last Name">
<span class="help-block"><?php echo isset($lnameError)?$lnameError:'';?></span>
</div>
<div class="form-group <?php echo !empty($ageError)?'has-error':'';?>">
<label for="inputAge">Age</label>
<input type="number" required="required" class="form-control" id="inputAge" value="<?php echo isset($age)?$age:'';?>" name="age" placeholder="Age">
<span class="help-block"><?php echo isset($ageError)?$ageError:'';?></span>
</div>
<div class="form-group <?php echo !empty($genderError)?'has-error':'';?>">
<label for="inputGender">Gender</label>
<select class="form-control" required="required" id="inputGender" name="gender" >
<option></option>
<option value="male" <?php echo isset($gender)?'selected':'';?>>Male</option>
<option value="female" <?php echo isset($gender)?'selected':'';?>>Female</option>
</select>
<span class="help-block"><?php echo isset($genderError)?$genderError:'';?></span>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn btn btn-default" href="index.php">Back</a>
</div>
</form>
</div> <!-- /row -->
</div> <!-- /container -->
</body>
</html>
Note:
If a user submits the form with empty fields except for gender, it will return true and will go to your insert statement. It will overwrite the value of your $valid variable in every if() statement.
You can try this instead for assigning value on your $valid variable:
if(empty($fname) || empty($lname) || empty($age) || empty($gender)){
$valid = "false";
}
else {
$valid = "true";
}
Your form will return false also because of your required = "required" attribute on your input fields, so the form won't submit and you won't be able to see the result of your conditions.
Additional note:
You can also use javascript to achieve what you want without submitting the form
If you want a sample of javascript, I can give you an example.
First, we want to assign a unique id attribute for your divs, input fields and <span>. And we should hide first the error message inside your <span>
Here is an example of your First Name field:
<div class="form-group" id="firstnamediv">
<label for="inputFName">First Name</label>
<input type="text" class="form-control" id="firstnamefield" name="fname" placeholder="First Name">
<span class="help-block" id="firstnamespan" style="display:none">Please enter First Name</span>
</div>
Then create your javascript with. (Beware that javascript is case sensitive):
<script type="text/javascript">
function validateForm(){
var firstname = document.getElementById('firstnamefield').value;
if(firstname == ''){
document.getElementById('firstnamediv').className = 'form-group has-error';
document.getElementById('firstnamespan').style.display = 'block';
return false;
}
else if(firstname != ''){
document.getElementById('firstnamediv'.className = ''form-group has-success';
document.getElementById('firstnamespan').style.display = 'none';
}
}
</script>
Then, to call the javascript function we have created, we must set an onsubmit attribute on your <form>
<form method="POST" action="create.php" onsubmit="return validateForm();">

Categories