I'm learning PHP and Bootstrap and I'm running into an issue when trying to validate my input fields.
Before I added Bootstrap I was able to validate the form but now it doesn't work.. does PHP and Bootstrap not work together for some reason in this fashion?
Particularly my page doesn't seem to be validating on the POST.
Does Bootstrap have the capability to validate user input directly???
I'm a bit confused and if I'm mixing technology's that shouldn't .. any help would be appreciated.
Thanks,
<?php require_once('../Connections/login.php'); ?>
<?php
session_start();
//initialize the session and verify user is logged in and allowed to view site
if (!isset($_SESSION['USER_ID'])) {
header("Location: login.php");
exit();
}else{
$qryUSER_ID=$_SESSION['USER_ID'];
}
//print_r($_POST);
//print_r($_SESSION);
//print_r($_GET);
?>
<?php
// define variables and set to empty values
$usernameErr = $passwordErr = $password_confirmErr = $password_matchErr = "";
$username = $password = $password_confirm = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "User name is required";
} else {
$username = test_input($_POST["username"]);
// check if username only contains letters and whitespace
if (!preg_match("/^[a-z0-9_.A-Z-' ]*$/",$username)) {
$usernameErr = "Only letters, numbers and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["password_confirm"])) {
$password_confirmErr = "Password confirm is required";
} else {
$password_confirm = test_input($_POST["password_confirm"]);
}
if ($_POST['password'] !== $_POST['password_confirm']) {
$password_matchErr = "Passwords must match";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" src="/css/bootstrap.min.css" >
<link href="/css/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
<title>Skins Game-Add User</title>
</head>
<body>
<form method="post" action="dtlprocess.php">
<div class="form-group">
<label class="control-label colspan="3" class="font-weight-bold"><h2>Add New User</h2></label>
</div>
<div class="form-group">
<label class="control-label col-sm-2">User Name:</label><span class="error"><?php echo $usernameErr;?></span>
<div class="col-sm-10">
<input type="text" class="form-control" name="username" value="<?php echo htmlspecialchars($username);?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password:</label><span class="error"><?php echo $passwordErr;?></span>
<div class="col-sm-10">
<input type="password" class="form-control" name="password" value="<?php echo htmlspecialchars($password);?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password Confirm:</label><span class="error"><?php echo $password_matchErr;?></span>
<div class="col-sm-10">
<input type="password" class="form-control" name="password_confirm" value="<?php echo htmlspecialchars($password_confirm);?>">
</div>
</div>
<div class="form-group">
<input type="submit" name="addUser" value="Submit" class="btn btn-secondary"> <button type="submit" name="frmback" class="btn btn-secondary">Cancel</button></td>
</div>
</form>
</body>
</html>
In case anyone runs across a similar problem in the future... here is the modified code using a paramater mysqli.
It seems like Bootstrap should have some built in functionality for validating Usernames and validating passwords, therefore eliminating some of the php code.
Thanks,
<?php require_once('../Connections/login.php'); ?>
<?php
session_start();
//initialize the session and verify user is logged in and allowed to view site
if (!isset($_SESSION['USER_ID'])) {
header("Location: login.php");
exit();
}else{
$qryUSER_ID=$_SESSION['USER_ID'];
}
//print_r($_POST);
//print_r($_SESSION);
//print_r($_GET);
?>
<?php
// define variables and set to empty values
$usernameErr = $passwordErr = $password_confirmErr = $password_matchErr = "";
$username = $password = $password_confirm = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "User name is required";
} else {
$username = test_input($_POST["username"]);
// check if username only contains letters and whitespace
if (!preg_match("/^[a-z0-9_.A-Z-' ]*$/",$username)) {
$usernameErr = "Only letters, numbers and white space allowed";
}
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["password_confirm"])) {
$password_confirmErr = "Password confirm is required";
} else {
$password_confirm = test_input($_POST["password_confirm"]);
}
if ($_POST['password'] !== $_POST['password_confirm']) {
$password_matchErr = "Passwords must match";
} else {
//Past the validation checks, add new user
//this also tests if the user exists before trying to add user since it will throw an error
if (isset($_POST['addUser'])){
//query if user exists already
$checkuser = $mysqli->prepare("SELECT * FROM users WHERE user_name = ?");
$checkuser->bind_param("s", $_POST['username']);
$checkuser->execute();
//row count will be > 0 if user exists
$checkrows= $checkuser->get_result();
$checkuser->close();
if($checkrows->num_rows > 0) {
echo "User already exists";
exit();
}else{
//Add new user since they do not exist
$activeuser = 'A';
$addnewuser = $mysqli->prepare("INSERT INTO users (user_name, password, active) VALUES (?,?,?)");
$addnewuser->bind_param("sss", $_POST['username'], $_POST['password'], $activeuser);
$addnewuser->execute();
$addnewuser->close();
header("Location: summary.php");
exit();
}
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" src="/css/bootstrap.min.css" >
<link href="/css/bootstrap.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
<style>
.error {color: #FF0000;}
.font10{font-size: 10px;}
</style>
<title>Skins Game-Add User</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div class="form-group">
<label class="control-label colspan="3" class="font-weight-bold"><h2>Add New User</h2></label>
</div>
<div class="form-group">
<label class="control-label col-sm-2">User Name:</label><label class="error font10"><?php echo $usernameErr;?></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="username" value="<?php echo $username;?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password:</label><span class="error font10"><?php echo $passwordErr;?></span>
<div class="col-sm-10">
<input type="password" class="form-control" name="password" value="<?php echo $password;?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password Confirm:</label><span class="error font10"><?php echo $password_matchErr;?></span>
<div class="col-sm-10">
<input type="password" class="form-control" name="password_confirm" value="<?php echo $password_confirm;?>">
</div>
</div>
<div class="form-group">
<input type="submit" name="addUser" value="Submit" class="btn btn-secondary"> <button type="submit" name="frmback" class="btn btn-secondary">Cancel</button></td>
</div>
</form>
</body>
</html>```
Use an array of errors instead of blank variables.
You can use validation like this just create a file for this:
validation.php:
$name = test_input($_POST['name']);
$login = test_input($_POST['login']);
$email = test_input($_POST['email']);
$password = test_input($_POST['password']);
$password_confirm = test_input($_POST['password_confirm']);
$succ = [];//old value of inputes will be stored here
if(empty($name)){
$errors['name'] = 'Name required';
}else{
$succ['name'] = $name;
}
if(empty($login)){
$errors['login'] = 'Login required';
}else{
$succ['login'] = $login;
}
if(empty($email)){
$errors['email'] = 'Email required';
}else{
$succ['email'] = $email;
}
if(empty($password)){
$errors['password'] = 'password required';
}
if($password_confirm != $password){
$errors['password_confirm'] = 'Passwords are not equal';
}
if(isset($errors)){
$_SESSION['errors'] = $errors;
$_SESSION['succ'] = $succ;
header("Location: index.php");
die;
}else{
header("Location: index.php")
}
and add into form attribute action="validation.php" and add to the top of your file:
index.php
if(isset($_SESSION['errors'])){
$errors = $_SESSION['errors'];//execute errors from the session
$succ = $_SESSION['succ'];
unset($_SESSION['succ']);
unset($_SESSION['errors']);//delete all errrors from the session
}
And then you can use $errors on your page as array of errors.
After that you can add an error container for each input like that:
.
.
...<input type="text" name="name" ....
<span class="error">
<?php
if(isset($errors['name'])){
echo $errors['name'];
}
?>
</span>
I have searched the internet for many hours. My Phpmailer works great but, it sends the email even if the form has errors, like if the email is take. I can't get it to know if the form has errors. Do I need to also query the database in my Phpmailer file or can I use the query return already done in my PHP register query?
In my register PHP query I check for if email is taken. If the email is taken the form displays an error, but PHPmailer sends the email even with the email taken error. How can I stop PHPmailer form sending an email with form errors.
Notice my variable $user holds the check if email is taken return. How can I get PHPmailer to also use the variable $user?
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
if(array_key_exists("first",$_POST) && $_POST["first"] != "" && array_key_exists("last",$_POST) && $_POST["last"] != "" && (array_key_exists('email', $_POST) and PHPMailer::validateAddress($_POST['email'])) && array_key_exists("unit",$_POST) && $_POST["unit"] != "") {
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'gator*****hostgator.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '***********.com'; // SMTP username
$mail->Password = '*********'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('admin********.com', 'Admin');
$mail->addAddress('admin*****.com', 'HP Website'); // Add a recipient
$mail->addAddress($_POST['email']); // Name is optional
// $mail->addReplyTo($email);
// $mail->addCC($_REQUEST['email']);
// $mail->addBCC('bcc#example.com');
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$unit = $_POST['unit'];
$bed = $_REQUEST['bed'];
$bath = $_REQUEST['bath'];
$web = $_REQUEST['web'];
$phone = $_REQUEST['phone'];
$manage = $_REQUEST['manage'];
//$unit = $_REQUEST['unit'];
//$uid = $_REQUEST['uid'];
$ck = $_REQUEST['rent'];
//Content
$mail->addEmbeddedImage('img/logo4.png', 'logo');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Your HP unit is signed up';
// $first_name = $_POST['first_name'];
// $last_name = $_POST['last_name'];
// $license_type = $_POST['license_type'];
$mail->Body = '<p style="background-color:#333; color:orange; text-align:center; font-weight:bolder">Welcome to the HP Owner website</p>
<p style="text-align:center; margin:0"><img src="cid:logo"></p>
<p><strong>Name: </strong>'.$first.' '.$last.'</p>
<p><strong>Email: </strong>'.$email.'</p>
<p><strong>Unit#: </strong>'.$unit.'</p>
<p><strong>Bed: </strong>'.$bed.'</p>
<p><strong>Bath: </strong>'.$bath.'</p>
<p><strong>Website: </strong>'.$web.'</p>
<p><strong>Phone: </strong>'.$phone.'</p>
<p><strong>Management: </strong>'.$manage.'</p>
<p><strong>Show on HP website - (1 means show): </strong>'.$ck.'</p>
<p>If any of your info above is wrong, login with your username and password. Click on Update My Unit button and update your info..<br>
<br>If you checked the box Show On Rental Site, your unit will show - refresh the rental site or go to http://www.*********.php<br>
<br>If you need to delete everything and start over - contact the admin email admin***********.com';
$mail->AltBody = 'HP Owner Web Site - You are signed up';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}
?>
AND MY PHP query
require_once 'dbh.inc.php';
//include_once 'mailer0.php';
include_once 'includes/mailer.php';
// Init vars
$first = $last = $email = $unit = $bed = $bath = $web = $phone = $manage = $pwd = $confirm_password = $ck = '';
$name_err = $unit_err = $bed_err = $bath_err = $phone_err = $email_err = $password_err = $confirm_password_err = '';
// Process form when post submit
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Sanitize POST
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// Put post vars in regular vars
$first = trim($_POST['first']);
$last = trim($_POST['last']);
$email = trim($_POST['email']);
$unit = trim($_POST['unit']);
$bed = trim($_POST['bed']);
$bath = trim($_POST['bath']);
$web = trim($_POST['web']);
$phone = trim($_POST['phone']);
$manage = trim($_POST['manage']);
// $uid = trim($_POST['uid']);
$pwd = trim($_POST['pwd']);
$confirm_password = trim($_POST['confirm_password']);
$ck = trim($_POST['rent']);
// Validate email
if(empty($email)){
$email_err = 'Please enter email';
} else {
$stmt = $pdo->prepare("SELECT * FROM condos_hp WHERE user_email=?");
if($stmt->execute([$email]));{
$user = $stmt->fetch();
}
if ($user) {
// email found
$email_err = 'Email is already taken';
}
unset($stmt);
}
// Validate name
if(empty($first) || empty($last)){
$name_err = 'Please enter name';
}
// Validate name
if(empty($unit)){
$unit_err = 'Please enter your unit #';
}
// Validate name
if(empty($bed) || empty($bath)){
$bed_err = 'Please enter bed/bath #';
}
// Validate name
if(empty($phone)){
$phone_err = 'Please enter your phone';
}
// Validate password
if(empty($pwd)){
$password_err = 'Please enter password';
} elseif(strlen($pwd) < 6){
$password_err = 'Password must be at least 6 characters ';
}
// Validate Confirm password
if(empty($confirm_password)){
$confirm_password_err = 'Please confirm password';
} else {
if($pwd !== $confirm_password){
$confirm_password_err = 'Passwords do not match';
}
}
// Make sure errors are empty
if(empty($name_err) && empty($email_err) && empty($password_err) && empty($confirm_password_err)){
// Hash password
$pwd = password_hash($pwd, PASSWORD_DEFAULT);
// Prepare insert query
// (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, rent)
$sql = 'INSERT INTO condos_hp (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, user_pwd, rent) VALUES (:first, :last, :email, :unit, :bed, :bath, :web, :phone, :manage, :pwd, :rent)';
// $sql = 'INSERT INTO condos_hp (name, email, password) VALUES (:name, :email, :password)';
if($stmt = $pdo->prepare($sql)){
// Bind params
// $stmt->bindParam(':name', $name, PDO::PARAM_STR);
// $stmt->bindParam(':email', $email, PDO::PARAM_STR);
// $stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':first', $first, PDO::PARAM_STR);
$stmt->bindParam(':last', $last, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':unit', $unit, PDO::PARAM_STR);
$stmt->bindParam(':bed', $bed, PDO::PARAM_STR);
$stmt->bindParam(':bath', $bath, PDO::PARAM_STR);
$stmt->bindParam(':web', $web, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':manage', $manage, PDO::PARAM_STR);
// $stmt->bindParam(':uid', $uid, PDO::PARAM_STR);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);
$stmt->bindParam(':rent', $ck, PDO::PARAM_STR);
// $stmt->bindParam(':id', $id);
// Attempt to execute
if($stmt->execute()){
// Redirect to login
header('Location: login0.php');
} else {
die('Something is not right');
}
}
unset($stmt);
}
// Close connection
unset($pdo);
}
?>
UPDATED CURRENT CODE.......
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Include db config
require_once 'dbh.inc.php';
//include_once 'mailer0.php';
// Init vars
$first = $last = $email = $unit = $bed = $bath = $web = $phone = $manage = $uid = $pwd = $confirm_password = $ck = '';
//$name_err = $unit_err = $bed_err = $bath_err = $phone_err = $email_err = $uid_err = $password_err = $confirm_password_err = '';
//$error = isset($_SESSION['error']) ? $_SESSION['error'] : [];
// Process form when post submit
if (isset($_POST["register"])) {
// $error = array()
//($_SERVER['REQUEST_METHOD'] === 'POST'){
// echo var_dump($_POST);
// echo '<br/>';
// print_r($_POST);
//$error = ($_SESSION['error']);
// Sanitize POST
// $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$error = array();
var_dump($error);
if (!empty($error)) {
echo "not empty";
} else {
echo "empty";
}
// Put post vars in regular vars
$first = trim($_POST['first']);
$last = trim($_POST['last']);
$email = trim($_POST['email']);
$unit = trim($_POST['unit']);
$bed = trim($_POST['bed']);
$bath = trim($_POST['bath']);
$web = trim($_POST['web']);
$phone = trim($_POST['phone']);
$manage = trim($_POST['manage']);
$uid = trim($_POST['uid']);
$pwd = trim($_POST['pwd']);
$confirm_password = trim($_POST['confirm_password']);
$ck = ($_POST['rent']);
// Validate email
if (empty($email)) {
$error['email'] = "Please enter email";
} else {
// check if email is taken
/*$sql = 'SELECT * FROM condos_hp WHERE user_email = :email';
if($stmt = $pdo->prepare($sql)){
// Bind variables
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
// Attempt to execute
if($stmt->execute()){
// Check if email exists
$user = $stmt->fetch()
if ($user){
$email_err = 'Email is already taken';
}
} else {
die('Something went wrong');
}
}*/
/*$sql= "SELECT * FROM condos_hp WHERE uid = :uid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':uid', $uid);
//$stmt = $pdo->prepare("SELECT uid FROM condos_hp WHERE uid=:uid");
//$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
//$user = $stmt->fetchALL(PDO::FETCH_ASSOC);
//print_r($stmt->fetchObject())
//$stmt->setFetchMode(PDO::FETCH_ASSOC);
$user = $stmt->fetch();
if ($user) {
// email found
$uid_err = 'UserID is already taken';
echo var_dump($user);*/
$stmt = $pdo->prepare("SELECT uid FROM condos_hp WHERE uid=?");
$stmt->bindValue('1', $uid);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
// $error[] = 'sorry username already taken !';
// email found
$error['uid'] = "user ID already taken";
// die;
// header('Location: register.php');
print_r($user);
// print_r($error);
//} else { // or not die('Something went wrong'); }
} else {
// echo 'user does not exist<br>';
}
unset($stmt);
}
// Validate name
if (empty($first) || empty($last)) {
$error['name'] = "Enter name";
}
// Validate name
if (empty($unit)) {
$error['unit'] = 'Please enter your unit #';
}
// Validate name
if (empty($bed) || empty($bath)) {
$error['rooms'] = 'Please enter bed/bath #';
}
// Validate name
if (empty($phone)) {
$error['phone'] = 'Please enter your phone';
}
//Check phone # format 000-000-0000
if (!preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone)) {
$error['phone'] = 'Please enter correct phone format';
}
//Check manage format
if (!preg_match("/^(\s\(([^)]+)\))?[[:punct:]]?\p{Lu}+(?:[\s'-]?[\p{L}\d]+)+(\(([^)]+)\))*$/", $manage)) {
$error['manage'] = 'Please enter correct management format';
}
//Check password format 4 and 8 digits long and include at least one numeric digit.
// if (!preg_match("/^(?=.*\d).{4,8}$/", $pwd)) {
// $password_err = 'Password must be at least 4 digits with 1 number ';
if (empty($uid)) {
$error['uid'] = 'Please enter uid';
}
// Validate password
if (empty($pwd)) {
$error['pwd'] = 'Please enter password';
}
if (!preg_match("/^(?=.*\d).{4,8}$/", $pwd)) {
$error['pwd'] = 'Password must be at least 4 digits with 1 number ';
}
// Validate Confirm password
if (empty($confirm_password)) {
$error['pwdpar'] = 'Please confirm password';
} else {
if ($pwd !== $confirm_password) {
$error['pwdpar'] = 'Passwords do not match';
}
}
// Make sure errors are empty
if (empty($error)) {
// Hash password
$pwd = password_hash($pwd, PASSWORD_DEFAULT);
// Prepare insert query
// (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, rent)
$sql = 'INSERT INTO condos_hp (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, uid, user_pwd, rent) VALUES (:first, :last, :email, :unit, :bed, :bath, :web, :phone, :manage, :uid, :pwd, :rent)';
// $sql = 'INSERT INTO condos_hp (name, email, password) VALUES (:name, :email, :password)';
if ($stmt = $pdo->prepare($sql)) {
// Bind params
// $stmt->bindParam(':name', $name, PDO::PARAM_STR);
// $stmt->bindParam(':email', $email, PDO::PARAM_STR);
// $stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':first', $first, PDO::PARAM_STR);
$stmt->bindParam(':last', $last, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':unit', $unit, PDO::PARAM_STR);
$stmt->bindParam(':bed', $bed, PDO::PARAM_STR);
$stmt->bindParam(':bath', $bath, PDO::PARAM_STR);
$stmt->bindParam(':web', $web, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':manage', $manage, PDO::PARAM_STR);
$stmt->bindParam(':uid', $uid, PDO::PARAM_STR);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);
$stmt->bindParam(':rent', $ck, PDO::PARAM_STR);
// $stmt->bindParam(':id', $id);
// Attempt to execute
if ($stmt->execute()) {
// Redirect to login
header('Location: register.php');
} else {
die('Something is not right');
}
}
unset($stmt);
}
// Close connection
unset($pdo);
}
//include_once 'includes/mailer.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="includes/style.css">
<title>Register HP Account</title>
<script>
function validate(form) {
fail = validateFirst(form.first.value)
fail += validateLast(form.last.value)
fail += validateEmail(form.email.value)
fail += validateUnit(form.unit.value)
fail += validateBed(form.bed.value)
fail += validateBath(form.bath.value)
fail += validateWebsite(form.web.value)
fail += validatePhone(form.phone.value)
fail += validateManage(form.manage.value)
fail += validateUid(form.uid.value)
fail += validatePassword(form.pwd.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
</script>
<script src="includes/validate_functions.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-8 mx-auto">
<h2 style="text-align:center">HP Sign-Up Form</h2>
<p style="text-align:center">Fill in this form to register</p>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
<div class="form-row justify-content-center">
<div class="form-group col-md-4">
<label for="first">First Name</label>
<input type="text" name="first"
class="form-control form-control-lg <?php echo (!empty($error['name'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($first); ?>">
<span class="invalid-feedback"><?php echo $error['name']; ?></span>
</div>
<div class="form-group col-md-4">
<label for="last">Last Name</label>
<input type="text" name="last"
class="form-control form-control-lg <?php echo (!empty($error['name'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($last); ?>">
<span class="invalid-feedback"><?php echo $error['name']; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-6">
<label for="email">Email Address</label>
<input type="email" name="email"
class="form-control form-control-lg <?php echo (!empty($error['email'])) ? 'is-invalid' : ''; ?>"
value="<?php echo $email; ?>">
<span class="invalid-feedback"><?php echo $error['email']; ?></span>
</div>
<div class="form-group col-md-2">
<label for="unit">Unit #</label>
<input type="text" name="unit"
class="form-control form-control-lg <?php echo (!empty($error['unit'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($unit); ?>">
<span class="invalid-feedback"><?php echo $error['unit']; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-1">
<label for="bed">Bed</label>
<input type="text" name="bed"
class="form-control form-control-lg <?php echo (!empty($error['rooms'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($bed); ?>">
<span class="invalid-feedback"><?php echo $error['rooms']; ?></span>
</div>
<div class="form-group col-md-1">
<label for="bath">Bath</label>
<input type="text" name="bath"
class="form-control form-control-lg <?php echo (!empty($error['rooms'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($bath); ?>">
<span class="invalid-feedback"><?php echo $error['rooms']; ?></span>
</div>
<div class="form-group col-md-6">
<label for="web">Website</label>
<input type="text" name="web" class="form-control form-control-lg"
value="<?php echo htmlentities($web); ?>">
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-3">
<label for="phone">Phone - 000-000-0000</label>
<input type="text" id="yourphone2" name="phone" placeholder="123-456-7890"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
class="form-control form-control-lg <?php echo (!empty($error['phone'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($phone); ?>">
<span class="invalid-feedback"><?php echo $error['phone']; ?></span>
</div>
<div class="form-group col-md-5">
<label for="manage">Management - (VRBO, SELF, etc.)</label>
<input type="text" name="manage"
class="form-control form-control-lg <?php echo (!empty($error['manage'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($manage); ?>">
<span class="invalid-feedback"><?php echo $error['manage'] = 'Please management'; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-2">
<label for="uid">UserID - 8 length</label>
<input type="text" name="uid"
class="form-control form-control-lg <?php echo (!empty($error['uid'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($uid); ?>" placeholder="6 chars ex.betty12">
<span class="invalid-feedback"><?php echo $error['uid']; ?></span>
</div>
<div class="form-group col-md-3">
<label for="pwd">Password - min 6 digits</label>
<input type="password" name="pwd"
class="form-control form-control-lg <?php echo (!empty($error['pwd'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($pwd); ?>"
placeholder="6 to 8 digits include 1 num - ex.1234, absd12">
<span class="invalid-feedback"><?php echo $error['pwd']; ?></span>
</div>
<div class="form-group col-md-3">
<label for="confirm_password">Confirm Password</label>
<input type="password" name="confirm_password"
class="form-control form-control-lg <?php echo (!empty($error['pwdpar'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($confirm_password); ?>">
<span class="invalid-feedback"><?php echo $error['pwdpar']; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="custom-control custom-checkbox">
<input type="hidden" name="rent" value="0">
<input type="checkbox" value="1" name="rent" class="custom-control-input" id="customCheck1"
checked="checked">
<label class="custom-control-label" for="customCheck1">Check to show on the rental site</label>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-4">
<input type="submit" value="register" name="register" class="btn btn-success btn-block">
</div>
<div class="form-group col-md-4">
Have an account? Login
</div>
</div>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"
integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T"
crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="dist/jquery-input-mask-phone-number.js"></script>
<script>
//xxx-xxx-xxxx format code
$(document).ready(function () {
$('#yourphone2').usPhoneFormat({
format: 'xxx-xxx-xxxx',
});
});
</script>
<?php require_once './includes/footer.php'; ?>
</html>
I have used header("Content-Type:text/html; charset=utf-8"); & <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> on both html & php parts.
But for the webpage contents displayed , the text of the Chinese words are garbled .How to tackle the problem ?
create.php
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=utf-8");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Amount = "";
$CName_err = $Address_err = $Amount_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_CName = trim($_POST["CName"]);
if(empty($input_CName)){
$CName_err = "Please enter a name.";
} elseif(!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z'-.\s ]+$/")))){
$CName_err = 'Please enter a valid name.';
} else{
$CName = $input_CName;
}
// Validate address
$input_Address = trim($_POST["Address"]);
if(empty($input_Address)){
$Address_err = 'Please enter an address.';
} else{
$Address = $input_Address;
}
// Validate Amount
$input_Amount = trim($_POST["Amount"]);
if(empty($input_Amount)){
$Amount_err = "Please enter the amount.";
} elseif(!ctype_digit($input_Amount)){
$Amount_err = 'Please enter a positive integer value.';
} else{
$Amount = $input_Amount;
}
// Check input errors before inserting in database
if(empty($CName_err) && empty($Address_err) && empty($Amount_err)){
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Amount) VALUES (?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName,$Address,$Amount));
Database::disconnect();
header("Location: index.php");
}}
?>
<!DOCTYPE html>
<!--<html lang="en">-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>捐贈表格</h2>
</div>
<p>本人願意以信用卡捐款</p><br>
<p>I would like to make donation</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($CName_err)) ? 'has-error' : ''; ?>">
<label>Name</label>
<input type="text" name="CName" class="form-control" value="<?php echo $CName; ?>">
<span class="help-block"><?php echo $CName_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<textarea name="Address" class="form-control"><?php echo $Address; ?></textarea>
<span class="help-block"><?php echo $Address_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Amount_err)) ? 'has-error' : ''; ?>">
<label>Amount</label>
<input type="text" name="Amount" class="form-control" value="<?php echo $Amount; ?>">
<span class="help-block"><?php echo $Amount_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
<p>多謝您的支持</p><br>
<p>Thank you for your support</p>
</div>
</div>
</div>
</div>
</body>
</html>
Update
garbled page :
Have being trying this query for 3 days now. I have a list of rows here: http://prntscr.com/dick00. All what I want to is to edit and delete each row respectively. For some reason the id is not carrying forward and no record is updating.
When I click on edit in access.php I get edit_access.php?id= in address bar.
Here is my link in access.php
<td><a href="edit_access.php?id=<?php echo $row['id']; ?>"><i class="fa fa-edit"></i>edit</td>
edit_access.php
EDIT 1: php code
<?php
// start session
session_start();
// error_reporting(E_ALL); ini_set('display_errors', 1);
if(!isset($_SESSION['user_type'])){
header('Location: index.php');
}
// include connection
require_once('include/connection.php');
// set user session variables
$userId = $_SESSION['user_id'];
$error = [] ;
if(isset($_POST['update']))
{
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$therapist = $_POST['therapist'];
$access_type = $_POST['access_type'];
$code = $_POST['code'];
$created_at = $_POST['created_at'];
$postcode = $_POST['postcode'];
// validate form field
if (empty($firstname)){
$error[] = 'Field empty, please enter patient first name';
}
if (empty($lastname)){
$error[] = 'Field empty, please enter patient last name';
}
if (empty($therapist)){
$error[] = 'Field empty, please enter your name';
// $error = true;
}
if (empty($code)){
$error[] = 'Field empty, please enter patient access code';
// $error = true;
}
if (empty($access_type)){
$error[] = 'Field empty, please check access type';
// $error = true;
}
if (empty($postcode)){
$error[] = 'Field empty, please enter patient postcode';
// $error = true;
}
//if no errors have been created carry on
if(empty($error)){
$updated_at = date('Y-m-d');
// ************* UPDATE PROFILE INFORMATION ************************//
if(!($stmt = $con->prepare("UPDATE access SET firstname = ?, lastname = ?, therapist = ?, access_type = ?, postcode = ?, code = ?, updated_at = ?
WHERE id = ?"))) {
echo "Prepare failed: (" . $con->errno . ")" . $con->error;
}
if(!$stmt->bind_param('sssssssi', $firstname, $lastname, $therapist, $access_type, $postcode, $code, $updated_at, $userId)){
echo "Binding paramaters failed:(" . $stmt->errno . ")" . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: (" . $stmt->errno .")" . $stmt->error;
}
if($stmt) {
$_SESSION['main_notice'] = '<div class="alert alert-success">"Access Code Added successfully!"</div>';
header('Location: access.php');
exit;
}else{
$_SESSION['main_notice'] = '<div class="alert alert-danger">"Some error, try again"</div>';
header('Location: '.$_SERVER['PHP_SELF']);
}
}
}
// title page
$title = "Edit Access Record | Allocation | The Whittington Center";
// include header
require_once('include/header.php');
?>
<?php
if(isset($_GET['id'])){
$userId = $_GET['id'];
}
else{
$userId = $_POST['user_id'];
// mysqli_close($con);
$stmt = $con->prepare("SELECT * FROM access WHERE id = ?");
$stmt->bind_param('s', $userId);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 0) {
echo 'No Data Found for this user';
}else {
$stmt->bind_result($firstname, $lastname, $therapist, $access_type, $postcode, $code);
while ($row = $stmt->fetch());
$stmt->close();
}
?>
EDIT 2: HTML part
<h2 class="text-light text-greensea">Edit Access Record</h2>
<form name="access" class="form-validation mt-20" novalidate="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" autocomplete='off'>
<div class="form-group">
<input type="text" name="firstname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' firstname ']; } ?>' placeholder='firstname'></td>
</div>
<div class="form-group">
<input type="text" name="lastname" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' lastname ']; } ?>' placeholder='lastname'></td>
</div>
<div class="form-group">
<input type="text" name="therapist" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' therapist ']; } ?>' placeholder='therapist'></td>
</div>
<?php $access_type = $access_type; ?>
<div class="form-group ">
<label for="work status">Access Type</label>
<div name="access_type" value='<?php if(isset($error)){ echo $_POST[' access_type ']; } ?>'>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($work_status) && $access_type == "Keysafe") echo "checked"; ?> value="Keysafe"><i></i>Keysafe
</label>
<label class="checkbox-inline checkbox-custom">
<input type="checkbox" name="access_type" <?php if (isset($access_type) && $access_type == "keylog") echo "checked"; ?> value="keylog"><i></i>Keylog
</label>
</div>
</div>
<div class="form-group">
<input type="text" name="code" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' code ']; } ?>' placeholder='access code'></td>
</div>
<div class="form-group">
<input type="text" name="postcode" class="form-control underline-input" value='<?php if(isset($error)){ echo $_POST[' postcode ']; } ?>' placeholder='postcode'></td>
</div>
<div class="form-group text-left mt-20">
<button type="update" class="btn btn-primary pull-right" name="update" id='update'>Add Access</button>
<!-- <label class="checkbox checkbox-custom-alt checkbox-custom-sm inline-block">
<input type="checkbox"><i></i> Remember me
</label> -->
<a href="access.php">
<button type="button" class="btn btn-greensea b-0 br-2 mr-5">Back</button>
</a>
</div>
</form>
</div>
<!-- end of container -->
Thanks guy's for requesting for more code... i hope have given enough code sample.
you most put your id inside of a hidden input in your html form like this:
<input type="hidden" name="itemId" value="<?php echo '$_GET['id']'?>">
and then when you submit your form you have itemId in side $_POST['itemId'] variable.
EDIT:
I must describe scenario for you. maybe you got the point.
you have a list of access witch in every row has this tag:
access ....
in your access-form.php you have a form with this structure:
<form method="post" action="edit-access.php">
.....
<input type="hidden" name="id" value="<?php echo $_GET['id']?>">
.....
</form>
next in your edit-access.php you can access to this id by this syntax:
echo $_POST['id'];
my form action is php_self so that it can validate the form...
what i want to do is after the form is submited, then the data is connect and send to sql....
i already import my sql table and it have a few data recorded inside the table....
so how can i connect to the sql??
and also where i should write my connect sql code in???
here is my php form code....
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = $checkErr ="";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
if(empty($_POST['agree']) || $_POST['agree'] != 'agree') {
$checkErr ="Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy";
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)">
I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</fieldset>
</form>
</div>
</body>
</html>
the userdetail.php is the page that shows the information that user submit...
so where and how i can insert the data in to sql....
You should write your SQL code within $valid.
Let me illustrate below:
Note: I've used default credentials: Hostname = localhost, username = root, password = '', database name = my_database.
You may refer to this: mysqli_connect()
if($valid){
echo "Valid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
/* SQL code starts */
$con = mysqli_connect("localhost", "root", "", "my_database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO...."; // Your insert query
$query = mysqli_query($con,$sql) or die(mysqli_error($con));
/* SQL code ends */
if ($query) { // Add this condition. Session should be written only when SQL query is successful
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
..........
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
} else {
echo "Unable to insert";
}
} else{
echo "Invalid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
}
Hope this helps.