How to update or delete data in php mysql - php

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>

Related

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.

i dont know why the isset function is not working when i submit

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php
$con = mysql_connect('localhost', 'root','');
mysql_select_db ('product');
echo "Connected to database";
session_start();
?>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Register</title>
<script type="text/javascript" src="assets/js/bootstrap.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<link rel="stylesheet" href="reg.css" />
<!-- Google Fonts -->
<link href='https://fonts.googleapis.com/css?family=Passion+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Oxygen' rel='stylesheet' type='text/css'>
<script src="jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<table align="center">
<td>
<tr>
<div align="center" style="size:30%;" class="container">
<div class="row main" style="width:30%;">
<div class="panel-heading">
<div class="panel-title text-center">
<h1 class="title">Register Here</h1>
<hr />
</div>
</div>
<div class="main-login main-center">
<form class="form-horizontal" method="post" action="<?php
echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div align="left" class="form-group">
<label name="name" class="cols-sm-2 control-label">Your Name</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="name" placeholder="Enter your Name"/>
</div>
</div>
</div>
<div align="left" class="form-group">
<label name="email" class="cols-sm-2 control-label">Your Email</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="email" placeholder="Enter your Email"/>
</div>
</div>
</div>
<div align="left" class="form-group">
<label name="user_name" class="cols-sm-2 control-label">Username</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="user_name" placeholder="Enter your Username"/>
</div>
</div>
</div>
<div align="left" class="form-group">
<label name="password" class="cols-sm-2 control-label">Password</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
<input type="password" class="form-control" name="password" placeholder="Enter your Password"/>
</div>
</div>
</div>
<div align="left" class="form-group">
<label name="confirm_password" class="cols-sm-2 control-label">Confirm Password</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
<input type="password" class="form-control" name="confirm_password" placeholder="Confirm your Password"/>
</div>
</div>
</div>enter code here
<div align="left" class="form-group ">
<button type="button" name="submit" class="btn btn-primary btn-lg btn-block login-button">Register</button>
</div>
<div class="login-register">
Already registered? Login here
</div>
</form>
</div>
</div>
</div>
</tr>
</td>
</table>
<?php
if (isset($_POST['submit']))
{
$name = $_POST['name'];
$username = $_POST['user_name'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['confirm_password'];
$slquery = "SELECT * FROM customer WHERE email = '$email'";
$selectresult = mysql_query($slquery);
if(empty($_POST['name']))
{
$nameErr='Enter Your Name!';
}
else
{
$user = test_input($_POST['name']);
if(!preg_match('/^[a-zA-Z0-9#_]*$/',$user))
{
$nameErr=' Re-Enter Your Name! Format Inccorrect!( only alpha, numbers,#_ are allowed)';
}
}
if(empty($_POST['password']))
{
$passErr='Enter Your Password!';
}
else
{
$user = test_input($_POST['password']);
if(!preg_match('/^[a-zA-Z0-9#_]*$/',$pass))
{
$passErr='Invalid Format! Re-Enter Password!';
}
}
if(mysql_num_rows($selectresult)>0)
{
$msg = 'email already exists';
}
elseif($password != $cpassword){
$msg = "passwords doesn't match";
}
else{
$query = "INSERT INTO customer (name,email,user_name, password,confirm_password, ) VALUES ('
$name', '$username', '$password', '$cpassword', '$email')";
$result = mysql_query($query);
if($result){
$msg = "User Created Successfully.";
}
}
}
?>
</body>
</html>
I am trying to create a registration form with validation.i used some bootstrap for the front end design then Mysql database along with php.
when I click to submit the registration form, it does not validate the field values.please, someone, tell me what's wrong with this.Also, it's not showing the errors. I don't know why this is not working.
Thank you in Advance.
Just change this line from
<button type="button" name="submit" class="btn btn-primary btn-lg btn-block login-button">Register</button>
to
<button type="submit" name="submit" class="btn btn-primary btn-lg btn-block login-button">Register</button>
You have used button so form is not submitted. Change it to submit type
EDIT
Note: please start using PDO or mysqli
Please check below point:
1) You have used test_input() but not defined in your shown code.
2) Your query have extra , after confirm_password.
3) Insert query will not work. There were some errors:
$query = "INSERT INTO customer (name,user_name, password,confirm_password, email) VALUES ('
$name', '$username', '$password', '$cpassword', '$email')";
4) No need to store confirm_password
Database
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "stackoverflow";
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
session_start();
?>
Change the Register button like this
<div align="left" class="form-group ">
<button type="submit" name="submit" class="btn btn-primary btn-lg btn-block login-button">Register</button>
</div>
test_function
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Full PHP
<?php
if (isset($_POST['submit']))
{
$name = $_POST['name'];
$username = $_POST['user_name'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['confirm_password'];
$slquery = "SELECT * FROM customer WHERE email = '$email'";
$selectresult = mysqli_query($conn,$slquery);
if(empty($_POST['name']))
{
$nameErr='Enter Your Name!';
}
else
{
$user = test_input($_POST['name']);
if(!preg_match('/^[a-zA-Z0-9#_]*$/',$user))
{
$nameErr=' Re-Enter Your Name! Format
Incorrect!( only alpha, numbers,#_ are allowed)';
}
}
if(empty($_POST['password']))
{
$passErr='Enter Your Password!';
}
else
{
$user = test_input($_POST['password']);
if(!preg_match('/^[a-zA-Z0-9#_]*$/',$password))
{
$passErr='Invalid Format! Re-Enter Password!';
}
}
if (mysqli_num_rows($selectresult)>0)
{
echo 'email already exists';
}
elseif($password != $cpassword){
$msg = "passwords doesn't match";
}
else{
var_dump($name.$email.$username.$password.$cpassword);
$query = "INSERT INTO customer(name,email,user_name,
password,confirm_password) VALUES ('
$name', '$email','$username', '$password', '$cpassword')";
if ($conn->query($query) === TRUE) {
echo "New user created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
$conn->close();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}?>

post/redirect/get - how to unset session variables

Bellow is part of the code from register.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
/* running some checks of an input*/
if(sizeof($errorArray)==0) {
// redirecting to avoid form resubmission
$_SESSION['registered'] = true;
header('location: success.php',true,303);
}
else{
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['errorArray'] = $errorArray;
header('location: register.php',true,303);
}
}
Logic is simple -- if an errorArray is empty redirect to a success page, else redirect to register.php itself. To avoid form resubmission i tried to put post variables into session variable, so the user doesn't have to fill form again in case of error.
<?php
if (isset($_SESSION['errorArray'])) {
if (sizeof($_SESSION['errorArray']) != 0) {
echo '<div class="alert alert-danger" role="alert">
<h4>There were errors in Your input:</h4>';
foreach ($_SESSION['errorArray'] as $item) {
echo $item . '<br>';
}
}
$_SESSION['post'] = null;
$_SESSION['errorArray'] = null;
}
?>
This part of a code is executed later in register.php but it doesen't gives me the result I want. Somehow the variables are sett to null before the loop above is executed (??!). I have found a solution with get method that includes microtime in url passed to header , but it seams to me that there is more elegant solution that does not every time adds new values to a session variable.
Is there some way around this?
edit :
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// array to hold all the errors of input
$errorArray = [];
$emailRegex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
$nameRegex = '/^[a-z0-9][a-z0-9_]*[a-z0-9]$/';
$passwordRegex = '/^[a-z0-9][-a-z0-9_!##$?]*[a-z0-9]$/';
$email = $_POST['email'];
if (empty($email)) {
array_push($errorArray, "E-mail field required");
} else {
if (!preg_match($emailRegex, $email)) array_push($errorArray, 'Invalid email');
}
$name = $_POST['name'];
if (empty($name)) {
array_push($errorArray, "Name field required");
} else {
if (!preg_match($nameRegex, $name)) array_push($errorArray, 'Invalid name');
}
$password = $_POST['password'];
$passwordR = $_POST['passwordR'];
if (empty($passwordR) || empty($password)) {
array_push($errorArray, 'Password fields required');
} else if (!preg_match($passwordRegex, $password)) {
array_push($errorArray, 'Invalid password');
} else {
if ($password !== $passwordR) {
array_push($errorArray, 'Password inputs are not the same');
}
}
if (sizeof($errorArray) == 0) {
// redirecting to avoid form resubmission
$_SESSION['registered'] = true;
header('location: success.php', true, 303);
} else {
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['errorArray'] = $errorArray;
header('location: register.php', true, 303);
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Log</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="css/maincss.css" type="text/css">
<meta name="viewport" content="width = device-width, initial-scale = 1, user - scalable = no">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed">
<div class="container">
Home
<ul class="navbar-brand col-xs-5"><?= (isset($username)) ? 'Welcome ' . $username : ''; ?></ul>
Login
Register
</div>
</nav>
<div class="container">
<form class="form-signin" action="register.php" method="post">
<h2 class="form-signin-heading text-center text-capitalize">Registration form</h2>
<!-- I have purposely excluded required attribute from inputs and set type="text"
for an email so all the checks could be done on server side -->
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="email" class="sr-only">Email address</label>
<input type="text" id="email" name="email" class="form-control" placeholder="Email address"
value="<?= (isset($_SESSION['post']['email'])) ? $_SESSION['post']['email'] : ''; ?>" autofocus>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="name" class="sr-only">Name</label>
<input type="text" id="name" name="name" class="form-control" placeholder="Name"
value="<?= (isset($_SESSION['post']['name'])) ? $_SESSION['post']['name'] : ''; ?>" autofocus>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password">
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="passwordR" class="sr-only">Repeat Password</label>
<input type="password" id="passwordR" name="passwordR" class="form-control"
placeholder="Repeat Password">
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row">
<div class="col-xs-4"></div>
<div class="col-xs-4 center-block">
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div>
<?php
if (isset($_SESSION['errorArray'])) {
if (sizeof($_SESSION['errorArray']) != 0) {
echo '<div class="alert alert-danger" role="alert">
<h4>There were errors in Your input:</h4>';
foreach ($_SESSION['errorArray'] as $item) {
echo $item . '<br>';
}
}
// $_SESSION['post'] = null;
// $_SESSION['errorArray'] = null;
}
?>
</div>
</form>
</body>
</html>

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>

Undefined Variable on this tutorial on PHP with Bootstrap

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>

Categories