What is the best way to write an insert code with PDO? - php

I have recently learned Object Oriented Programming PHP, and I tried to test my knowledge on that, so I tried to write some queries by myself...
(Example practice: inserting new row, updating a row and deleting a row).
And here is of the templates that I've coded myself in order to Insert New Row into database:
class Register
{
protected $notice = array();
private $_db;
public function __construct()
{
$this->_db = new Connection();
$this->_db = $this->_db->dbConnect();
}
public function CheckUname($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$chk1 = $this->_db->prepare("SELECT user_name FROM admins WHERE user_name = ?");
$chk1->bindParam(1,$username);
$chk1->execute();
if($chk1->rowCount() == 1)
{
$notice['username_exists'] = "Try different username";
return $this->notice;
}else{
$chk2 = $this->_db->prepare("SELECT email_address FROM admins WHERE email_address = ?");
$chk2->bindParam(1,$email);
$chk2->execute();
if($chk2->rowCount() == 1)
{
$notice['email_exists'] = "The email address that you have entered is already exists in database";
return $this->notice;
}else{
$this->NewAdmin($username,$email,$password,$groups,$level);
$notice['success_message'] = "New admin was successfully added";
return $this->notice;
}
}
}
}
public function NewAdmin($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$reg = $this->_db->prepare("INSERT INTO admins (user_name, email_address, password_hash, group_admin, date_joined, admin_level) VALUES ( ?, ?, ?, ?, NOW(), ?)");
$reg->bindParam(1,$username);
$reg->bindParam(2,$email);
$reg->bindParam(3,$password);
$reg->bindParam(4,$groups);
$reg->bindParam(5,$level);
$reg->execute();
}
}
public function getNotice()
{
return $this->notice;
}
}
And I called this Class on index:
<?php
if (isset($_POST['submit'])){
$username = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['pass'];
$groups = $_POST['groups'];
if($groups == "Administrator"){
$level = 2;
}else if($groups == "ContentCreatorBlog"){
$level = 3;
}else if($groups == "ContentCreatorShop"){
$level = 4;
}else if($groups == "ContentCreatorGallery"){
$level = 5;
}else if($groups == "Secretary"){
$level = 6;
}else if($groups == "SocialMediaManager"){
$level = 7;
}else if($groups == "Analyst"){
$level = 8;
}else{
$level = Null;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$notice['email_validation'] = "The email that you have entered is not a valid one";
}else{
$registration = new Register();
$notice[] = $registration->CheckUname($username,$email,$password,$groups,$level);
}
}
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Add New Admin
<small>You can add new admin here</small>
</h1>
<ol class="breadcrumb">
<li class="active">addnewadmin.php</li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box box-primary" id="myModal1">
<div class="box-header with-border">
<h3 class="box-title">Required Information</h3>
</div>
<?php
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</div>
";
}
if(isset($notice['username_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
?>
<form role="form" method="POST" action="" data-tour-index="1" data-tour-title="Card Type" data-tour-description="A card will usually be one of multiple similar type items on a page.">
<div class="box-body">
<div class="form-group">
<label>User name</label>
<input type="text" class="form-control" placeholder="Enter username" name="uname" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Temporary password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter password" name="pass" required>
</div>
<div class="form-group">
<label>Group admin</label>
<select class="form-control" name="groups">
<option value="Administrator">Administrator</option>
<option value="ContentCreatorBlog">Blog Content Creator</option>
<option value="ContentCreatorShop">Shop Content Creator</option>
<option value="ContentCreatorGallery">Gallery Content Creator</option>
<option value="Secretary">Secretary</option>
<option value="SocialMediaManager">Social Media Manager</option>
<option value="Analyst">Analyst</option>
</select>
</div>
</div>
<div class="box-footer">
Visit admin new documentation to know more about this page.
</div>
<div class="box-footer">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
So shortly what it does is showing the form and take some information and assign to parameters and then call the Class:
$registration = new Register();
$notice[] = $registration->CheckUname($username,$email,$password,$groups,$level);
So if the form faced any error such as:
already registerd username error
already exists email address error
It should simply take back an error message and show it to users by these code on the index page:
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</div>
";
}
if(isset($notice['username_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
Question:
The problem with this code is that the error messages does not pop up when a user enters information despite of the rules. However it still adds new row to table correctly.
So now the question is "Why the errors does not show up on page when users enters wrong information? Which part I made a mistake"

There's an diffrence between $notice and $this->notice. $notice is a local var and $this->notice is a class var. In your case, you only create a local var, assign a value, but return the still empty class var.
To fix this, simply replace it with $this->notice[..] = ....
But there are also other logical issues. Why does CheckUname creates a user? It would be the task of NewAdmin to call CheckUname. Also you could merge the two database queries into one, asking, if there's a entry with the username or the password. There's more to fix/change, but that would be part of Code Review

Your $notice variable will always be "not set" below. All the variables will be reset after post processing. However, you can redirect to the url that has the $notice variable. For instance, after all the processing you can:
redirect_to('index.php?notice=1');
where redirect_to is a function that takes a url.
function redirect_to($path){
die("<meta http-equiv='refresh' content=0;URL='".$path."' />");
}
And then in your index.php, you can check the notice variable if it is set. There are different ways on how to do this though.
EDIT:
function redirect_to($path){
header("Location: " . $path);
}

Related

Cannot display alert once the user login inputs incorrect credentials PHP PDO

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>';
} ?>

Weird Undefined variable php error [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 years ago.
I'm working on a CMS using PHP OOP. And in this CMS, there's a feature which admins of a website can add another admin. What I did for this, is that I created a form and added the action. This file is called admin_new.php and goes like this:
<?php
if (isset($_POST['submit'])){
$username = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['pass'];
$groups = $_POST['groups'];
if($groups == "Main Admin"){
$level = 1;
}else if($groups == "Administrator"){
$level = 2;
}else if($groups == "Content Creator"){
$level = 3;
}else if($groups == "Social Media Manager"){
$level = 4;
}else{
$level = 5;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$notice['email_validation'] = "The email that you have entered is not a valid one";
}else{
$registration = new Register();
$notice = $registration->CheckUname($username,$email,$password,$groups‌​,$level);
}
}
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Add New Admin
<small>You can add new admin here</small>
</h1>
<ol class="breadcrumb">
<li class="active">addnewadmin.php</li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Required Information</h3>
</div>
<?php
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</div>
";
}
if(isset($notice['username_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
?>
<form role="form" method="POST" action="">
<div class="box-body">
<div class="form-group">
<label>User name</label>
<input type="text" class="form-control" placeholder="Enter username" name="uname" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Temporary password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter password" name="pass" required>
</div>
<div class="form-group">
<label>Group admin</label>
<select class="form-control" name="groups">
<option value="Main Admin">Main Admin</option>
<option value="Administrator">Administrator</option>
<option value="Content Creator">Content Creator</option>
<option value="Social Media Manager">Social Media Manager</option>
<option value="Analyst">Analyst</option>
</select>
</div>
</div>
<div class="box-footer">
Visit admin types documentation to know the differences between each admin.
</div>
<div class="box-footer">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
As you can see I have called a class named Register and this class also goes here:
<?php
class Register
{
protected $notice = array();
private $db;
public function __construct()
{
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function CheckUname($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$chk1 = $this->db->prepare("SELECT user_name FROM admins WHERE user_name = ?");
$chk1->bindParam(1,$username);
$chk1->execute();
if($chk1->rowCount() == 1)
{
$notice['username_exists'] = "Try different username";
return $this->notice;
}else{
$chk2 = $this->db->prepare("SELECT email_address FROM admins WHERE email_address = ?");
$chk2->bindParam(1,$email);
$chk2->execute();
if($chk2->rowCount() == 1)
{
$notice['email_exists'] = "The email address that you have entered is already exists in database";
return $this->notice;
}else{
$this->NewAdmin($username,$email,$password,$groups,$level);
$notice['success_message'] = "New admin was successfully added";
return $this->notice;
}
}
}
}
public function NewAdmin($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$reg = $this->db->prepare("INSERT INTO admins (user_name, email_address, password_hash, group_admin, date_joined, admin_level) VALUES ( ?, ?, ?, ?, NOW(), ?)");
$reg->bindParam(1,$username);
$reg->bindParam(2,$email);
$reg->bindParam(3,$password);
$reg->bindParam(4,$groups);
$reg->bindParam(5,$level);
$reg->execute();
}
}
public function getNotice()
{
return $this->notice;
}
}
?>
So it look basically fine and perfect but the ONLY problem with this is that, whenever I try to submit in the form, I get this error:
Undefined variable: groups‌​ in admin_new.php on line 22
And line 22 of admin_new.php is this:
$notice = $registration->CheckUname($username,$email,$password,$groups‌​,$level);
So you can see in the code that I have defined the $groups variable already and it gets the groups value in the form. Therefore I REALLY don't know why am I getting this error ?!
So if you know what should I do or what is my fault, please let me know.. I really really appreciate that. Thanks
You are getting this error since $groups in call
$notice = $registration->CheckUname($username,$email,$password,$groups‌​‌​,$level);
$groups is written in different encoding and has non-ASCII characters. Probably one or more of the letters is in different language typed. Just type it in regular latin or copy over from above one of the variable mention.
That should solve the problem.
Edit:
In addition to future problems, if you stumble upon similar issue, just convert code to ASCII encoding and back to UTF-8, and all NON-ASCII characters will be replaced with some generic replacement like underscore or questionmark
In below function you have used $groups1 instead of $groups >> Update with $groups.
public function NewAdmin($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$reg = $this->db->prepare("INSERT INTO admins (user_name, email_address, password_hash, group_admin, date_joined, admin_level) VALUES ( ?, ?, ?, ?, NOW(), ?)");
$reg->bindParam(1,$username);
$reg->bindParam(2,$email);
$reg->bindParam(3,$password);
$reg->bindParam(4,$groups1);
$reg->bindParam(5,$level);
$reg->execute();
}
}

php oop check if user exists?

I want to display an error if a username exists, however no error is being thrown.
the function is on the User.php and im trying to display an error from that function.
i referenced this, however it is not relevant to the OOP way.
User.php
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$row['user_name'] == $username;
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Index.php
<?php
session_start();
require_once 'User.php';
$guest = new User();
if($guest->is_logged())
{
$guest->redirect('profile');
}
if (isset($_POST['btn_signup']) ){
$username = htmlentities($_POST['txt_username']);
$unpass = htmlentities($_POST['txt_password']);
$password = password_hash($unpass, PASSWORD_BCRYPT, ['cost' => 12] );
$unemail = $_POST['txt_email'];
$email = filter_var($unemail, FILTER_VALIDATE_EMAIL);
$guest = new User();
if($email == ""){
$errors[]= "Enter a Email";
}
if($username == ""){
$errors[]= "Enter a Username please";
}
if($password == ""){
$errors[]= "Enter a Password";
}
if($guest->check_user_exists($username)){
$errors[]= "Username Already Taken";
}
if($guest->signup($email,$password,$username)){
$guest->redirect('profile');
die('didnt redirect');
}
else{
$errors[]= "Invalid Entry";
}
}
$title = "Home";
require_once 'layouts/header.php';
?>
<div class="container">
<div class="row">
<div class="col-md-6">
<?php
if(isset($errors))
{
foreach($errors as $error)
{
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
}
}
else if(isset($_GET['joined']))
{
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered <a href='index.php'>login</a> here
</div>
<?php
}
?>
<h1>Sign Up</h1>
<form action ="" method="POST">
<div class="form-group">
<label for="Email">Email address</label>
<input type="email" class="form-control" aria-describedby="emailHelp" name="txt_email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" aria-describedby="emailHelp" name="txt_username" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" class="form-control" aria-describedby="emailHelp" name="txt_password" placeholder="Enter password">
</div>
<button type="submit" name="btn_signup" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
return $stmt->fetchColumn() > 0; // fetchColumn return the number of rows selected
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Your function doesn't actually return or do anything. Return the result of fetch(), if it returns true - a result was found. If it returns false, there was no row matching the username. You don't need to check anything after that, as the fetch() method will only be true if a result was found.
Adjusted for that, your function would look like this
public function check_user_exists($username) {
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username' => $username));
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOExeception $e) {
echo $e->getMessage();
}
}
Also, its not a good idea to output errors directly (on a testing/development environment its fine, but on a live environment you should log it (error_log()) instead.
http://php.net/manual/en/pdostatement.fetch.php
public function ifUserAlreadyExist(string $email):bool{
$sql = "SELECT 1 FROM users WHERE email= :Email";
$statment = $this->conn->prepare($sql);
if (false === $statment) {
return false;
}
$statment->execute([':Email' => $email]);
return (bool)$statment->fetchColumn();
}
//You need to just select 1 object if is already exist and in this case function hint will be so handy, can set the function to boolean and see if it return true or false.
I hope I could help.

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.

How to call a function inside of another function in PHP OOP

I'm making my own custom CMS using PHP Object Oriented... I have made a page where a main admin of a site can add another admin. In order to do this I made this form:
<form role="form" method="POST" action="">
<div class="box-body">
<div class="form-group">
<label>User name</label>
<input type="text" class="form-control" placeholder="Enter username" name="uname" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Temporary password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter password" name="pass" required>
</div>
<div class="form-group">
<label>Group admin</label>
<select class="form-control">
<option>Main Admin</option>
<option>Administrator</option>
<option>Content Creator</option>
<option>Analyst</option>
</select>
</div>
</div>
<div class="box-footer">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Then I added this as action file:
if (isset($_POST['submit'])) {
$username = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['pass'];
$registration = new Register();
$registration->CheckUname($username,$email);
}
So as you can see I have called a class called Register and in this class I coded this:
class Register {
private $db;
public function __construct() {
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function CheckUname($username,$email) {
if(!empty($username)&&($email)) {
$chk1 = $this->db->prepare("SELECT username FROM admins WHERE user_name= ?");
$chk1->bindParam(1,$username);
$chk1->execute();
if($chk1->rowCount() == 1)
{
$notice['username_exists'] = "Try different username";
} else {
$chk2 = $this->db->prepare("SELECT email FROM admins WHERE email_address= ?");
$chk2->bindParam(1,$email);
$chk2->execute();
if($chk2->rowCount() == 1)
{
$notice['email_exists'] = "The email address that you have entered is already exists in database";
}else{
// I want to call the NewAdmin function here
}
}
}
}
public function NewAdmin($username,$email,$password) {
if(!empty($username)&&!empty($email)&&!empty($password)) {
$reg = $this->db->prepare("INSERT INTO admins (user_name, email_address, password_hash) VALUES ( '?', '?', '?')");
$reg->bindParam(1,$username);
$reg->bindParam(2,$email);
$reg->bindParam(2,$password);
$reg->execute();
}
}
}
Basically I tried to check if that username already exists or not then I also checked if the email exists and if not I want to call the NewAdmin function so the admin can be inserted to db. The problem is I don't know how to do that inside of the CheckUname function. Any help please ?
Also I've got another question which is why the errors that should be produced when the user enter a username or email that already exists in database does not shown! However I have set a variable for this:
if($chk1->rowCount() == 1) {
$notice['username_exists'] = "Try different username";
} else {
$chk2 = $this->db->prepare("SELECT email FROM admins WHERE email_address= ?");
$chk2->bindParam(1,$email);
$chk2->execute();
if($chk2->rowCount() == 1) {
$notice['email_exists'] = "The email address that you have entered is already exists in database";
} else {
// I want to call the NewAdmin function here
}
}
I have also set the error in the page like this:
if(isset($notice['username_exists'])) {
echo "<div class='alert alert-danger'><strong>Hey!</strong> ".$notice['username_exists'].".</div>";
}
if(isset($notice['email_exists'])) {
echo "<div class='alert alert-danger'><strong>Hey!</strong> ".$notice['email_exists'].".</div>";
}
But no errors appears on the page while submitting a username or an email that exists in the db!
Use $this->NewAdmin($username,$email,$password) inside the CheckUname() function of Register class. You can call same class function inside another class by using $this. $this represents the current class object.
I am just learning to use stack overflow, please don't approve this edit of mine...! Thanks..

Categories