Inserting angularjs form values into database using php - php

I have created angularjs form. I want to store the form values into data base using PHP and before inserting I want to check weather the email is already exists or not. I am new to PHP. Any help would be appreciated. Thanks.
Register.html:
<div class="container col-lg-10" style="margin-top:2em; margin-left:2em;" >
<div class="panel panel-default">
<div class="panel-body" ng-app="TempleWebApp" ng-controller="RegisterCtrl">
<form name="userForm" ng-submit="submitForm()" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && (userForm.name.$dirty || submitted)}">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="user.name" placeholder="Your Name" ng-required="true">
<p ng-show="userForm.name.$error.required && (userForm.name.$dirty || submitted)" class="help-block">You name is required.</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && (userForm.email.$dirty || submitted)}">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Your Email Address" ng-required="true">
<p ng-show="userForm.email.$error.required && (userForm.email.$dirty || submitted)" class="help-block">Email is required.</p>
<p ng-show="userForm.email.$error.email && (userForm.email.$dirty || submitted)" class="help-block">Enter a valid email.</p>
</div>
<!-- PASSWORD -->
<div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid && (userForm.password.$dirty || submitted)}">
<label>Password</label>
<input type="Password" name="password" class="form-control" ng-model="user.passwrd" placeholder="Your Password" ng-required="true">
<p ng-show="userForm.password.$error.required && (userForm.password.$dirty || submitted)" class="help-block">Your password is required.</p>
</div>
<!-- TERMS & CONDITIONS -->
<div class="form-group" ng-class="{ 'has-error' : userForm.terms.$invalid && (userForm.terms.$dirty || submitted)}">
<label>Accept Terms & Conditions</label>
<input type="checkbox" value="" name="terms" ng-model="user.terms" ng-required="true" />
<p ng-show="userForm.terms.$error.required && (userForm.terms.$dirty || submitted)" class="help-block">Accept terms & conditions.</p>
</div>
<!-- ng-disabled FOR ENABLING AND DISABLING SUBMIT BUTTON -->
<!--<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Register</button>-->
<button type="submit" class="btn btn-primary col-lg-offset-6">Register</button>
</form>
<pre>{{user}}
</pre>
</div>
</div>
</div>
Main.js:
var app = angular.module('TempleWebApp', [ 'ngRoute']);
app.controller('RegisterCtrl', function ($scope,$location, $http) {
$scope.user = {};
$scope.user.name= "" ;
$scope.user.email ="";
$scope.user.passwrd="";
$scope.user.terms="";
// function to submit the form after all validation has occurred
$scope.submitForm = function () {
// Set the 'submitted' flag to true
$scope.submitted = true;
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
console.log("Inserted Successfully!");
});
};
});
PHP code.
<?php
$data = json_decode(file_get_contents("php://input"));
$username = $data->username;
$email = $data->email;
$password = $data->password;
$con = mysql_connect("localhost","root","");
mysql_select_db("userregister");
$sql = "insert into user(username,email,password) values($username,'$email','$password')";
$result = mysql_query($sql);
?>

Try using mysqli in the following manner (Also note you should create the variable $dbname and assign the right dbname to it:
$data = json_decode(file_get_contents("php://input"));
$username = #$data->username;
$email = #$data->email;
$password = #$data->password;
$dbname = '';
$conn = new mysqli("localhost","root","",$dbname);
$check = "SELECT * FROM user WHERE email='$email'";
//The following rows check whether this email already exists in the DB
$results = $conn->query($check);
if($results && mysqli_num_rows($results)>0)
{
echo "email";
die;
}
//The following rows will work only if there is no such email in the DB
if($conn->connect_error)
{
echo "false";
die;
}
$sql = "INSERT INTO user VALUES values($username,'$email','$password')";
if ($conn->query($sql) === true)
{
echo "true";
}
You will also need to change your Javascript to fit the possible events:
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
if(data == 'true'){
console.log("Inserted Successfully!");
}
else if(data == 'email'){
console.log("The email already exists");
}
else{
console.log("There was an issue connecting to the DB");
}
});

Related

PDO error 42000

i had an error when i run my code and i don't understand this error
error:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE UserID = 'ahmed' SET Username = 'adasda#dmail.ck',Email = 'ahmed',FullName' at line 1 in C:\wamp64\www\eC
<?php
/*
==============================================================
= Manage Member do
= you can Add | Edit | Delete Members from here
==============================================================
*/
session_start();
$pageTitle = 'Members';
if(isset($_SESSION['Username'])){
include 'init.php';
$do = isset($_GET['do']) ? $_GET['do'] : 'Manage';
// $do= '';
//
// if(isset($_GET['do'])){
//
// $do = $_GET['do'];
// }else {
// $do = 'Manage';
// }
// start Manage do
if ($do == 'Manage') {
echo 'welcom in manage do';
//Manage page
}elseif ($do == 'Edit') { //edit page
// check If the GET Request is Numeric && Get the Integer value of it
$userid = isset($_GET['userid']) && ($_GET['userid']) ? intval($_GET['userid']) : 0;
// Select the row of user from the table
// select All data Depend on this Id
$stmt = $con->prepare("SELECT * FROM users WHERE UserID = ? LIMIT 1");
// extract Query
$stmt->execute(array($userid));
// Fetch the data
$row = $stmt->fetch();
// the row count
$count = $stmt->rowCount(); // to count the row in the table
if ($stmt->rowCount() > 0) {
?>
<h1 class="text-center">Edit Member</h1>
<div class="container">
<form class="form-horizontal" action="?do=Update" method="POST">
<input type="hidden" name='userid' value="<?php echo $userid ?>"/>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Username</label>
<div class="col-sm-10">
<input type="text" name="username" class="form-control" value="<?php echo $row['Username'] ?>" autocomplete="off"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Password</label>
<div class="col-sm-10">
<input type="hidden" name="oldpassword"/>
<input type="password" name="newpassword" class="form-control" autocomplete="new-password"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">E-mail</label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" value="<?php echo$row['Email'] ?>" autocomplete="off"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Full-Name</label>
<div class="col-sm-10">
<input type="text" name="full" class="form-control" value="<?php echo$row['FullName'] ?>" autocomplete="off" />
</div>
</div>
<div class="form-group form-group-lg">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="save" class="btn btn-primary btn-lg" />
</div>
</div>
</form>
</div>
<?php
}else {
echo "you are not welcom in this page ";
}
}
// update page
elseif ($do == 'Update') {
echo "<h1 class='text-center'> welcom in the update page </h1>";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
# get the variable from the form
$id = $_POST['userid'];
$user = $_POST['username'];
$email= $_POST['email'];
$name = $_POST['full'];
//echo $id . $user . $pass . $name;
$stmt = $con->prepare('UPDATE users WHERE UserID = ? SET Username = ?,Email = ?,FullName = ?,');
$stmt->execute(array($user,$email,$name,$id));
echo $stmt->rowCount() . "Record Updated";
}else {
echo "you cant brows this page directly";
}
}
include $tpl . 'footer.php';
}else {
header('location: index.php');
exit();
}
?>
ommers\first_project\admin\members.php on line 110
Your update query is incorrect, you need to use the following:
$stmt = $con->prepare('UPDATE users SET Username = ?,Email = ?,FullName = ? Where UserId =?');
And change the rest of the code accordingly.

retrieve php error messages on bootstrap modal form submitting with ajax

I have a bootstrap form and i use jquery modal so i can open it on the same index.php window and when it is submitted the form should close and save data to database which it does on the other hand if there are error messages from formValidation.php file then it should show error messages instead of closing form.Now it does disappear even if there are errors and when i open it up again error messages are shown.I know there has been similar questions but i really cant make up solution for weeks from all sources i can get so i am a bit frustrated.Would appreciate help.Here is my code.
Here is my form from index.php file
<div class="container" id="register" style="display:none">
<div class="row centered-form">
<div class="col-xs-12 col-sm-8 col-md-4 col-sm-offset-2 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Banāns <small>Sia</small></h3>
</div>
<div class="panel-body">
<form role="form" class="ajax" method="post" action="index.php">
<?php include('classes/errors.php'); ?>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Vārds</label>
<input type="text" name="firstname" value="<?php echo $firstName;?>" id="firstname" class="form-control input-sm" placeholder="Vārds">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Uzvārds</label>
<input type="text" name="lastname" value="<?php echo $lastName;?>" id="lastname" class="form-control input-sm" placeholder="Uzvārds">
</div>
</div>
</div>
<div class="form-group">
<label>Lietotājvārds</label>
<input type="text" name="username" value="<?php echo $userName;?>" id="username" class="form-control input-sm" placeholder="Lietotājvārds">
</div>
<div class="form-group">
<label>E-pasts</label>
<input type="email" name="email" value="<?php echo $email;?>" id="email" class="form-control input-sm" placeholder="E-pasta adrese">
</div>
<div class="form-group">
<label>Telefona numurs</label>
<input type="number" name="number" value="<?php echo $number;?>" id="number" class="form-control input-sm" placeholder="Telefona numurs">
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Parole</label>
<input type="password" name="password1" id="password1" class="form-control input-sm" placeholder="Parole">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label>Apstipriniet paroli</label>
<input type="password" name="password2" id="password2" class="form-control input-sm" placeholder="Apstipriniet paroli">
</div>
</div>
</div>
<input type="submit" name="submit" id="submit" value="Register" class="btn btn-info btn-block">
<span id="success_msg"></span>
<span id="error_msg"></span>
<p>Aizvērt ...</p>
</form>
</div>
</div>
</div>
</div>
</div>
Here is my formValidation.php
<?php
include('classes/config.php');
$firstName = $lastName = $userName = $email = $number = $password1 = $password2 = "" ;
$errors = array();
if(isset($_POST["submit"])) {
$firstName = mysqli_real_escape_string($con, $_POST["firstname"]);
$lastName = mysqli_real_escape_string($con, $_POST["lastname"]);
$userName = mysqli_real_escape_string($con, $_POST["username"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$number = mysqli_real_escape_string($con, $_POST["number"]);
$password1 = mysqli_real_escape_string($con, $_POST["password1"]);
$password2 = mysqli_real_escape_string($con, $_POST["password2"]);
if (empty($firstName)) {
array_push($errors, "Lūdzu ievadiet vārdu.");
} else {
$firstName = test_input($firstName);
if (!preg_match("/^[a-zēūīāšžčķļņA-ZŅĒŪĪĀŠŽČĶĻŅ]*$/",$firstName)) {
array_push($errors, "Lūdzu ievadiet tikai burtus.");
}
}
if (empty($lastName)) {
array_push($errors, "Lūdzu ievadiet uzvārdu.");
} else {
$lastName = test_input($lastName);
if (!preg_match("/^[a-zēūīāšžčķļņA-ZŅĒŪĪĀŠŽČĶĻŅ]*$/",$lastName)) {
array_push($errors, "Lūdzu ievadiet tikai burtus.");
}
}
if (empty($userName)){
array_push($errors, "Lūdzu ievadiet lietotājvārdu.");
} else {
$userName = test_input($userName);
if(strlen($userName <= "6")){
array_push($errors, "Lietotājvārdam jāsastāv no vismaz 6 burtiem un/vai cipariem.");
}
}
if (empty($email)) {
array_push($errors,"Lūdzu ievadiet e-pasta adresi.");
} else {
$email = test_input($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, "Lūdzu pārbaudiet e-pasta adresi.");
}
}
if (empty($number)) {
$number = "NULL";
} else {
$number = test_input($number);
if (!preg_match("/^[0-9]{8}$/", $number)) {
array_push($errors, "Lūdzu ievadiet 8 ciparu numuru.");
}
}
if(!empty($password1) && $password1 == $password2){
$password1 = test_input($password1);
$password2 = test_input($password2);
} elseif ($password1 != $password2){
array_push($errors, "Paroles nesakrīt.");
} else {
array_push($errors, "Lūdzu ievadiet paroli.");
}
if(count($errors) == 0){
$password = md5($password1);
$query = "INSERT INTO users(firstname, lastname, username, email, phonenumber, password)
VALUES ('$firstName', '$lastName', '$userName', '$email', '$number', '$password')";
mysqli_query($con, $query);
$_SESSION["username"] = "$userName";
$_SESSION["succes"] = "Apsveicu, tu esi pieslēdzies!";
header("location: index.php");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
and my error messages are looped trough in seperate errors.php file and are echoed in error class in index.php
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
And finally Ajax
This submits the form and it closes even if there are error messages.
$("#submit").click(function() {
e.preventDefault();
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var username = $("#username").val();
var email = $("#email").val();
var number = $("#number").val();
var password1 = $("#password1").val();
var password2 = $("#password2").val();
var submit = $("#submit").val();
$.ajax({
url: "classes/formValidation.php",
method: "POST",
data: {
firstname: firstname,
lastname: lastname,
username: username,
email: email,
number: number,
password1: password1,
password2: password2,
},
success: function(data){
if(data == "success"){
$("#register").hide();
location.reload();
}else{
return false;
}
}
});
});
And i have tried this
If i open up console it retrieves all my form name attributes in an object.I have tried to change action to my formValidation.php or errors.php but it does not work.
$('form.ajax').on('submit', function(){
var bzz = $(this),
url = bzz.attr('action'),
method = bzz.attr('method'),
data = {};
bzz.find('[name]').each(function(index, value) {
var bzz = $(this),
name = bzz.attr('name'),
value = bzz.val();
data[name] = value;
console.log(data);
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});

Ajax live insertion double submit glitch

This code is a savings system. But the withdrawal is not finished yet because i've found a glitch in my code. This code works fine. It can validate properly and deposite properly. And i found the glitch after I accidentally press the enter twice. And i noticed that i inserted two records in the database before clearing the password of the cashier. I want is even the cashier pressed the enter twiced.It's just insert one record in the transaction table.
this is my SavingsAddInsert.php
<?php
include("general.php");
if(isset($_POST['Submit'])){
$Amount = $_POST['Amount'];
$Password = $_POST['Password'];
$Transaction = $_POST['Transaction'];
$SaverAccount = $_POST['AccountID'];
if(empty($Amount) && empty($Password) && $Transaction == "undefined"){
$error[] = "Please Select Transaction Type and put an Amount and Password!";
}else{
if(empty($Amount) === true || $Amount === null){
$error[] = "Amount is empty";
}else{
if(!preg_match('/^[0-9.]*$/',$Amount)){
$error[] = "i only accept numeric and decimal";
}
}
if(empty($Password) === true || $Password === null){
$error[] = "Password is empty";
}else{
$Cashier_Password = Cashier_password($_SESSION['AccountID'],$Password);
if($Cashier_Password === false){
$error[] = "Cashier Password is wrong";
}
}
if($Transaction == "undefined"){
$error[] = "Please select Category in Transaction Type ";
}else{
if($Transaction == "WITHDRAW"){
if($Amount > Check_Balance($SaverAccount)){
$error[] = "Insufficient Balance!";
}
}
}
}
if(isset($error)){
echo output_errors($error);
}
if(empty($error) || $error = 0){
if($Transaction == "DEPOSITE"){//deposite
$Balance = Check_Balance($SaverAccount);
$TotalAmount = $Balance + $Amount;
$Cashier = $_SESSION['AccountID'];
$SavingsID = Get_SavingsID($SaverAccount);
$update_savings = mysql_query("UPDATE tblsavings SET TotalSavings = '$TotalAmount' WHERE AccountID = '$SaverAccount'");
if($update_savings){
$insert_transaction = mysql_query("INSERT INTO tbltransaction
(SavingsID,Cashier,ReceiveWithdraw,RunningBalance,TransactionType,Date,Time) VALUES
('$SavingsID','$Cashier','$Amount','$TotalAmount','$Transaction',now(),now())") or die(mysql_error());
if($insert_transaction){
echo "<p><i class='fa fa-check' aria-hidden='true'></i>Transaction Complete. The Total Amount of AccountNo:'".get_AccountNo($SaverAccount)."' is ".$TotalAmount."</p>";
}
}
}
else if($Transaction == "WITHDRAW"){//withdraw
unset($Password);
}
}
}
?>
this is my SavingsAdd.php
<div class="popup-wrapper">
<div class="popup-body">
<div class="popup-head">
<p>Withdraw and Deposite</p>
</div>
<?php
if(isset($_GET['Account'])){
$Account = $_GET['Account'];
$get_info1 = mysql_query("SELECT tbluserdetail.FirstName,
tbluserdetail.MiddleName,
tbluserdetail.LastName,
tbluserdetail.Image,
tbluserdetail.ImageName,
tbluserdetail.Gender,
useraccounts.AccountNo,
useraccounts.AccountID,
useraccounts.Position
FROM useraccounts
INNER JOIN tbluserdetail
ON useraccounts.UserID=tbluserdetail.UserID
WHERE useraccounts.AccountID = '$Account'");
while($row1 = mysql_fetch_array($get_info1)){
$FirstName_p = $row1['FirstName'];
$MiddleName_p = $row1['MiddleName'];
$LastName_p = $row1['LastName'];
$AccountNo_p = $row1['AccountNo'];
$AccountID_p = $row1['AccountID'];
$Gender_p = $row1['Gender'];
$Image_p = $row1['Image'];
?>
<div class="container-fluid">
<div class="row">
<div class="p-header col-md-2 col-sm-2 col-xs-2">
<?php
if(empty($Image_p)){
if($Gender_p == "Male"){
echo '<img src="img/default-male.jpg"/>';
}else if($Gender_p == "Female"){
echo '<img src="img/default-female.jpg"/>';
}
}else{
echo '<img src="data:image/jpeg;base64,'.base64_encode( $Image_p ).'"/>';
}
?>
</div>
<div class="p-info col-md-9 col-sm-9 col-xs-9">
<div class="row">
<p><?php if(isset($_GET['Account'])){ echo $FirstName_p." ".$MiddleName_p." ".$LastName_p;} ?></p>
</div>
<div class="row">
<p>Account No: <?php if(isset($_GET['Account'])){ echo $AccountNo_p;} ?></p>
</div>
</div>
</div>
<hr/>
<div id="ajaxResult">
</div>
<hr/>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<p>Transaction Type:</p>
</div>
<div class="col-md-7 col-sm-7 col-xs-7">
<select class="form-control" name="Transaction">
<option value="undefined">Select</option>
<option value="WITHDRAW">Withdraw</option>
<option value="DEPOSITE">Deposite</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<p>Amount:</p>
</div>
<div class="col-md-7 col-sm-7 col-xs-7">
<input type="text" class="form-control" name="Amount" id="Amount" placeholder="0.00"/>
<input type="hidden" class="form-control" name="AccountID" id="AccountID" value="<?php if(isset($_GET['Account'])){ echo $AccountID_p;} ?>" readonly>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<p>Cashier password:</p>
</div>
<div class="col-md-7 col-sm-7 col-xs-7">
<input type="password" class="form-control" name="Password" id="Password" placeholder="••••••••••"/>
</div>
</div>
<div class="row">
<div class="float-right col-md-12">
<input type="button" value="Cancel" name="Cancel" class="btn btn-danger"/>
<input type="submit" value="Submit" name="Submit" id="Submit" class="btn btn-success"/>
</div>
</div>
</div>
<?php }}?>
</div>
</div>
and this is my javascript inside the SavingsAdd.php
var form = document.forms.namedItem("myForm");
form.addEventListener('submit', function(ev) {
var oOutput = document.getElementById("ajaxResult"),
fn = new FormData(form);
fn.append("Submit", fn.get('Submit'));
fn.append("Amount", fn.get('Amount'));
fn.append("AccountID", fn.get('AccountID'));
fn.append("Password", fn.get('Password'));
fn.append("Transaction", fn.get('Transaction'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'SavingAddInsert.php', true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
if(form){
document.getElementById('Amount').value = null;
document.getElementById('Password').value = null;
var return_data = xhr.responseText;
document.getElementById("ajaxResult").innerHTML = return_data;
}
}
}
xhr.send(fn);
ev.preventDefault();
}, false);
as you can see in the image. i try to submit by pressing double enter. and the record inserted it twice.
You reset the passwort input field only after you receive a response from the server. You need to do this directly after you send the request.
If you want to keep the data (including passwort) in case the request fails, you need to add a variable stating if a request is active (and waiting). Set this to 1 or 'active' instead of emptying the password field and reset after the request was successful. As long as a request is active, your JS must not send another request.

Can't add data through PHP and MySQL

Validate function
function validate(add_app_form){
var valid = true;
var userTxt = document.getElementById("patient_name").value;
var dateTxt = document.getElementById("app_date").value;
var timeTxt = document.getElementById("app_time").value;
var oldName = document.getElementById("select_old").value;
if(userTxt == "" && dateTxt == "" && timeTxt == "" && oldName == "choose")
{
//$("#lblTxt").text("Username and Password are required!");
$('#patient_name').css('border-color', 'red');
$('#app_date').css('border-color', 'red');
$('#app_time').css('border-color', 'red');
$('#select_old').css('border-color', 'red');
$("#add_app_lbl").text("Please Fill all the form");
valid = false;
}
if(userTxt == "" && oldName == "choose")
{
$('#patient_name').css('border-color', 'red');
$("#add_app_lbl").text("Please Add Patient Name Or select an old patient");
valid = false;
}
if(dateTxt == "")
{
$('#app_date').css('border-color', 'red');
$("#add_app_lbl").text("Please Add a Date");
valid = false;
}
return valid;
}
EDITED CODE
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
EDITED CODE 2
<form class="form-horizontal" id="add_app_form" method="post" action="add_appoint.php" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" id="add_app_btn" name="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
I have a php code that take values from a form and add them into MySQL database.
First part of the PHP code, see if the admin choose an already exist patient from drop list, then add a date and time of an appointment with a reason.
Then values are posted into PHP code where we see if we have already an appointment in those date and time. If not ($appExistStmtCount == 0) then go and insert an appointment.
The problem is that nothing added to database and can't see any PHP errors echoed.
Here is the PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
if(isset($_POST['add_app_btn'])){
//Values From AJAX
$patient_name = $_POST['patient_name'];
$date_app = $_POST['app_date'];
$time_app = $_POST['app_time'];
$reason = $_POST['app_reason'];
$old_patient_id = $_POST['select_old'];
//If new patient
if($patient_name == "" && $old_patient_id != "choose")
{
try{
//See if date and time exist
$appExist = "SELECT * FROM appointment WHERE id_logged = :id_logged AND date_app = :date_app and time_app = : time_app";
$appExistStmt = $conn->prepare($appExist);
$appExistStmt->bindValue(":id_logged", $id_logged);
$appExistStmt->bindValue(":date_app", $date_app);
$appExistStmt->bindValue(":time_app", $time_app);
$appExistStmt->execute();
$appExistStmtCount = $appExistStmt->rowCount();
if($appExistStmtCount == 0)
{
//Add to appointment table
$appAdd = "INSERT INTO appointment(id_logged, patient_id, date_app, time_app, reason)
VALUES(:id_logged, :patient_id, :date_app, :time_app, :reason)";
$appAddStmt = $conn->prepare($appAdd);
$appAddStmt->bindValue(":id_logged", $id_logged);
$appAddStmt->bindValue(":patient_id", $old_patient_id);
$appAddStmt->bindValue(":date_app", $date_app);
$appAddStmt->bindValue(":time_app", $time_app);
$appAddStmt->bindValue(":reason", $reason);
$appAddStmt->execute();
echo "added";
}
else
{
echo "not added";
header("Location: add_appoint.php");
}
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
header("Location: add_app_btnoint.php");
}
}
}
?>
And here the HTML form:
<form class="form-horizontal" id="add_app_form" onSubmit="return validate(this);">
<div class="box-body">
<div class="form-group">
<label for="patient_name" class="col-sm-3 control-label">Old Patient</label>
<div class="col-sm-4">
<select id="select_old" name="select_old">
<option value="choose">Choose Name</option>
<?php foreach($name_array as $na) { ?>
<option value="<?php echo $na['id'] ?>"><?php echo $na['patient_name'] ?></option>
<?php } ?>
</select>
</div>
<label for="patient_name" class="col-sm-1 control-label">New</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="patient_name" name="patient_name" placeholder="New Patient Name">
</div>
</div>
<div class="form-group">
<label for="app_date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<input type="date" class="form-control" id="app_date" name="app_date">
</div>
<label for="app_time" class="col-sm-2 control-label">Time</label>
<div class="col-sm-4">
<input type="time" class="form-control" id="app_time" name="app_time">
</div>
</div>
<div class="form-group">
<label for="app_reason" class="col-sm-2 control-label">Reason</label>
<div class="col-sm-10">
<textarea class="form-control" id="app_reason" name="app_reason" placeholder="Reason"></textarea>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submi;" id="add_app_btn" class="btn btn-success pull-right">Add Appointment</button>
</div><!-- /.box-footer -->
</form>
PS
Values can be seen in the URL but the page just refresh and nothing added
Your form has no method, so it's passing data through get. You need to add method="post" to your form.
Edit. As #u_mulder mentioned, you need to add name attribute to your button for the check in your php if the button is clicked.

else statement no being accessed in php if statement

I am writing a log in script for a site, I have most things working except on a validation mysqli query the else tatement is not being accessed and I cannot figure out how to resolve it, the code below is the index page that has the html and then the php script that is called, All of the php validation works except for the bit of script that validates all the input fields match the database fields, i can get the validation side of the if statement to work and it sends me to the relevent page, the problem is that if the validation in the first part of the if statement shows invalid it doesnt then pass to the else statement, all i get is a blank white page and it is the same as the php page doing the validation not the page i need it to go too. Any help would be most appreciated.
HTML CODE ***********
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dot Mov Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/styles/home.css" rel="stylesheet" type="text/css">
<!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.-->
<script>var __adobewebfontsappname__="dreamweaver"</script>
<script src="http://use.edgefonts.net/lemon:n4:default.js" type="text/javascript"></script>
<script src="/js/civem.js"></script>
<script type='text/javascript' src='http://code.jquery.com/jquery.min.js'></script>
<script src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script src="/js/pswrd_strength.js"></script>
<script src="/js/email_dbvalidate.js"></script>
<script src="/js/username_dbvalidate.js"></script>
<script src="/js/confirm_password__dbvalidate.js"></script>
<script type="text/javascript">
function SwapDivsWithClick(div1,div2)
{
d1 = document.getElementById(div1);
d2 = document.getElementById(div2);
if( d2.style.display == "none" )
{
d1.style.display = "none";
d2.style.display = "block";
}
else
{
d1.style.display = "block";
d2.style.display = "none";
}
}
</script>
</head>
<body>
<div id="video_container">
<video muted autoplay loop >
<source src="/video/South Dakota Badlands Scenic Byway 720p (Video Only)_1.3gp" type="video/3gp">
<source src="/video/South Dakota Badlands Scenic Byway 720p (Video Only).webm" type="video/webm">
<source src="/video/South Dakota Badlands Scenic Byway 720p.ogg" type="video/ogg">
Your browser does not support the video tag. I suggest you upgrade your browser. </video>
</div>
<header>
<div class="upload">UPLOAD</div>
<div class="view">VIEW</div>
<div class="spacer1"></div>
<div class="search_bar">
<form action="/search_results.php" method="post" name="search_database" autocomplete="on">
<input type="text" class="search" placeholder="Search">
</form>
</div>
<div class="logo_text">.MOV </div>
<div class="tagline">Motorcycle Online Video</div>
</a></header>
<main>
<div id="login" style="display:block">
<form method="post" action="includes/login.inc.php" id="loginform">
<input name="email" type="email" id="email" form="loginform" placeholder="Please Enter Your Email">
<input name="password" type="password" id="password" form="loginform" placeholder="Please Enter Your Password" title="Please Enter Your Password">
<div class="submit_buttons">
<input type="submit" class="login_btn" form="loginform" formaction="includes/login.inc.php" title="Login" value="Login">
<div class="join_but">Or Join</div>
</div>
<div id="forgotten_password">Forgotten Password</div>
<div class="login_statements">
<div class="statement1">
<div class="by_joining">By Joining</div>
<div class="dot_mov">.MOV</div>
<div class="agree">You agree to our</div>
</div>
<div class="statement2">
<div class="terms_link">Terms of Service</div>
<div class="and">and</div>
<div class="service_link">Privacy Policy</div>
</div>
</div>
<div class="facebook_login">
<div class="facebook_icon"><img src="images/fb.png" class="fb_icon"></div>
<div class="fb_link">Login with FaceBook </div>
</div>
</form>
</div>
</div>
<div id="join" style="display: none;">
<form action="includes/register.inc.php" method="post" id="joinform">
<input name="name2" type="text" id="name2" form="joinform" placeholder="Please Enter Your Username" title="Please Enter Your Username">
<div id="user-name">
<h4>Username must meet the following requirements!<br>If you have forgotten your Password, click on "Forgotten Password"!</h4>
<div id="name_result"></div>
<div id="name_length" class="invalid">At least <strong>6 letters</strong></div>
</div>
<input name="email2" type="email" id="email2" form="joinform" placeholder="Please Enter Your Email" title="Please Enter a Valid Email">
<div id="user-email">
<h4>Email must be a valid Email format!<br>If the Email exists, Either Login using the Username the Email was setup with or check your Email is correct!</h4>
<div id="email_result">
<div id="email_validate" class="invalid">Email Valid</div>
<div id="emaildb_validate"></div>
</div>
</div>
<input name="password2" type="password" id="password2" form="joinform" placeholder="Please Enter Your Password" title="Please Enter Your Password">
<div id="pswd_info">
<h4>Password must meet the following requirements!<br>If the Password doesnt meet the requirements you will be required to fill in the form again!</h4>
<ul id="pswd_list">
<li id="letter" class="invalid">At least <strong>one letter</strong></li>
<li id="capital" class="invalid">At least <strong>one capital letter</strong></li>
<li id="number" class="invalid">At least <strong>one number</strong></li>
<li id="length" class="invalid">Be at least <strong>8 characters</strong></li>
</ul>
</div>
<input name="confirm_password2" type="password" id="confirm_password2" form="joinform" placeholder="Please Confirm Your Password" title="Please Confirm Your Password">
<div id="user-confirm_password">
<h4>Please Confirm Password<br>If the Passwords do not match, you wil be required to fill in the form again!</h4>
<div id="error" class="error"></div>
<div id="confirm_match" class="invalid">Passwords Match</div>
</div>
<div class="submit_buttons2">
<input name="join_btn2" type="submit" id="join_btn2" form="joinform" formaction="includes/register.inc.php" " formmethod="POST" title="Join" value="Join">
<div class="join_btn2">Or Login</div>
</div>
<div class="login_statements2">
<div class="statement1">
<div class="by_joining">By Joining</div>
<div class="dot_mov">.MOV</div>
<div class="agree">You agree to our</div>
</div>
<div class="statement2">
<div class="terms_link">Terms of Service</div>
<div class="and">and</div>
<div class="service_link">Privacy Policy</div>
</div>
</div>
<div class="facebook_login2">
<div class="facebook_icon"><img src="images/fb.png" class="fb_icon"></div>
<div class="fb_link">Login with FaceBook </div>
</div>
</form>
</div>
</div>
</div>
<div class="scroll_container">
<a data-scroll href="#body2"><div class="scroll_link">
<div class="arrow"><img src="/images/arrow.png" alt="" class="arrow_icon"/></div>
<div class="arrow3"><img src="/images/arrow.png" alt="" class="arrow_icon"/></div>
Scroll Down</div></a>
</div>
</main>
<div class="body2" id="body2">
<div class="vid_grid">
<div class="top_section">
<div class="top_left_quarter"></div>
<div class="top_right_quarter">
<div class="top_right_left_quarter"></div>
<div class="top_right_right_quarter"></div>
<div class="top_right_bottom_left"></div>
<div class="top_right_bottom_right"></div>
</div>
</div>
<div class="bottom_section">
<div class="bottpm_left_top"></div>
<div class="bottpm_left_bottom"></div>
<div class="bottom_middle"></div>
<div class="bottom_left_quarter"></div>
<div class="bottom_right_quarter"></div>
<div class="bottom_right_top"></div>
<div class="bottom_right_bottom"></div>
</div>
<div class="staff_picks">Staff Picks </div>
</div>
</div>
<footer class="footer">
<div id="breadcrumbs">Terms &vert; Privacy &vert; About Us &vert; Copyright &vert; Cookies &vert; &reg &copy 2015</div><img src="/images/.mov.png" alt="" width="42" height="14" class="logo"/>
<div class="social_media"><img src="/images/fb.png" alt="" width="30" height="30" class="fbicon"/><img src="/images/twitter.png" alt="" width="32" height="32" class="twittericon"/><img src="/images/googleplus.png" alt="" width="32" height="32" class="googleplusicon"/></div>
</footer>
<script src="/js/smooth-scroll.js"></script>
<script src="/js/smooth-scroll.min.js"></script>
<script type="text/javascript">
smoothScroll.init({
speed: 1000,
easing: 'easeInOutCubic',
offset: 0,
updateURL: true,
callbackBefore: function ( toggle, anchor ) {},
callbackAfter: function ( toggle, anchor ) {}
});
</script>
</body>
</html>
PHP ***************
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
$emailErr = $passwordErr = $password_matchErr = $email_exsistErr = '';
$email = $name = $password = $confirm_password = '';
if (isset($_POST['name2'], $_POST['email2'], $_POST['paswword2'], $_POST['confirm_password2'])) {
$error_msg .= "please fill in the form";
} else {
// Sanitize the data passed in 'name'
$name = filter_input(INPUT_POST, 'name2', FILTER_SANITIZE_STRING);
// Sanitize the data passed in 'email'
$email = filter_input(INPUT_POST, 'email2', FILTER_SANITIZE_EMAIL);
// validate the data passed in 'email'
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
// check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$emailErr = "The email address you entered is not valid";
}
//Sanitize the data passed in 'password'
$password = filter_input(INPUT_POST, 'password2', FILTER_SANITIZE_STRING);
//validate the data passed in 'password'
if (preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $password)) {
} else {
$passwordErr = "Password is invalid!<br>Please ensure your password is formatted as described when filling in the form!";
}
//Sanitize the data passed in 'confirm_password'
$confirm_password = filter_input(INPUT_POST, 'confirm_password2', FILTER_SANITIZE_STRING);
//check that password and confirm password match
if ($password != $confirm_password) {
// error matching passwords
$confirm_passwordErr = "Your passwords do not match.<br>Please type carefully.";
}
$results = $mysqli->query("SELECT * FROM signed_up WHERE email = `'$email'");`
while($row = $results->fetch_assoc()) {
if ($row["name"] == $name && $row["email"] == $email && $row["password"] == $password) {
$regErr = 'User Already Exsists!<br>Please Login';
$_SESSION['regErr'] = $regErr;
header('location: ../login.php');
} else {
//if ($emailErr == '' && $passwordErr == '' && $password_matchErr == '' && $email_exsistErr =='') {
echo '15';
$_SESSION['emailErr'] = $emailErr;
$_SESSION['passwordErr'] = $passwordErr;
$_SESSION['confirm_passwordErr'] = $confirm_passwordErr;
$_SESSION['email_exsistErr'] = $email_exsistErr;
header('Location: ../join.php');
exit();
}
}
}
//}
?>
This is the section of code where the issue is ***********
$results = $mysqli->query("SELECT * FROM signed_up WHERE email = '$email'");
while($row = $results->fetch_assoc()) {
if ($row["name"] == $name && $row["email"] == $email && $row["password"] == $password) {
$regErr = 'User Already Exsists!<br>Please Login';
$_SESSION['regErr'] = $regErr;
header('location: ../login.php');
} else {
//if ($emailErr == '' && $passwordErr == '' && $password_matchErr == '' && $email_exsistErr =='') {
echo '15';
$_SESSION['emailErr'] = $emailErr;
$_SESSION['passwordErr'] = $passwordErr;
$_SESSION['confirm_passwordErr'] = $confirm_passwordErr;
$_SESSION['email_exsistErr'] = $email_exsistErr;
header('Location: ../join.php');
exit();
}
}
}
//}
?>
edited code that now works ***********************
$results = $mysqli->query("SELECT * FROM signed_up WHERE email = '$email'");
while($row = $results->fetch_assoc()) {
if ($row["name"] == $name && $row["email"] == $email && $row["password"] == $password) {
$regErr = 'User Already Exsists!<br>Please Login';
$_SESSION['regErr'] = $regErr;
header('location: ../login.php');
}else{
$_SESSION['emailErr'] = $emailErr;
$_SESSION['passwordErr'] = $passwordErr;
$_SESSION['confirm_passwordErr'] = $confirm_passwordErr;
$_SESSION['email_exsistErr'] = $email_exsistErr;
header('Location: ../join.php');
exit();
}
}
}
Put your validation directly into SQL
$results = $mysqli->query("SELECT count(*) FROM signed_up WHERE email = '$email' AND name = '$name'");
if ($result->fetchColumn()){
echo "User already exists";
}else{
echo "New user";
}

Categories