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
Related
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
I would like to write a communicate during registration, when user already exists. With this code it redirects me on another page. I would like to see this communicate under form. I tried like this but it still redirects me on another page. I also would like to do by function 'response', but it didn't work.
register3.php
<html>
<?php
if (isset($_POST["register"])) {
$connection = new mysqli("localhost", "root", "root", "users");
$email = $connection->real_escape_string($_POST["email"]);
$password = sha1($connection->real_escape_string($_POST["password"]));
$imie = $connection->real_escape_string($_POST["imie"]);
$nazwisko = $connection->real_escape_string($_POST["nazwisko"]);
$data2 = $connection->query("SELECT * FROM user WHERE email='$email'");
if($data2->num_rows >0) {
exit('<font color="red">This user already exists</font>');
} else
$data = $connection->query("INSERT INTO user
(email, password, imie, nazwisko)
VALUES ('$email', '$password', '$imie', '$nazwisko')");
if (($data === false) && ($email != "" || $password != "")) {
echo '<script>alert("Wypełnij poprawnie pola!")</script>';
} else {
echo '<script>alert("Zostałeś zarejestrowany, zaloguj się.")</script>';
}
}
?>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-16">
<link rel="stylesheet" href="style_reg.css">
<title>Strona o nalewkach - Login </title>
</head>
<body>
<nav class="navbar">
<div class="content">
<div class="logo" >Nalewki z tradycją</div>
<ul class="menu-list">
<div class="icon cancel-btn">
<i class="fas fa-times"></i>
</div>
<li>Home</li>
<li>Przepisy na nalewki</li>
<li>Logowanie</li>
<li>Galeria</li>
<li>Kontakt</li>
</ul>
<div class="icon menu-btn">
<i class="fas fa-bars"></i>
</div>
</div>
</nav>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-50">
<form class="login100-form validate-form" method="POST" action="register3.php">
<span class="login100-form-title p-b-33">
Zarejestruj się do świata nalewek
</span>
<div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<input class="input100" type="text" name="email" placeholder="Email">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required">
<input class="input100" type="password" name="password" placeholder="Haslo">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required">
<input class="input100" type="text" name="imie" placeholder="Imie">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required">
<input class="input100" type="text" name="nazwisko" placeholder="nazwisko">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="container-login100-form-btn m-t-20">
<input type="submit" class="login100-form-btn" value="Zarejestruj" name="register">
</div>
<p id="response"></p>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#login").on('click', function () {
var email = $("#email").val();
var password = $("#password").val();
if (email == "" || password == "")
alert('Wypelnij poprawnie formularz');
else {
$.ajax({
url: 'register3.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password,
imiePHP: imie,
nazwiskoPHP: nazwisko
},
success: function(response) {
$("#response").html(response);
if (response.indexOf('success') >=0)
alert('Wypelnij poprawnie formularz');
},
dataType: 'text'
}
);
}
});
});
</script>
</body>
</html>
You use jQuery but you never import it, put this in hour head section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In your javascript you have this
$("#login").on('click', function () {
but I don't see any element with id login. To prevent form submition just jsut replace the above line with this
$("form").on('submit', function (e) {
e.preventDefault();
Give each of your form inputs an id, they don't have them now, so as to be able to do that
var email = $("#email").val();
var password = $("#password").val();
var imie = $("#imie").val();
var nazwisko = $("#nazwisko").val();
Prepare separate php file for your ajax call, can't use same register3.php for that, because php file has to be executed to give you a response, you cannot do that on register3.php without page reload.
In that other php file, for example email-check.php, check if user exists and if not register and return response ok
$.ajax({
url: 'email-check.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password,
imiePHP: imie,
nazwiskoPHP: nazwisko
},
success: function(response) {
if (response == 'ok') {
//new user registered succesfully
//log user in or redirect to login page
} else {
//user already exists
$("#response").html('This email address is taken');
},
});
This is a commenting system using jQuery, Ajax, PHP, MySQL, and HTML. When I click the Edit button, it displays the comment of the first row of the table of MySQL instead of the row that I selected. However, once I edit it, it does correct the correct row. I can’t figure out a way to display the comment of the row that I want to edit.
I can display the correct comment_id of the row into the textarea, but it displays the comment of the first row into the textarea.
Here is the test case code:
MySQL table has two rows: comment_id as primary row and comment for text. I named the database: testcaseedit_db, and the table: tbl_comment.
index.php
<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>
<div id="display_comment"></div>
<div id="comment_message"></div>
<div id="display_edit"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
let count = 0;
$(document).on('click change', '.edit, .submit', function(e) {
if ($(this).is('.edit')) {
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
var closestDiv = $('button').closest('div.panel');
$('.div.panel').not(closestDiv.next('.div.panel')).hide();
closestDiv.next('div.panel').slideToggle(100);
var commentEdit = $('#display_comment').find('#editable').html();
++count;
const htmlString =
`<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">
<div class="input-group-prepend">
<textarea name="comment" id="comment${count}" class="form-control" rows="30" cols="160">
${commentEdit} ${comment_id}
</textarea>
</div>
<div class="input-group-prepend">
<input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
<input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
</div>
</form>`;
$('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);
} else if ($(this).is('.submit')) {
$.ajax({
url:"edit.php",
method:"POST",
data: new FormData(this),
contentType: false,
processData: false,
success:function(data)
{
if(data.error != '') {
$('#comment_form')[0].reset();
$('#comment_id').val(comment_id);
$('#comment').val(comment);
}
}
});
location.reload();
$(this).closest('form').submit();
e.stopPropagation();
} else {
return false;
}
});
// Fetch comment
function load_comment(){
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data){
$('#display_comment').html(data);
}
})
};
load_comment();
// End of (document).ready(function){}
});
</script>
</body>
</html>
fetch.php
<?php
$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');
$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row) {
$output .= '
<div class="panel panel-default">
<div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
<div class="panel-body"><b> Comment: </b> <br> <span id="editable"> '.$row["comment"].' </span> </div>
<div class="panel-footer" align="right">
<button type="button" class="btn btn-default edit" id="'.$row["comment_id"].'">Edit</button>
</div>
</div>
';
}
echo $output;
?>
edit.php
<?php
$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');
$comment_id = $_POST["comment_id"];
$comment = $_POST["comment"];
if ( $error == '' && !empty($_POST["comment"]) ) {
$query = "UPDATE tbl_comment SET comment = :comment WHERE comment_id = :comment_id ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':comment_id' => $comment_id,
':comment' => $comment
)
);
header("Location: index.php");
}
$data = array(
'error' => $error
);
echo $error;
?>
Here is the solution:
In fetch.php file, I made the id for each variable into an array as follows:
<button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'" id[2]="'.$row["comment"].'">Edit</button>
And in index.php file, I grabbed the value of each variable as follows:
var comment_id = $(this).attr("id[1]");
$('#comment_id').val(comment_id);
var comment = $(this).attr("id[2]");
$('#comment').val(comment);
Then I displayed the comment variable inside the textarea as follows:
<textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">${comment}</textarea>
Here is the full code for index.php and fetch.php. I left edit.php untouched:
index.php
<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>
<div id="display_comment"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
let count = 0;
$(document).on('click change', '.edit, .submit', function(e) {
if ($(this).is('.edit')) {
var comment_id = $(this).attr("id[1]");
$('#comment_id').val(comment_id);
var comment = $(this).attr("id[2]");
$('#comment').val(comment);
var closestDiv = $('button').closest('div.panel');
$('div.panel').not(closestDiv.next('div.panel')).hide();
closestDiv.next('div.panel').slideToggle(100);
++count;
const htmlString =
`<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">
<div class="input-group-prepend">
<textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">
${comment}
</textarea>
</div>
<div class="input-group-prepend">
<input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
<input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
</div>
</form>`;
$('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);
} else if ($(this).is('.submit')) {
$.ajax({
url:"edit.php",
method:"POST",
data: new FormData(this),
contentType: false,
processData: false,
success:function(data)
{
if(data.error != '') {
$('#comment_form')[0].reset();
$('#comment_id').val(comment_id);
$('#comment').val(comment);
}
}
});
location.reload();
$(this).closest('form').submit();
e.stopPropagation();
} else {
return false;
}
});
// Fetch comment
function load_comment(){
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data){
$('#display_comment').html(data);
}
})
};
load_comment();
// End of (document).ready(function){}
});
</script>
</body>
</html>
fetch.php
<?php
$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');
$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row) {
$output .= '
<div class="panel panel-default">
<div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
<div class="panel-body"><b> Comment: </b> <br> '.$row["comment"].' </div>
<div class="panel-footer" align="right">
<button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'" id[2]="'.$row["comment"].'">Edit</button>
</div>
</div>
';
}
echo $output;
?>
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
Heyho,
I have a problem with the following code. I took the example from here: http://phpflow.com/php/how-to-add-edit-and-delete-a-row-in-jquery-flexigrid-using-php-and-mysql/ and only removed the "age" option.
But after the removal, I am no longer able to add records to my database via the form. If I add the record manually (with phpMyAdmin) I am able to edit the records via the webpage.
Maybe someone could figure out where the mistake is...
This is my code:
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</title>
<link rel="stylesheet" href="dist/bootstrap.min.css" type="text/css" media="all">
<link href="dist/jquery.bootgrid.css" rel="stylesheet" />
<script src="dist/jquery-1.11.1.min.js"></script>
<script src="dist/bootstrap.min.js"></script>
<script src="dist/jquery.bootgrid.min.js"></script>
</head>
<body>
<div class="container">
<div class="">
<h1>Simple Bootgrid example with add,edit and delete using PHP,MySQL and AJAX</h1>
<div class="col-sm-8">
<div class="well clearfix">
<div class="pull-right"><button type="button" class="btn btn-xs btn-primary" id="command-add" data-row-id="0">
<span class="glyphicon glyphicon-plus"></span> Record</button></div></div>
<table id="employee_grid" class="table table-condensed table-hover table-striped" width="60%" cellspacing="0" data-toggle="bootgrid">
<thead>
<tr>
<th data-column-id="id" data-type="numeric" data-identifier="true">Empid</th>
<th data-column-id="employee_name">Name</th>
<th data-column-id="employee_salary">Salary</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<div id="add_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_add">
<input type="hidden" value="add" name="action" id="action">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="name" name="name"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="salary" name="salary"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_add" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<div id="edit_model" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit Employee</h4>
</div>
<div class="modal-body">
<form method="post" id="frm_edit">
<input type="hidden" value="edit" name="action" id="action">
<input type="hidden" value="0" name="edit_id" id="edit_id">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="edit_name" name="edit_name"/>
</div>
<div class="form-group">
<label for="salary" class="control-label">Salary:</label>
<input type="text" class="form-control" id="edit_salary" name="edit_salary"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn_edit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$( document ).ready(function() {
var grid = $("#employee_grid").bootgrid({
ajax: true,
rowSelect: true,
post: function ()
{
/* To accumulate custom parameter with the request object */
return {
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "response.php",
formatters: {
"commands": function(column, row)
{
return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-edit\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";
}
}
}).on("loaded.rs.jquery.bootgrid", function()
{
/* Executes after data is loaded and rendered */
grid.find(".command-edit").on("click", function(e)
{
//alert("You pressed edit on row: " + $(this).data("row-id"));
var ele =$(this).parent();
var g_id = $(this).parent().siblings(':first').html();
var g_name = $(this).parent().siblings(':nth-of-type(2)').html();
console.log(g_id);
console.log(g_name);
//console.log(grid.data());//
$('#edit_model').modal('show');
if($(this).data("row-id") >0) {
// collect the data
$('#edit_id').val(ele.siblings(':first').html()); // in case we're changing the key
$('#edit_name').val(ele.siblings(':nth-of-type(2)').html());
$('#edit_salary').val(ele.siblings(':nth-of-type(3)').html());
} else {
alert('Now row selected! First select row, then click edit button');
}
}).end().find(".command-delete").on("click", function(e)
{
var conf = confirm('Delete ' + $(this).data("row-id") + ' items?');
alert(conf);
if(conf){
$.post('response.php', { id: $(this).data("row-id"), action:'delete'}
, function(){
// when ajax returns (callback),
$("#employee_grid").bootgrid('reload');
});
//$(this).parent('tr').remove();
//$("#employee_grid").bootgrid('remove', $(this).data("row-id"))
}
});
});
function ajaxAction(action) {
data = $("#frm_"+action).serializeArray();
$.ajax({
type: "POST",
url: "response.php",
data: data,
dataType: "json",
success: function(response)
{
$('#'+action+'_model').modal('hide');
$("#employee_grid").bootgrid('reload');
}
});
}
$( "#command-add" ).click(function() {
$('#add_model').modal('show');
});
$( "#btn_add" ).click(function() {
ajaxAction('add');
});
$( "#btn_edit" ).click(function() {
ajaxAction('edit');
});
});
</script>
response.php
<?php
//include connection file
include_once("connection.php");
$db = new dbObj();
$connString = $db->getConnstring();
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$empCls = new Employee($connString);
switch($action) {
case 'add':
$empCls->insertEmployee($params);
break;
case 'edit':
$empCls->updateEmployee($params);
break;
case 'delete':
$empCls->deleteEmployee($params);
break;
default:
$empCls->getEmployees($params);
return;
}
class Employee {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
public function getEmployees($params) {
$this->data = $this->getRecords($params);
echo json_encode($this->data);
}
function insertEmployee($params) {
$data = array();;
$sql = "INSERT INTO `employee` (employee_name, employee_salary) VALUES('" . $params["name"] . "', '" . $params["salary"] . "' ); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert employee data");
}
function getRecords($params) {
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) { $page = $params['current']; } else { $page=1; };
$start_from = ($page-1) * $rp;
$sql = $sqlRec = $sqlTot = $where = '';
if( !empty($params['searchPhrase']) ) {
$where .=" WHERE ";
$where .=" ( employee_name LIKE '".$params['searchPhrase']."%' ";
$where .=" OR employee_salary LIKE '".$params['searchPhrase']."%' )";
}
if( !empty($params['sort']) ) {
$where .=" ORDER By ".key($params['sort']) .' '.current($params['sort'])." ";
}
// getting total number records without any search
$sql = "SELECT * FROM `employee` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp!=-1)
$sqlRec .= " LIMIT ". $start_from .",".$rp;
$qtot = mysqli_query($this->conn, $sqlTot) or die("error to fetch tot employees data");
$queryRecords = mysqli_query($this->conn, $sqlRec) or die("error to fetch employees data");
while( $row = mysqli_fetch_assoc($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"current" => intval($params['current']),
"rowCount" => 10,
"total" => intval($qtot->num_rows),
"rows" => $data // total data array
);
return $json_data;
}
function updateEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "Update `employee` set employee_name = '" . $params["edit_name"] . "', employee_salary='" . $params["edit_salary"]."' WHERE id='".$_POST["edit_id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to update employee data");
}
function deleteEmployee($params) {
$data = array();
//print_R($_POST);die;
$sql = "delete from `employee` WHERE id='".$params["id"]."'";
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
}
}
?>
There is also connection.php but the connection to my database works.
I guess that the response.php expects 3 parameters (name, salary and age) but only gets two...
Please don`t hesitate to ask for more details!
Thank you in advance,
Francis
Yes, you just had to delete the field from your database. It was likely marked as NOT NULL, and when you removed the field from the code, INSERT failed trying to insert a null employee_age :)
You should use your browsers developer tools to check the 'Network' tab for the XHR requests that get fired and have a look at the responses of those.
I think you can debug your way to a working solution from there.
You can use other tools like postman to test you AJAX "API" (response.php) but the developer tools of your browser should be more then sufficient for this ;)