Multiple AngularJS controllers in my code - php

I found two instructions on angularjs (http://softaox.info/category/angularjs/). However, I would like to combine it together - ie displaying, filtering and additionally editing the database directly from the website.
However, I have a problem with connecting two controllers on one page. The database reads, but when I want to edit, delete it, nothing happens. Will you help me solve the problem?
Here is my code
`index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>SoftAOX | AngularJS Sorting, Searching and Pagination of Data Table using PHP, MySQL</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-app="myApp" ng-controller="controller">
<div class="container">
<br/>
<h3 align="center">AngularJS Sorting, Searching and Pagination of Data Table using PHP, MySQL</a></h3>
<br/>
<div class="row">
<div class="col-sm-2 pull-left">
<label>PageSize:</label>
<select ng-model="data_limit" class="form-control">
<option>10</option>
<option>20</option>
<option>50</option>
<option>100</option>
</select>
</div>
<div class="col-sm-6 pull-right">
<label>Search:</label>
<input type="text" ng-model="search" ng-change="filter()" placeholder="Search" class="form-control" />
</div>
</div>
<br/>
<div class="row">
<div class="col-md-12" ng-show="filter_data > 0">
<table class="table table-striped table-bordered">
<thead>
<th>S.No</th>
<th>Name <a ng-click="sort_with('name');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Age <a ng-click="sort_with('age');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Email <a ng-click="sort_with('email');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Edit</th>
<th>Delete</th>
</thead>
<tbody>
<tr ng-repeat="data in names = (file | filter:search | orderBy : base :reverse) | beginning_data:(current_grid-1)*data_limit | limitTo:data_limit">
<td>{{data.id}}</td>
<td>{{data.name}}</td>
<td>{{data.age}}</td>
<td>{{data.email}}</td>
<td>
<button class="btn btn-success btn-xs" ng-click="update_data(data.id, data.name, data.email, data.age)">
<span class="glyphicon glyphicon-edit"></span> Edit
</button>
</td>
<td>
<button class="btn btn-danger btn-xs" ng-click="delete_data(data.id )">
<span class="glyphicon glyphicon-trash"></span> Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12" ng-show="filter_data == 0">
<div class="col-md-12">
<h4>No records found..</h4>
</div>
</div>
<div class="col-md-12">
<div class="col-md-6 pull-left">
<h5>Showing {{ searched.length }} of {{ entire_user}} entries</h5>
</div>
<div class="col-md-6" ng-show="filter_data > 0">
<div pagination="" page="current_grid" on-select-page="page_position(page)" boundary-links="true" total-items="filter_data" items-per-page="data_limit" class="pagination-small pull-right" previous-text="«" next-text="»"></div>
</div>
</div>
<div ng-app="myApp" ng-controller="cont1" ng-init="show_data()">
<div class="col-md-6">
<label>Name</label>
<input type="text" name="name" ng-model="name" class="form-control">
<br/>
<label>Email</label>
<input type="text" name="email" ng-model="email" class="form-control">
<br/>
<label>Age</label>
<input type="text" name="age" ng-model="age" class="form-control">
<br/>
<input type="hidden" ng-model="id">
<input type="submit" name="insert" class="btn btn-primary" ng-click="insert()" value="{{btnName}}">
</div>
</div>
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min.js"></script>
<script src="myapp.js"></script>
</body>
</html>
myapp.js
var app = angular.module('myApp', ['ui.bootstrap']);
app.filter('beginning_data', function() {
return function(input, begin) {
if (input) {
begin = +begin;
return input.slice(begin);
}
return [];
}
});
app.controller('controller', function($scope, $http, $timeout) {
$http.get('fetch.php').success(function(user_data) {
$scope.file = user_data;
$scope.current_grid = 1;
$scope.data_limit = 10;
$scope.filter_data = $scope.file.length;
$scope.entire_user = $scope.file.length;
});
$scope.page_position = function(page_number) {
$scope.current_grid = page_number;
};
$scope.filter = function() {
$timeout(function() {
$scope.filter_data = $scope.searched.length;
}, 20);
};
$scope.sort_with = function(base) {
$scope.base = base;
$scope.reverse = !$scope.reverse;
};
});
app.controller("cont1", function($scope, $http) {
$scope.btnName = "Insert";
$scope.insert = function() {
if ($scope.name == null) {
alert("Enter Your Name");
} else if ($scope.email == null) {
alert("Enter Your Email ID");
} else if ($scope.age == null) {
alert("Enter Your Age");
} else {
$http.post(
"insert.php", {
'name': $scope.name,
'email': $scope.email,
'age': $scope.age,
'btnName': $scope.btnName,
'id': $scope.id
}
).success(function(data) {
alert(data);
$scope.name = null;
$scope.email = null;
$scope.age = null;
$scope.btnName = "Insert";
$scope.show_data();
});
}
}
$scope.show_data = function() {
$http.get("display.php")
.success(function(data) {
$scope.names = data;
});
}
$scope.update_data = function(id, name, email, age) {
$scope.id = id;
$scope.name = name;
$scope.email = email;
$scope.age = age;
$scope.btnName = "Update";
}
$scope.delete_data = function(id) {
if (confirm("Are you sure you want to delete?")) {
$http.post("delete.php", {
'id': id
})
.success(function(data) {
alert(data);
$scope.show_data();
});
} else {
return false;
}
}
});
insert.php
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$info = json_decode(file_get_contents("php://input"));
if (count($info) > 0) {
$name = mysqli_real_escape_string($conn, $info->name);
$email = mysqli_real_escape_string($conn, $info->email);
$age = mysqli_real_escape_string($conn, $info->age);
$btn_name = $info->btnName;
if ($btn_name == "Insert") {
$query = "INSERT INTO insert_emp_info(name, email, age) VALUES ('$name', '$email', '$age')";
if (mysqli_query($conn, $query)) {
echo "Data Inserted Successfully...";
} else {
echo 'Failed';
}
}
if ($btn_name == 'Update') {
$id = $info->id;
$query = "UPDATE insert_emp_info SET name = '$name', email = '$email', age = '$age' WHERE id = '$id'";
if (mysqli_query($conn, $query)) {
echo 'Data Updated Successfully...';
} else {
echo 'Failed';
}
}
}
?>
display.php
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$output = array();
$query = "SELECT * FROM insert_emp_info";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$output[] = $row;
}
echo json_encode($output);
}
?>
fetch.php
<?php
$conn = new mysqli('localhost', 'root', '', 'test');
$query = "select distinct id, name, age, email from insert_emp_info order by id";
$result = $conn->query($query) or die($conn->error . __LINE__);
$fetch_data = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$fetch_data[] = $row;
}
}
$jResponse = json_encode($fetch_data);
echo $jResponse;
?>`

You can use the same controller for one page. I modified index.php and myapp.js file
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>SoftAOX | AngularJS Sorting, Searching and Pagination of Data Table using PHP & MySQL</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-app="myApp" ng-controller="controller">
<div class="container">
<br/>
<h3 align="center">AngularJS Sorting, Searching and Pagination of Data Table using PHP & MySQL</a></h3>
<br/>
<div class="row">
<div class="col-sm-2 pull-left">
<label>PageSize:</label>
<select ng-model="data_limit" class="form-control">
<option>10</option>
<option>20</option>
<option>50</option>
<option>100</option>
</select>
</div>
<div class="col-sm-6 pull-right">
<label>Search:</label>
<input type="text" ng-model="search" ng-change="filter()" placeholder="Search" class="form-control" />
</div>
</div>
<br/>
<div class="row">
<div class="col-md-12" ng-show="filter_data > 0">
<table class="table table-striped table-bordered">
<thead>
<th>Name <a ng-click="sort_with('name');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Gender <a ng-click="sort_with('gender');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Age <a ng-click="sort_with('age');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Email <a ng-click="sort_with('email');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Phone <a ng-click="sort_with('phone');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Organization <a ng-click="sort_with('organization');"><i class="glyphicon glyphicon-sort"></i></a></th>
</thead>
<tbody>
<tr ng-repeat="data in searched = (file | filter:search | orderBy : base :reverse) | beginning_data:(current_grid-1)*data_limit | limitTo:data_limit">
<td>{{data.name}}</td>
<td>{{data.gender}}</td>
<td>{{data.age}}</td>
<td>{{data.email}}</td>
<td>{{data.phone}}</td>
<td>{{data.organization}}</td>
<td>
<button class="btn btn-success btn-xs" ng-click="update_data(data.id, data.name, data.email, data.age)">
<span class="glyphicon glyphicon-edit"></span> Edit
</button>
</td>
<td>
<button class="btn btn-danger btn-xs" ng-click="delete_data(data.id )">
<span class="glyphicon glyphicon-trash"></span> Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12" ng-show="filter_data == 0">
<div class="col-md-12">
<h4>No records found..</h4>
</div>
</div>
<div class="col-md-12">
<div class="col-md-6 pull-left">
<h5>Showing {{ searched.length }} of {{ entire_user}} entries</h5>
</div>
<div class="col-md-6" ng-show="filter_data > 0">
<div pagination="" page="current_grid" on-select-page="page_position(page)" boundary-links="true" total-items="filter_data" items-per-page="data_limit" class="pagination-small pull-right" previous-text="«" next-text="»"></div>
</div>
</div>
</div>
<div class="col-md-6">
<label>Name</label>
<input type="text" name="name" ng-model="name" class="form-control">
<br/>
<label>Email</label>
<input type="text" name="email" ng-model="email" class="form-control">
<br/>
<label>Age</label>
<input type="text" name="age" ng-model="age" class="form-control">
<br/>
<input type="hidden" ng-model="id">
<input type="submit" name="insert" class="btn btn-primary" ng-click="insert()" value="{{btnName}}">
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min.js"></script>
<script src="myapp.js"></script>
</body>
</html>
myapp.js
var app = angular.module('myApp', ['ui.bootstrap']);
app.filter('beginning_data', function() {
return function(input, begin) {
if (input) {
begin = +begin;
return input.slice(begin);
}
return [];
}
});
app.controller('controller', function($scope, $http, $timeout) {
$http.get('fetch.php').success(function(user_data) {
$scope.file = user_data;
$scope.current_grid = 1;
$scope.data_limit = 10;
$scope.filter_data = $scope.file.length;
$scope.entire_user = $scope.file.length;
});
$scope.page_position = function(page_number) {
$scope.current_grid = page_number;
};
$scope.filter = function() {
$timeout(function() {
$scope.filter_data = $scope.searched.length;
}, 20);
};
$scope.sort_with = function(base) {
$scope.base = base;
$scope.reverse = !$scope.reverse;
};
$scope.btnName = "Insert";
$scope.insert = function() {
if ($scope.name == null) {
alert("Enter Your Name");
} else if ($scope.email == null) {
alert("Enter Your Email ID");
} else if ($scope.age == null) {
alert("Enter Your Age");
} else {
$http.post(
"insert.php", {
'name': $scope.name,
'email': $scope.email,
'age': $scope.age,
'btnName': $scope.btnName,
'id': $scope.id
}
).success(function(data) {
alert("Data Updated Successfully...");
$scope.name = null;
$scope.email = null;
$scope.age = null;
$scope.btnName = "Insert";
$scope.show_data();
});
}
}
$scope.show_data = function() {
$http.get('fetch.php').success(function(user_data) {
$scope.file = user_data;
$scope.current_grid = 1;
$scope.data_limit = 10;
$scope.filter_data = $scope.file.length;
$scope.entire_user = $scope.file.length;
});
}
$scope.update_data = function(id, name, email, age) {
$scope.id = id;
$scope.name = name;
$scope.email = email;
$scope.age = age;
$scope.btnName = "Update";
}
$scope.delete_data = function(id) {
if (confirm("Are you sure you want to delete?")) {
$http.post("delete.php", {
'id': id
})
.success(function(data) {
alert("Data Deleted Successfully...");
$scope.show_data();
});
} else {
return false;
}
}
});
delete.php
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$data = json_decode(file_get_contents("php://input"));
if (count($data) > 0) {
$id = $data->id;
$query = "DELETE FROM insert_emp_info WHERE id='$id'";
if (mysqli_query($conn, $query)) {
echo 'Data Deleted Successfully...';
} else {
echo 'Failed';
}
}
?>
insert.php
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$info = json_decode(file_get_contents("php://input"));
if (count($info) > 0) {
$name = mysqli_real_escape_string($conn, $info->name);
$email = mysqli_real_escape_string($conn, $info->email);
$age = mysqli_real_escape_string($conn, $info->age);
$btn_name = $info->btnName;
if ($btn_name == "Insert") {
$query = "INSERT INTO insert_emp_info(name, email, age) VALUES ('$name', '$email', '$age')";
if (mysqli_query($conn, $query)) {
echo "Data Inserted Successfully...";
} else {
echo 'Failed';
}
}
if ($btn_name == 'Update') {
$id = $info->id;
$query = "UPDATE insert_emp_info SET name = '$name', email = '$email', age = '$age' WHERE id = '$id'";
if (mysqli_query($conn, $query)) {
echo 'Data Updated Successfully...';
} else {
echo 'Failed';
}
}
}
?>
fetch.php
<?php
$conn = new mysqli('localhost', 'root', '', 'test');
$query = "select distinct id, name, age, email from insert_emp_info order by id";
$result = $conn->query($query) or die($conn->error . __LINE__);
$fetch_data = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$fetch_data[] = $row;
}
}
$jResponse = json_encode($fetch_data);
echo $jResponse;
?>

May use $rootScope to pass the info u need across different controller
Difference between $scope and $rootScope

Related

How yo insert data with image in AngularJs and PHP mysql

I have a CRUD table where I want to display users list with the profile pictures
I'm using AngularJs and Bootstrap
I have added upload file to the form and I'm able to insert to the DB but not able to save the uploaded file to my directory (/uploads)
My index form
<!DOCTYPE html>
<html>
<head>
<title>users</title>
<script src="jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="jquery.dataTables.min.js"></script>
<script src="angular-datatables.min.js"></script>
<script src="bootstrap.min.js"></script>
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="datatables.bootstrap.css">
</head>
<body ng-app="crudApp" ng-controller="crudController">
<div class="container" ng-init="fetchData()">
<br />
<h3 align="center">user's List</h3>
<br />
<div class="alert alert-success alert-dismissible" ng-show="success" >
×
{{successMessage}}
</div>
<div align="right">
<button type="button" name="add_button" ng-click="addData()" class="btn btn-success">Add</button>
</div>
<br />
<div class="table-responsive" style="overflow-x: unset;">
<table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
<thead>
<tr><!--data-visible="false"-->
<th width="10%">Image</th>
<th width="35%">First Name</th>
<th width="35%">Last Name</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="name in namesData">
<td>
<img id="{{name.id}}" ng-src="uploads/{{name.photo}}" class="thumbnail" height="50" width="50" >
</td>
<td>{{name.first_name}}</td>
<td>{{name.last_name}}</td>
<td><button type="button" ng-click="fetchSingleData(name.id)" class="btn btn-warning btn-xs">Edit</button></td>
<td><button type="button" ng-click="deleteData(name.id)" class="btn btn-danger btn-xs">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
<div class="modal fade" tabindex="-1" role="dialog" id="crudmodal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form method="post" ng-submit="submitForm()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">{{modalTitle}}</h4>
</div>
<div class="modal-body">
<div class="alert alert-danger alert-dismissible" ng-show="error" >
×
{{errorMessage}}
</div>
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" ng-model="first_name" class="form-control" />
</div>
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" ng-model="last_name" class="form-control" />
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="photo" ng-model="photo">
<label class="custom-file-label" for="photo">Choose file</label>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="hidden_id" value="{{hidden_id}}" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="{{submit_button}}" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<script>
var app = angular.module('crudApp', ['datatables']);
app.controller('crudController', function($scope, $http){
$scope.success = false;
$scope.error = false;
$scope.fetchData = function(){
$http.get('fetch_data.php').success(function(data){
$scope.namesData = data;
});
};
$scope.openModal = function(){
var modal_popup = angular.element('#crudmodal');
modal_popup.modal('show');
};
$scope.closeModal = function(){
var modal_popup = angular.element('#crudmodal');
modal_popup.modal('hide');
};
$scope.addData = function(){
$scope.modalTitle = 'Add Data';
$scope.submit_button = 'Insert';
$scope.openModal();
};
$scope.submitForm = function(){
$http({
method:"POST",
url:"insert.php",
data:{'photo':$scope.photo, 'first_name':$scope.first_name, 'last_name':$scope.last_name, 'action':$scope.submit_button, 'id':$scope.hidden_id}
}).success(function(data){
if(data.error != '')
{
$scope.success = false;
$scope.error = true;
$scope.errorMessage = data.error;
}
else
{
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.form_data = {};
$scope.closeModal();
$scope.fetchData();
}
});
};
$scope.fetchSingleData = function(id){
$http({
method:"POST",
url:"insert.php",
data:{'id':id, 'action':'fetch_single_data'}
}).success(function(data){
$scope.photo = data.photo;
$scope.first_name = data.first_name;
$scope.last_name = data.last_name;
$scope.hidden_id = id;
$scope.modalTitle = 'Edit Data';
$scope.submit_button = 'Edit';
$scope.openModal();
});
};
$scope.deleteData = function(id){
if(confirm("Are you sure you want to remove it?"))
{
$http({
method:"POST",
url:"insert.php",
data:{'id':id, 'action':'Delete'}
}).success(function(data){
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.fetchData();
});
}
};
});
</script>
Insert file which I'm unable to insert images
<?php
//insert.php
include('database_connection.php');
$form_data = json_decode(file_get_contents("php://input"));
$error = '';
$message = '';
$validation_error = '';
$first_name = '';
$last_name = '';
if($form_data->action == 'fetch_single_data')
{
$query = "SELECT * FROM tbl_sample WHERE id='".$form_data->id."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output['first_name'] = $row['first_name'];
$output['last_name'] = $row['last_name'];
}
}
elseif($form_data->action == "Delete")
{
$query = "
DELETE FROM tbl_sample WHERE id='".$form_data->id."'
";
$statement = $connect->prepare($query);
if($statement->execute())
{
$output['message'] = 'Data Deleted';
}
}
else
{
if(empty($form_data->first_name))
{
$error[] = 'First Name is Required';
}
else
{
$first_name = $form_data->first_name;
}
if(empty($form_data->last_name))
{
$error[] = 'Last Name is Required';
}
else
{
$last_name = $form_data->last_name;
}
if(empty($error))
{
if($form_data->action == 'Insert')
{
$data = array(
':first_name' => $first_name,
':last_name' => $last_name
);
$query = "
INSERT INTO tbl_sample
(first_name, last_name) VALUES
(:first_name, :last_name)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Inserted';
}
}
if($form_data->action == 'Edit')
{
$data = array(
':first_name' => $first_name,
':last_name' => $last_name,
':id' => $form_data->id
);
$query = "
UPDATE tbl_sample
SET first_name = :first_name, last_name = :last_name
WHERE id = :id
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Edited';
}
}
}
else
{
$validation_error = implode(", ", $error);
}
$output = array(
'error' => $validation_error,
'message' => $message
);
}
echo json_encode($output);
?>
Fetch table
<?php
//fetch_data.php
include('database_connection.php');
$query = "SELECT * FROM tbl_sample ORDER BY id";
$statement = $connect->prepare($query);
if($statement->execute())
{
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
?>
I'm using PDO connection
How I can add insert image among the above function

Wanted to add some edit/delete button on my comment system reply part

INDEX.PHP
<body>
<br />
<h2 align="center">Comment System using PHP and Ajax</h2>
<br />
<div class="container">
<form method="POST" id="comment_form" >
<div class="form-group w-50">
<input type="text" name="comment_name" id="comment_name" class="form-control" value="<?php echo $_SESSION['username'];?>" readonly/>
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-inline ">
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Comment" />
</div>
<input type="reset" value="Cancel" class="btn btn-primary" style="margin-left: 5px;">
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();//CONVERTS/STORES THE FORM INTO URL IN CODE
$.ajax({
url:"add_comment.php",//WHERE WILL THE INFO GO ---- OR ---- SENDS REQUEST/GOES TO ADD_COMMENT.PHP and records the info
method:"POST",//FOUND IN THE FORM METHOD, telss what kind of method to use to send the data to server so we use ---POST---
data:form_data,//data: it is the variable/code we used to convert/store the form into url in code
dataType:"JSON",
success:function(data)//Will be called if the sending of data to the comment.php is successful
{ //and success will receive the same data/the form_data from server OR DATA WAS RECEIVED BY SUCCESS
if(data.error != '')//check if there is no error in the process and DISPLAYS THE DATA BELOW
{
$('#comment_form')[0].reset();//as Array, it starts with 0 and the .reset() JUST RESETS THE FORM FIELD/OFF THE AUTO COMPLETE
$('#comment_message').html(data.error);//outputs if there is an error or not
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()//loads all the comment
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)//DISPLAYS DATA BELOW if success
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();// if click it will focus on the comment name
});
});
</script>
ADD_COMMENT.php
<?php
session_start();
//add_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$error = '';
$comment_name = $_SESSION['username'];
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')//if this condition runs then there is no validation error or whatsoever
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
FETCH_COMMENT.php
where the reply part is
<?php
session_start();
//fetch_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
$delete = '';
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>';
$output .= get_reply_comment($connect, $row["comment_id"]);
}
echo $output;
function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
$output .= '
<div class="panel panel-default" style="margin-left:'.$marginleft.'px">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($connect, $row["comment_id"], $marginleft);
}
}
return $output;
}
?>

Why won't my first_name field send to database?

I'm using a comment form with a first name field that is supposed to send to the database with the comments, but for some reason even though I have the column first_name in the database it won't send, any suggestions?
P.S
I am aware of any SQL Injection vulnerabilities but thank you for being concerned! I plan to just focus on this problem before going further.
Thank you for helping!
<?php
session_start();
$loggedIn = false;
if (isset($_SESSION['loggedIn']) && isset($_SESSION['name'])) {
$loggedIn = true;
}
$conn = new mysqli('localhost', '', '', 'profiles2');
function createCommentRow($data) {
global $conn;
$response = '
<div class="comment">
<div class="user">'.$data['name'].' <span class="time">'.$data['createdOn'].'</span></div>
<div class="userComment">'.$data['comment'].'</div>
<div class="reply">REPLY</div>
<div class="replies">';
$sql = $conn->query("SELECT replies.id, name, comment, DATE_FORMAT(replies.createdOn, '%Y-%m-%d') AS createdOn FROM replies INNER JOIN users ON replies.userID = users.id WHERE replies.commentID = '".$data['id']."' ORDER BY replies.id DESC LIMIT 1");
while($dataR = $sql->fetch_assoc())
$response .= createCommentRow($dataR);
$response .= '
</div>
</div>
';
return $response;
}
if (isset($_POST['getAllComments'])) {
$start = $conn->real_escape_string($_POST['start']);
$response = "";
$sql = $conn->query("SELECT comments.id, name, comment, DATE_FORMAT(comments.createdOn, '%Y-%m-%d') AS createdOn FROM comments INNER JOIN users ON comments.userID = users.id ORDER BY comments.id DESC LIMIT $start, 20");
while($data = $sql->fetch_assoc())
$response .= createCommentRow($data);
exit($response);
}
if (isset($_POST['addComment'])) {
$comment = $conn->real_escape_string($_POST['comment']);
$isReply = $conn->real_escape_string($_POST['isReply']);
$commentID = $conn->real_escape_string($_POST['commentID']);
$first_name = $conn->real_escape_string($_POST['first_name']);
if ($isReply != 'false') {
$conn->query("INSERT INTO replies (comment, commentID, userID, createdOn) VALUES ('$comment', '$commentID', '".$_SESSION['userID']."', NOW())");
$sql = $conn->query("SELECT replies.id, name, comment, DATE_FORMAT(replies.createdOn, '%Y-%m-%d') AS createdOn FROM replies INNER JOIN users ON replies.userID = users.id ORDER BY replies.id DESC LIMIT 1");
} else {
$conn->query("INSERT INTO comments (userID, first_name, comment, createdOn) VALUES ('".$_SESSION['userID']."','".$first_name."','$comment',NOW())");
$sql = $conn->query("SELECT comments.id, name, comment, DATE_FORMAT(comments.createdOn, '%Y-%m-%d') AS createdOn FROM comments INNER JOIN users ON comments.userID = users.id ORDER BY comments.id DESC LIMIT 1");
}
$data = $sql->fetch_assoc();
exit(createCommentRow($data));
}
if (isset($_POST['register'])) {
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$sql = $conn->query("SELECT id FROM users WHERE email='$email'");
if ($sql->num_rows > 0)
exit('failedUserExists');
else {
$ePassword = password_hash($password, PASSWORD_BCRYPT);
$conn->query("INSERT INTO users (name,email,password,createdOn) VALUES ('$name', '$email', '$ePassword', NOW())");
$sql = $conn->query("SELECT id FROM users ORDER BY id DESC LIMIT 1");
$data = $sql->fetch_assoc();
$_SESSION['loggedIn'] = 1;
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['userID'] = $data['id'];
exit('success');
}
} else
exit('failedEmail');
}
if (isset($_POST['logIn'])) {
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$sql = $conn->query("SELECT id, password, name FROM users WHERE email='$email'");
if ($sql->num_rows == 0)
exit('failed');
else {
$data = $sql->fetch_assoc();
$passwordHash = $data['password'];
if (password_verify($password, $passwordHash)) {
$_SESSION['loggedIn'] = 1;
$_SESSION['name'] = $data['name'];
$_SESSION['email'] = $email;
$_SESSION['userID'] = $data['id'];
exit('success');
} else
exit('failed');
}
} else
exit('failed');
}
$sqlNumComments = $conn->query("SELECT id FROM comments");
$numComments = $sqlNumComments->num_rows;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>YouTube Comment System</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style type="text/css">
.comment {
margin-bottom: 20px;
}
.user {
font-weight: bold;
color: black;
}
.time, .reply {
color: gray;
}
.userComment {
color: #000;
}
.replies .comment {
margin-top: 20px;
}
.replies {
margin-left: 20px;
}
#registerModal input, #logInModal input {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="modal" id="registerModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Registration Form</h5>
</div>
<div class="modal-body">
<input type="text" id="userName" class="form-control" placeholder="Your Name">
<input type="email" id="userEmail" class="form-control" placeholder="Your Email">
<input type="password" id="userPassword" class="form-control" placeholder="Password">
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="registerBtn">Register</button>
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal" id="logInModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Log In Form</h5>
</div>
<div class="modal-body">
<input type="email" id="userLEmail" class="form-control" placeholder="Your Email">
<input type="password" id="userLPassword" class="form-control" placeholder="Password">
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="loginBtn">Log In</button>
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="container" style="margin-top:50px;">
<div class="row">
<div class="col-md-12" align="right">
<?php
if (!$loggedIn)
echo '
<button class="btn btn-primary" data-toggle="modal" data-target="#registerModal">Register</button>
<button class="btn btn-success" data-toggle="modal" data-target="#logInModal">Log In</button>
';
else
echo '
Log Out
';
?>
</div>
</div>
<div class="row" style="margin-top: 20px;margin-bottom: 20px;">
<div class="col-md-12" align="center">
<iframe width="560" height="315" src="https://www.youtube.com/embed/u2O_QyPfdpE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
<div class="form">
<form action="search_page.php" method="post">
<input type="text" name="search" />
<button>Search</button>
</form>
</div>
<div class="row">
<div class="col-md-12">
<form method="POST" action="index.php">
<input type="text" name="first_name" placeholder="First Name...">
<textarea class="form-control" id="mainComment" placeholder="Add Public Comment" cols="30" rows="2"></textarea><br>
<input type="submit" value="Comment" style="float:right" class="btn-primary btn" onclick="isReply = false;" id="addComment">
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h2><b id="numComments"><?php echo $numComments ?> Comments</b></h2>
<div class="userComments">
</div>
</div>
</div>
</div>
<div class="row replyRow" style="display:none">
<div class="col-md-12">
<textarea class="form-control" id="replyComment" placeholder="Add Public Comment" cols="30" rows="2"></textarea><br>
<button style="float:right" class="btn-primary btn" onclick="isReply = true;" id="addReply">Add Reply</button>
<button style="float:right" class="btn-default btn" onclick="$('.replyRow').hide();">Close</button>
</div>
</div>
<script src="http://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
var isReply = false, commentID = 0, max = <?php echo $numComments ?>;
$(document).ready(function () {
$("#addComment, #addReply").on('click', function () {
var comment;
if (!isReply)
comment = $("#mainComment").val();
else
comment = $("#replyComment").val();
if (comment.length > 5) {
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
addComment: 1,
comment: comment,
isReply: isReply,
commentID: commentID
}, success: function (response) {
max++;
$("#numComments").text(max + " Comments");
if (!isReply) {
$(".userComments").prepend(response);
$("#mainComment").val("");
} else {
commentID = 0;
$("#replyComment").val("");
$(".replyRow").hide();
$('.replyRow').parent().next().append(response);
}
}
});
} else
alert('Please Check Your Inputs');
});
$("#registerBtn").on('click', function () {
var name = $("#userName").val();
var email = $("#userEmail").val();
var password = $("#userPassword").val();
if (name != "" && email != "" && password != "") {
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
register: 1,
name: name,
email: email,
password: password
}, success: function (response) {
if (response === 'failedEmail')
alert('Please insert valid email address!');
else if (response === 'failedUserExists')
alert('User with this email already exists!');
else
window.location = window.location;
}
});
} else
alert('Please Check Your Inputs');
});
$("#loginBtn").on('click', function () {
var email = $("#userLEmail").val();
var password = $("#userLPassword").val();
if (email != "" && password != "") {
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
logIn: 1,
email: email,
password: password
}, success: function (response) {
if (response === 'failed')
alert('Please check your login details!');
else
window.location = window.location;
}
});
} else
alert('Please Check Your Inputs');
});
getAllComments(0, max);
});
function reply(caller) {
commentID = $(caller).attr('data-commentID');
$(".replyRow").insertAfter($(caller));
$('.replyRow').show();
}
function getAllComments(start, max) {
if (start > max) {
return;
}
$.ajax({
url: 'index.php',
method: 'POST',
dataType: 'text',
data: {
getAllComments: 1,
start: start
}, success: function (response) {
$(".userComments").append(response);
getAllComments((start+20), max);
}
});
}
</script>
</body>
</html>
It appears to me that you are making an Ajax call with addComment set to 1, but you are not sending the first_name, you are only sending comment, commentID and isReply.
Your form needs an ID on the first_name
<form method="POST" action="index.php">
<input type="text" name="first_name" id='first_name' placeholder="First Name...">
Then, send the first name value in your addComment ajax call like this:
First, get the value of first_name
var first_name = $("first_name").val()
...
Then add it to ajax call:
data: {
first_name:first_name,
addComment: 1,
comment: comment,
isReply: isReply,
commentID: commentID

PHP MySQL Ajax form data output

I have a code that I have been trying to run for days without success, could anyone look at it and help figure where I am going crazy?
here is report.js:
$(document).ready(function() {
$('#navReport').addClass('active');
// order date picker
$('#startDate').datepicker();
// order date picker
$('#endDate').datepicker();
$('#getReportForm')
.unbind('submit')
.bind('submit', function() {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
var personId = $('#personId').val();
if (startDate == '' || endDate == '' || personId == '') {
if (startDate == '') {
$('#startDate')
.closest('.form-group')
.addClass('has-error');
$('#startDate').after(
'<p class="text-danger">The Start Date is required</p>'
);
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
}
if (endDate == '') {
$('#endDate')
.closest('.form-group')
.addClass('has-error');
$('#endDate').after(
'<p class="text-danger">The End Date is required</p>'
);
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
}
if (personId == '') {
$('#personId')
.closest('.form-group')
.addClass('has-error');
$('#personId').after(
'<p class="text-danger">Person Name is required</p>'
);
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
}
} else {
$('.form-group').removeClass('has-error');
$('.text-danger').remove();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'text',
success: function(response) {
var mywindow = window.open(
'',
'Child Behavior Management System',
'height=400,width=600'
);
mywindow.document.write('<html><head><title>Report</title>');
mywindow.document.write('</head><body>');
mywindow.document.write(response);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.print();
mywindow.close();
} // /success
}); // /ajax
} // /else
console.log(personId, startDate, endDate);
return false;
});
});
Here is getReport.php:
<?php
require_once 'core.php';
if($_POST) {
$personId = $_POST['personId'];
$startDate = $_POST['startDate'];
$date = DateTime::createFromFormat('m/d/Y',$startDate);
$start_date = $date->format("Y-m-d");
$endDate = $_POST['endDate'];
$format = DateTime::createFromFormat('m/d/Y',$endDate);
$end_date = $format->format("Y-m-d");
$table = '';
$sql = "SELECT notes.note_id, notes.note_content, notes.person_id,
notes.note_date, notes.note_status, persons.persons_name
FROM notes INNER JOIN persons ON notes.person_id = persons.persons_id
WHERE notes.person_id = '$personId' AND notes.note_date
BETWEEN CAST('$start_date' AS DATE) AND CAST('$end_date' AS DATE)
AND notes.note_status = 1"
$query = $connect->query($sql);
$table = '
<table border="1" cellspacing="0" cellpadding="0" style="width:100%;">
<tr>
<th>Date</th>
<th>Note</th>
<th>Resident</th>
</tr>
<tr>';
while ($result = $query->fetch_assoc()) {
$table .= '<tr>
<td><center>'.$result['notes.note_date'].'</center></td>
<td><center>'.$result['notes.note_content'].'</center></td>
<td><center>'.$result['persons.persons_name'].'</center></td>
</tr>';
}
$table .= '
</tr>
</table>
';
echo $table;
}
?>
And here is report.php:
<?php require_once 'includes/header.php'; ?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<i class="glyphicon glyphicon-check"></i> Generate Report
</div>
<!-- /panel-heading -->
<div class="panel-body">
<form class="form-horizontal" action="php_action/getReport.php" method="post" id="getReportForm">
<div class="form-group">
<label for="personId" class="col-sm-2 control-label">Resident</label>
<div class="col-sm-10">
<select type="text" class="form-control" id="personId" placeholder="Resident" name="personId" >
<option value="">~~SELECT~~</option>
<?php
$sql = "SELECT persons_id, persons_name, persons_status FROM persons WHERE persons_status = 1";
$result = $connect->query($sql);
while($row = $result->fetch_array()) {
echo "<option value='".$row[0]."'>".$row[1]."</option>";
} // while ?>
</select>
</div>
</div> <!-- /form-group-->
<div class="form-group">
<label for="startDate" class="col-sm-2 control-label">Start Date</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="startDate" name="startDate" placeholder="Start Date" />
</div>
</div>
<div class="form-group">
<label for="endDate" class="col-sm-2 control-label">End Date</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="endDate" name="endDate" placeholder="End Date" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success" id="generateReportBtn"> <i class="glyphicon glyphicon-ok-sign"></i>
Generate Report</button>
</div>
</div>
</form>
</div>
<!-- /panel-body -->
</div>
</div>
<!-- /col-dm-12 -->
</div>
<!-- /row -->
<script src="custom/js/report.js"></script>
<?php require_once 'includes/footer.php'; ?>
I would love to have expert solution to this. I have looked for solution almost the entire night but no joy. The popup is not firing when I select the preferred person, start and end dates based on the query.

Page For Entering One-time-password Does Not Appear After Sending OTP to User Using PHP

I am working on a class project, but I am stuck a little bit.
I am working on a login form, which authorizes a user to enter a one-time-password that is being sent to the user's email.
So far, the otp and the current time and date are being saved to the database successfully.
I have also managed to send the code to the user's email but once it is sent, the page does not navigate to the form where the user is supposed to enter the one-time-password.
All that works is this part here:
<form method="post" action="">
.
.
.
<div class="form-top-left">
<h3>Log in</h3>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
<p id="profile-name" class="profile-name-card"></p>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<span id="reauth-email" class="reauth-email"></span>
<input type="email" id="inputEmail" name="form_email" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="form_password" id="inputPassword" class="form-control" placeholder="Password" required>
<input class="btn btn-lg btn-primary btn-block btn-signin" type="submit" name="login" value="Sign in">
<div class="text-center">
<a href="wlt_passwordreset.php" class="forgot-password">
Forgot the password?
</a>
</div>
<hr>
<form class="form-signin" action="http://localhost/Dreamweaver/regist.php">
<input type="submit" value="Sign Up" class="btn btn-lg btn-primary btn-block btn-signup">
.
.
.
</form>
What could be the problem?? Can someone please help me on this.Thank you.
Here is the html part:
<html>
<head>
<title>Home</title>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-static-top" role="navigation" style="margin-bottom:20px">
<div class="navbar-header">
<a class="navbar-inverse" href="http://localhost/Dreamweaver/index.php"><img src="img/neza.png" alt="logo"></a>
</div>
<!-- /.navbar-header -->
</nav>
</div>
<div class="container">
<div class="card card-container">
<form class="form-signin" method="post" action="">
<?php
if($success == 1) {
?>
<div class="form-wrap">
<h2>A verification code has been sent to <?php $row["form_email"] ?>. Please enter it below to verify your account.</h2>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<div class="form-group">
<label for="key">Verification Code:</label>
<input type="password" name="otp" id="key" class="form-control">
</div>
<input type="submit" id="btn-login" class="btn btn-custom btn-lg btn-block" name="submit_otp" value="Verify Account">
<h2>Did not receive the verification code?</h2>
<!---- <form id="login-form"> ------>
<input type="submit" id="btn-login" class="btn btn-custom1 btn-lg btn-block" value="Resend Code">
<!----- </form> ----->
</div> <!---/form-wrap----->
<?php
} elseif ($success == 2) {
header("Location: fomu.php");
}else {
?>
<div class="form-top-left">
<h3>Log in</h3>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
<p id="profile-name" class="profile-name-card"></p>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<span id="reauth-email" class="reauth-email"></span>
<input type="email" id="inputEmail" name="form_email" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="form_password" id="inputPassword" class="form-control" placeholder="Password" required>
<input class="btn btn-lg btn-primary btn-block btn-signin" type="submit" name="login" value="Sign in">
<div class="text-center">
<a href="wlt_passwordreset.php" class="forgot-password">
Forgot the password?
</a>
</div>
<hr>
<form class="form-signin" action="http://localhost/Dreamweaver/regist.php">
<input type="submit" value="Sign Up" class="btn btn-lg btn-primary btn-block btn-signup">
</form>
<?php
}
?>
</form>
</div><!-- /card-container -->
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="text-centre">
<a class="text-new" href="#">Privacy|</a>
<a class="text-new" href="#">Security|</a>
<a class="text-new" href="#">Fees</a>
</div>
</div> <!---/row--->
</div> <!---/container--->
</div><!-- /container1-->
<!-- jQuery -->
<script src="js/jquery-1.11.1.min.js"></script>
<script src="logwin.js"></script>
<script src="bootstrap.min.js"></script>
<script src="js/mscript.js"></script>
<script src="js/scripts.js"></script>
<script src="js/jquery.backstretch.min.js"></script>
</body>
</html>
Here is the dbtest.php used to INSERT TO the db:
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "myPassword";
private $database = "myDB";
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$resultset = [];
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function updateQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function insertQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function deleteQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function generate_OTP($length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789'){
$chars_length = (strlen($chars) - 1);
$string = $chars{rand(0, $chars_length)};
for ($i = 1; $i < $length; $i = strlen($string)){
$r = $chars{rand(0, $chars_length)};
if ($r != $string{$i - 1}) $string .= $r;
}
return $string;
}
function getConn(){
return $this->conn;
}
}
?>
Here is the PHP code that I am referring to:
<?php
session_start();
$success = "";
require_once('dbtest.php');
$db = new DBController();
if(isset($_POST["login"])) {
$result = $db->runQuery("SELECT * FROM registered_users WHERE
form_email='" . $_POST["form_email"] . "' AND status = 'active' ");
if (!empty($result)){
foreach($result as $row){
//Verify password
if ( $row['form_password'] === crypt( $_POST["form_password"], $row['form_password'] ) ) {
$otp = $db->generate_OTP();
require_once("mail_function.php");
$mail_status = sendOTP($_POST["form_email"],$otp);
if($mail_status == 1) {
$query = "UPDATE registered_users SET `otp` = '" . $otp . "', `is_expired` = 0, `create_at` = '" . date("Y-m-d H:i:s"). "' WHERE form_email = '" . $_POST["form_email"] . "'";
$result = $db->updateQuery($query);
if(!empty($result)){
$current_id = mysqli_insert_id($db->getConn());
if(!empty($current_id)) {
$success = 1;
}
}
}
}
else {
$error_message = "Email or password is incorrect!";
}
}
}
else {
$error_message = "Email or password is incorrect!";
}
}
if(isset($_POST["submit_otp"])) {
$result = $db->runQuery("SELECT * FROM registered_users WHERE otp='" . $_POST["otp"] . "' AND is_expired!=1 AND NOW() <= DATE_ADD(create_at, INTERVAL 24 HOUR)");
if(!empty($result)) {
$query = "UPDATE registered_users SET `is_expired` = 1 WHERE otp = '" . $_POST["otp"] . "'";
$result = $db->updateQuery($query);
$success = 2;
}else {
$success = 1;
$error_message = "Invalid OTP!";
}
}
?>
Bad syntax: you have the <html> tag inside the <form>, that should not happen. The <html> should only be used once at the beginning to open it and end at the end to close it.
UPDATE:
Also, mysqli_insert_id() expects the link identifier of the last mysqli_connect used. In your code, youre supplying it with $conn, but $conn is not whats being used in the DBController class.
To fix this:
add this method to you DBController class:
function getConn(){
return $this->conn;
}
then change this:
$result = $db_handle->insertQuery($query);
if (!empty($result)) {
$current_id = mysqli_insert_id($conn);
if (!empty($current_id)) {
$success = 1;
}
}
to this:
$result = $db_handle->insertQuery($query);
if (!empty($result)) {
$current_id = mysqli_insert_id($db_handle->getConn());
if (!empty($current_id)) {
$success = 1;
}
}
UPDATE2:
You asked this "After adding this method function getConn(){ return $this->conn; } I find some errors working with mysqli_fetch_array(). I am using if(!empty($result->num_rows)){while($rowcount = $result->fetch_assoc()){$row['password'];}}"
look at what runQuery() does:
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
it runs your SQL query, then if there are any results, it returns an array $resultset.. The problem is that you are not accounting for empty results. So lets add that, change it to this:
function runQuery($query) {
$resultset = [];
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
Now it will return an empty array, or an array with your results.
And you can call it with:
$result = $db->runQuery("SELECT * FROM registered_users WHERE form_email='" . $_POST["form_email"] . "' AND status = 'active' ");
and use $result like this:
if(!empty($result)){
foreach($result as $row){
echo $row['password'];
}
}

Categories