index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>
This is the USER class with the register and send_mail functions. The send_mail function doesn't work. I've followed other questions that were similar, but it doesn't work for me. Maybe someone can spot a mistake I've made, thanks.
require_once 'dbconfig.php';
class USER
{
public function register($uname,$email,$upass,$code)
{
try
{
$password = md5($upass);
$stmt = $this->conn->prepare("INSERT INTO tbl_users(userName,userEmail,userPass,tokenCode)
VALUES(:user_name, :user_mail, :user_pass,
:active_code)");
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
function send_mail($email,$message,$subject)
{
require_once('mailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "mail.smeinfratech.co.za";
$mail->Port = 465;
$mail->AddAddress($email);
$mail->Username="datalogging#smeinfratech.co.za";
$mail->Password="**********";
$mail->SetFrom('datalogging#smeinfratech.co.za','SME DATALOGGING');
$mail->AddReplyTo("datalogging#smeinfratech.co.za","SME DATALOGGING");
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->isHTML(true);
$mail->Send();
}
}
The following is the sign up page code where call these functions
<?php
if(!session_id()){
session_start();
}
require_once 'class.user.php';
require_once 'dbconfig.php';
$reg_user = new USER();
if ($reg_user->is_logged_in() != "") {
$reg_user->redirect('SystemStatus.php');
}
Post for the submit button
if (isset($_POST['btn-signup'])) {
$uname = ($_POST['txtuname']);
$email = ($_POST['txtemail']);
$upass = ($_POST['txtpass']);
$code = md5(uniqid(rand()));
$stmt = $reg_user->runQuery("SELECT * FROM tbl_users WHERE userEmail=:email_id");
$stmt->execute(array(
":email_id" => $email
));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
$msg = "<div class='alert alert-danger'>
<strong>Sorry!</strong> The email already exists. Please try another one.
</div>";
}
else
{
$reg_user->register($uname, $email, $upass, $code);
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = "<div class='alert alert-success'>
Hello $uname,
<br /><br />
Welcome to SME Datalogging!<br/>
To complete your registration please click the following link<br/>
<br /><br />
<a href='http://elec.specmech.co.za/SMELogin2/verify.php?id=$id&code=$code'>Click HERE to Activate :)</a>
<br /><br />
Thanks,
</div>";
$subject = "Confirm Registration";
send_mail($email, $message, $subject);
$msg = "<div class='alert alert-success'>
<strong>Success!</strong> We've sent an email to $email.
Please click on the confirmation link in the email to create your account.
</div>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>SME DATALOGGING | Sign Up</title>
<?php require_once 'v2/php/head.php'; ?>
</head>
<body>
<div id="content" class="container pt-5">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="system-card">
<img src="v2/img/sme.png" alt="SME" width="100%"/>
<form>
<div class="text-center">
<h4 class="mb-5 mt-5 text-primary"><strong>Sign Up</strong></h4>
</div>
<div class=" form-sm mt-5">
<label class="required">Username</label>
<input type="text" id="username" class="form-control" formControlName="username" name="txtuname" required>
</div>
<div class=" form-sm">
<label class="required">Email</label>
<input type="text" id="email" class="form-control" formControlName="email" name="txtemail" required>
</div>
<div class=" form-sm">
<label class="required">Password</label>
<input type="password" id="password" class="form-control" formControlName="password" name="txtpass" required>
</div>
<div class="row d-flex align-items-center mb-4 mt-4">
<div class="col-md-3 col-md-6 text-center">
<button class="btn btn-primary btn-block" type="submit" name="btn-signup">SIGN UP</button>
</div>
<div class="col-md-6">
<div class="text-center">
<small>
Already have an acount? Sign In
</small>
</div>
</div>
</div>
<?php
if (isset($msg)) echo $msg;
?>
</form>
</div>
</div>
</div>
</div>
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="/assets/js/jquery-2.1.4.min.js"></script>
</body>
</html>
From what I can see you are trying to call the send_mail method of the USER class as a regular function.
$subject = "Confirm Registration";
send_mail($email, $message, $subject);
This is not going to work, because there is no function named send_mail.
You will have to create an instance of the class USER, and then call the method send_mail.
$subject = "Confirm Registration";
$user = new USER;
$user->send_mail($email, $message, $subject);
This is how you would call this method.
Or just like this (given that $reg_user is an instance of the USER class).
$subject = "Confirm Registration";
$reg_user->send_mail($email, $message, $subject);
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've been testing a CRUD interface with PHP and SQLSRV driver but i got stuck on the creating part, i can read the data that alredy was added on the database by id, but i cant get to work the create data from PHP to the database, when i press the create Button it clears the inputs and shows the errors. Would like to know if there is something wrong with my code so far.
PHP CODE:
<?php
require 'database.php';
if ( !empty($_POST)) {
$iError = null;
$nError = null;
$dError = null;
$tError = null;
$id = $_POST['id'];
$name = $_POST['name'];
$Address = $_POST['Address'];
$phone = $_POST['phone'];
$valid = true;
if (empty($id)) {
$iError = 'add id';
$valid = false;
}
if (empty($name)) {
$nError = 'add name';
$valid = false;
}
if (empty($Address)) {
$dError = 'add address';
$valid = false;
}
if (empty($phone)) {
$tError = 'add phone';
$valid = false;
}
if ($valid) {
$tsql = "INSERT INTO dbo.TEST1 (id, name, Address, phone) values(?, ?, ?, ?)";
$arr1 = array($id, $name, $Address, $phone);
$stmt = sqlsrv_query($conn, $tsql, $arr1 );
if ( $stmt === FALSE ){
echo "New data created";
}
else {
echo "Error creating data";
die(print_r(sqlsrv_errors(),true));
}
}
}?>`
this is the HTML part:
<body>
<div>
<div>
<h3>CREAR</h3>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class=" <?php echo !empty($iError)?'error':'';?>">
<label >ID</label>
<div >
<input name="name" type="text" placeholder="ID" value="<?php echo !empty($id)?$id:'';?>">
<?php if (!empty($iError)): ?>
<span ><?php echo $iError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($nError)?'error':'';?>">
<label>name</label>
<div>
<input name="name" type="text" placeholder="name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nError)): ?>
<span><?php echo $nError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($emailError)?'error':'';?>">
<label >Address</label>
<div >
<input name="email" type="text" placeholder="Address" value="<?php echo !empty($Address)?$Address:'';?>">
<?php if (!empty($dError)): ?>
<span><?php echo $dError;?></span>
<?php endif;?>
</div>
</div>
<div class=" <?php echo !empty($tError)?'error':'';?>">
<label >phoner</label>
<div >
<input name="mobile" type="text" placeholder="phone" value="<?php echo !empty($phone)?$phone:'';?>">
<?php if (!empty($tError)): ?>
<span ><?php echo $tError;?></span>
<?php endif;?>
</div>
</div>
<div >
<button type="submit">Create</button>
Return
</div>
</form>
</div>
</div>