Im really confused now please help
... This is the edit/update part which you will edit chosen user. The problem is i think $row or array is empty. The problem is that part. Im accepting any advice to my code to make it better.
Output
This is the output when i click edit button
update.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="uprec.php">
<?php
if(isset($_POST["borrower_id"])){
$output = '';
$connect = mysqli_connect("localhost", "root", "", "librarydb");
$query = "SELECT * FROM tbl_books WHERE id = '".$_POST["borrower_id"]."'";
$result = mysqli_query($connect, $query);
echo "Connected ";
while($row = mysqli_fetch_array($result)){
echo "fetch success";
}
echo "fetch failed";
}
else{
echo "Not Connected";
}
?>
<input type="submit" name="update" id="update" value="UPDATE" class="btn btn-success" />
</form>
</body>
</html>
database.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="script/livesearch.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<a class="navbar-brand" href="#">Home</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Books</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Transactions</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Accounts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="logout.php">Logout</a>
</li>
</ul>
</div>
</nav>
<?php
if(!empty($_SESSION)) {
?>
<div class="container p-3">
<h1 class="">Library Database</h1>
<hr><br>
<form>
<div class="input-group ">
<div class="input-group-prepend">
<span class="input-group-text">Search</span>
</div>
<input type="text" name="search_text" id="search_text" class="form-control" />
</div>
</form>
<br />
<button type="button" class="btn btn-primary mb-3" data-toggle="modal" data-target="#addbook_modal">Add Book</button>
<div id="result"></div>
</div>
<hr>
<?php
}else echo '<div class="alert alert-danger alert-dismissible fade show">
<strong>Login Required!</strong> You needed to be login first before you can access the database.
Go back to login
</div>';
?>
</body>
</html>
<script>
$(document).ready(function() {
$('#addbook_form').on("submit", function(event) {
event.preventDefault();
if ($('#booktitle').val() == "") {
alert("Book Title is required");
} else if ($('#category').val() == '') {
alert("Category is required");
} else if ($('#author').val() == '') {
alert("Author is required");
} else if ($('#publishername').val() == '') {
alert("Publisher Name is required");
} else if ($('#datepublished').val() == '') {
alert("Date Published is required");
} else if ($('#copies').val() == '') {
alert("Copies is required");
} else {
$.ajax({
url: "insert.php",
method: "POST",
data: $('#addbook_form').serialize(),
beforeSend: function() {
$('#addbtn').val("Inserting");
},
success: function(data) {
$('#addbook_form')[0].reset();
$('#addbook_modal').modal('hide');
$('#result').html(data);
}
});
}
});
});
$(document).on('click', '#editbtn', function() {
var borrower_id = $(this).attr("id");
$.ajax({
url: "update.php",
method: "POST",
data: {
borrower_id: borrower_id
},
success: function(data) {
$('#borrower_detail').html(data);
$('#editbook_modal').modal('show');
console.log(data);
}
});
});
</script>
<div id="addbook_modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Book</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form method="POST" id="addbook_form">
<div class="form-group">
<label>Book Title:</label>
<input type="text" name="booktitle" id="booktitle" class="form-control" placeholder="Title of the Book">
</div>
<div class="form-group">
<label>Category:</label>
<select name="category" id="category" class="custom-select">
<option>Art</option>
<option>English</option>
<option>Math</option>
<option>Science</option>
<option>Filipino</option>
</select>
</div>
<div class="form-group">
<label>Author:</label>
<input type="text" name="author" id="author" class="form-control" placeholder="Author of the Book">
</div>
<div class="form-group">
<label>Publisher Name:</label>
<input type="text" name="publishername" id="publishername" class="form-control" placeholder="Name of the Publisher">
</div>
<div class="form-group">
<label>Date Published</label>
<input type="date" name="datepublished" id="datepublished" class="form-control" placeholder="Date of Publication">
</div>
<div class="form-group">
<label>Copies</label>
<input type="number" name="copies" id="copies" class="form-control" placeholder="Number of Copies">
</div>
<div class="form-group">
<button id="addbtn" class="btn btn-success">Add</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="editbook_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Book Details</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="borrower_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
fetch.php
<?php
session_start();
include ('connection.php');
if(!empty($_SESSION)) {
$output = '';
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM tbl_books
WHERE booktitle LIKE '%".$search."%'
OR category LIKE '%".$search."%'
OR author LIKE '%".$search."%'
OR copies LIKE '%".$search."%'
OR publishername LIKE '%".$search."%'
OR datepublished LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM tbl_books ORDER BY id DESC
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="table-responsive" id="employee_table">
<table class="table table-bordered">
<thead>
<tr>
<th>Book Title</th>
<th>Category</th>
<th>Author</th>
<th>Publisher Name</th>
<th>Date Published</th>
<th>Copies</th>
<th>Action</th>
</tr>
</thead>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["booktitle"].'</td>
<td>'.$row["category"].'</td>
<td>'.$row["author"].'</td>
<td>'.$row["publishername"].'</td>
<td>'.$row["datepublished"].'</td>
<td>'.$row["copies"].'</td>
<td><button type="submit" class="btn btn-success btn-sm" id="editbtn">Edit</button>
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
}else echo '<div class="alert alert-danger alert-dismissible fade show">
<strong>Login Required!</strong> You needed to be login first before you can access the database.
Go back to login
</div>';
?>
Currently
$_POST["borrower_id"]
is always "editbtn" all the time. So query always returns zero entries.
Your problem is this
<button type="submit" class="btn btn-success btn-sm" id="editbtn">Edit</button>
and this should probably something like this
<button type="submit" class="btn btn-success btn-sm" id="editbtn" bookid='.$row['id'].'>Edit</button>
$row['id'] depends on whatever your id field is named.
Also you have to change
var borrower_id = $(this).attr("id");
to
var borrower_id = $(this).attr("bookid");
This should work.
Related
The "if(isset($_POST["titleId"]) && !empty($_POST["titleId"])" in my code is returning false value.
I'm working on a CRUD application, the insert modal is working fine, now I'm stuck at the update part of it. So when you click on the update icon it does fetch the right titleId in the URL but the first 'if' condition returns false and hence the update isn't working.
Here's what I've tried so far.
admin.php
<?php
$typeId = filter_input(INPUT_GET, "type");
$titleId = filter_input(INPUT_GET, "titleId");
$active = "admin" . $typeId;
require_once './pages/header.php';
require_once './functions/queries.php';
$getAll = Queries::getAllTitle($typeId);
?>
<div class="container">
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header clearfix">
<h2 class="pull-left"></h2>
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
</div>
<!--<div class="container">
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
<br><br>-->
<div class="panel-group" id="titleAccordion">
<?php
for ($i = 0; $i < count($getAll); $i++) {
echo <<<HTML
<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title">
<a data-toggle="collapse" data-parent="#titleAccordion" href="#collapseF{$i}">{$getAll[$i]['title']}</a></h4>
</div>
<div id="collapseF{$i}" class="panel-collapse collapse" >
<div class="panel-body">
<div class="table-responsive">
<table class="table table-condensed"><tbody>
<tr><td>Title:</td><td>{$getAll[$i]['title']}</td></tr>
<tr><td>Units:</td><td>{$getAll[$i]['units']}</td></tr>
<tr><td>Category:</td><td>{$getAll[$i]['category']}</td></tr>
<tr><td>
<tr><td><input type="hidden" id="titleId" name="titleId" value="{$getAll[$i]['titleId']}"> </tr><td>
<a href='edit.php?titleId={$getAll[$i]['titleId']}' title='Update Record' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>
<a href='delete.php?titleId={$getAll[$i]['titleId']}' title='Delete Record' data-toggle='tooltip'><span class='glyphicon glyphicon-trash'></span></a>
</tr></td>
</tbody></table>
</div>
</div>
</div>
</div>
HTML;
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Title Add Modal-->
<div class="modal fade" id="facultyAddModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Title</h4>
</div>
<div class="modal-body">
<div id="adminResult" class="hide" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div id="resultAdminContent"></div>
</div>
<form class="cmxform" id="adminForm" method="post">
<label for="Activity">ActivityAttended (required)</label>
<input class="form-control" id="adminTitle" name="title" type="text" required>
<br>
<label for="units">Units (required)</label>
<input class="form-control" id="adminUnits" type="number" name="units" required>
<br>
<label for="Category">Category (Optional)</label>
<input class="form-control" id="adminCategory" type="text" name="category">
<br>
<?php echo
'<input type="hidden" id="addadminTypeId" value="'.$typeId.'">';
?>
<?php echo
'<input type="hidden" id="titleId" name="titleId" value="'.$titleId.'">';
?>
<button class="btn btn-info btn-primary" type="submit">Submit</button>
<br>
<br>
</form>
</div>
</div>
</div>
</div>
update.php
<?php
require_once 'functions/db_connection.php';
$conn = DB::databaseConnection();
$title = $units = $category = "";
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
$titleId = $_POST['titleId'];
$sql = "UPDATE title SET title = :title, units = :units, category = :category WHERE titleId = :titleId";
if($stmt = $conn->prepare($sql))
{
// Bind variables to the prepared statement as parameters
$stmt->bindParam(':titleId', $titleId);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':units', $units);
$stmt->bindParam(':category', $category);
if ($stmt->execute()) {
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
unset($stmt);
}
unset($conn);
} else{
if(isset($_GET["titleId"]) && !empty(trim($_GET["titleId"]))){
$titleId = trim($_GET["titleId"]);
$sql = "SELECT * FROM title WHERE titleId = :titleId";
if($stmt = $conn->prepare($sql))
{
$stmt->bindParam(':titleId', $titleId);
if ($stmt->execute()){
if($stmt->rowCount() == 1){
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Retrieve individual field value
$title = $result["title"];
$units = $result["units"];
$category = $result["category"];
} else{
echo"error1";
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
unset($stmt);
unset($conn);
} else{
// URL doesn't contain id parameter. Redirect to error page
echo"error2";
exit();
}
}
?>
<!--<!DOCTYPE html>-->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Update Record</h2>
</div>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<label for="Activity">Title</label>
<input class="form-control" id="adminTitle" name="title" type="text" value="<?php echo $title; ?>" required>
<br>
<label for="units">Units (required)</label>
<input class="form-control" id="adminUnits" type="number" name="units" value="<?php echo $units; ?>" required>
<br>
<label for="Category">Category (Optional)</label>
<input class="form-control" id="adminCategory" type="text" value="<?php echo $category; ?>" name="category">
<br>
<input type="hidden" name="titleId" value="<?php echo $titleId; ?>">
<button class="btn btn-info btn-primary" type="submit">Submit</button>
<br>
<br>
</form>
</div>
</<div>
</div>
</div>
</div>
</body>
</html>
The only goal here is to get the update form working, the user should be able to update the records of the respective title being selected.
I don't know crud but I think there is a way to debug a little:
e.g. try this:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
// test if you are here:
echo 'hi, yeah I am here!';
}
or this
echo '<pre>';
var_dump($_POST);
echo '</pre>';
// before:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
// ...
}
also, take a look at
error_get_last()['message']
I need a help here when I click on the edit button on the image below i expect to see data populated on a form in a bootstrap modal window I am using jquery ajax method to populate the data in the form of
and the edit modal image
Here is code for the home page
<?php require_once("connect.php"); ?>
<?php require_once("fetch.php"); ?>
<?php require_once("select.php"); ?>
<?php require_once("process.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Home</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<ul class="nav nav-pills">
<li>Home</li>
</ul>
<button type="button" class="btn btn-primary pull-right" data-toggle="modal" data-target="#myModal">Add</button>
<table class="table" id="table">
<tr>
<th>S/N</th>
<th>Name</th>
<th>Email</th>
<th>Description</th>
<th>Edit</th>
<th>View</th>
<th>Delete</th>
</tr>
<?php
$query = "SELECT * FROM contact";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run select query ".mysqli_error($connect));
}
$sn = 1;
while($row = mysqli_fetch_assoc($runQuery)){ ?>
<tr>
<td><?php echo $sn++ ?></td>
<td><?php echo $row["name"] ?></td>
<td><?php echo $row["email"] ?></td>
<td><?php echo $row["description"] ?></td>
<td>
<button type="button" data-toggle="modal" data-target="#myModal" class="btn btn-warning btn-sm edit-data" id="<?php echo $row['userid'] ?>">Edit</button>
</td>
<td>
<button type="button" data-target="#viewModal" data-toggle="modal" class="btn btn-primary btn-sm view-data" id="<?php echo $row['userid'] ?>">View</button>
</td>
<td>
<button type="button" class="btn btn-danger btn-sm del-data" id="<?php echo $row['userid'] ?>">Danger</button>
</td>
</tr>
<?php } ?>
</table>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Data</h4>
</div>
<div class="modal-body">
<div id="success" class="alert alert-success"></div>
<form class="form" method="POST" id="insertData">
<div id="nameError" class="alert alert-danger"></div>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div id="emailError" class="alert alert-danger"></div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" id="email">
</div>
<input type="hidden" name="userid" id="contactUserId">
<div id="descriptionError" class="alert alert-danger"></div>
<div class="form-group">
<label>Description</label>
<textarea name="description" id="description" class="form-control"></textarea>
</div>
<input type="submit" class="btn btn-primary" value="Add" name="add" id="add">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="viewModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">View Data</h4>
</div>
<div class="modal-body" id="contactDetail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/myscript.js"></script>
</body>
</html>
This code is for entering and updating data in the database process.php
<?php
if(!empty($_POST)){
$name = $_POST["name"];
$email = $_POST["email"];
$description = $_POST["description"];
$userid = $_POST["userid"];
if($userid != ''){
$query = "UPDATE contact SET name = '$name', email='$email', description='$description' WHERE userid = $userid ";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run query ".mysqli_error($connect));
}
}else{
$query = "INSERT INTO contact(name, email, description) VALUES ";
$query .=" ('$name', '$email', '$description')";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run insert query ".mysqli_error($connect));
}
}
}
This code retrieves data from database
<?php
if(isset($_POST['userid'])){
$editId = (int)$_POST['userid'];
$query = "SELECT * FROM contact WHERE userid = $editId";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run query ".mysqli_error($connect));
}
$getData = mysqli_fetch_assoc($runQuery);
echo json_encode($getData);
}
This is my js file
$(document).ready(function(){
$("#insertData").submit(function(event){
event.preventDefault();
if($("#name").val() == ""){
$("#nameError").css("display", "block").html("Name is required");
}else if ($("#email").val() == "") {
$("#emailError").css("display", "block").html("Email is required");
}else if ($("#description").val() == "") {
$("#descriptionError").css("display", "block").html("Description is required");
}else{
$.ajax({
url: "index.php",
method: "POST",
data: $("#insertData").serialize(),
success: function(data){
$("#success").css("display", "block").html("Data added");
$("#insertData")[0].reset();
}
});
}
});
$(document).on("click", ".edit-data", function(){
var contactId = $(this).attr("id");
$.ajax({
url:"index.php",
method: "POST",
data: {contactId:contactId},
dataType: "json",
success: function(data){
$("#name").val(data.name);
$("#email").val(data.email);
$("#description").val(data.description);
$("#contactUserId").val(data.userid);
$("#add").val("Update");
$("#myModal").modal("show");
}
});
});
$(document).on('click', '.view-data', function(){
var contactId = $(this).attr("id");
if(contactId != '')
{
$.ajax({
url:"index.php",
method:"POST",
data:{contactId:contactId},
success:function(data){
$('#contactDetail').html(data);
$('#viewModal').modal('show');
}
});
}
});
});
You are sending contactId and in your PHP you are looking for userid. Change your data to data: { userid: userid }.
$(document).on("click", ".edit-data", function() {
var userid = $(this).attr("id");
$.ajax({
url: "index.php",
method: "POST",
data: { userid: userid },
dataType: "json",
success: function(data) {
$("#name").val(data.name);
$("#email").val(data.email);
$("#description").val(data.description);
$("#contactUserId").val(data.userid);
$("#add").val("Update");
$("#myModal").modal("show");
}
});
});
I want to update my database using php ajax modal. When updating the relevant field { $('#main_id').val(data.id); } don't pass an id to the update query therefor an insertion occurs without executing the updating query.
console log details when trying to update
I tried to solve this but I couldn't. without updating the existing data it inserts a new record
here is my index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ohmsp");
$query = "SELECT * FROM tbl_main_category ORDER BY cat_Id DESC";
$result = mysqli_query($connect, $query);
?>
<div id="employee_table">
<table class="table table-bordered">
<tr> <th width="70%">Employee id</th>
<th width="70%">Employee Name</th>
<th width="15%">Edit</th>
<th width="15%">View</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr> <td><?php echo $row["cat_Id"]; ?></td>
<td><?php echo $row["category_name"]; ?></td>
<td><input type="button" name="edit" value="Edit" id="<?php echo $row["cat_Id"]; ?>" class="btn btn-info btn-xs edit_data" /></td>
<td><input type="button" name="view" value="view" id="<?php echo $row["cat_Id"]; ?>" class="btn btn-info btn-xs view_data" /></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
</body>
</html>
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Employee Details</h4>
</div>
<div class="modal-body" id="employee_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="add_data_Modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">PHP Ajax Update MySQL Data Through Bootstrap Modal</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<label>Enter Employee Name</label>
<input type="text" name="category_name" id="category_name" class="form-control" />
<br />
<input type="hidden" name="main_id" id="main_id" />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#add').click(function(){
$('#insert').val("Insert");
$('#insert_form')[0].reset();
});
$(document).on('click', '.edit_data', function(){
console.log('test')
var main_id = $(this).attr("id");
console.log(main_id)
$.ajax({
url:"fetch.php",
method:"POST",
data:{main_id:main_id},
dataType:"json",
success:function(data){
console.log(data)
$('#category_name').val(data.category_name);
console.log(data.category_name)
$('#main_id').val(data.id);
console.log(data.id)
$('#insert').val("Update");
$('#add_data_Modal').modal('show');
}
});
});
insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ohmsp");
if(!empty($_POST))
{
$output = '';
$message = '';
$category_name = mysqli_real_escape_string($connect, $_POST["category_name"]);
if($_POST["main_id"] != '')
{
$query = "
UPDATE tbl_main_category
SET category_name='$category_name' WHERE cat_Id='".$_POST["main_id"]."'";
$message = 'Data Updated';
}
else
{
$query = "
INSERT INTO tbl_main_category(category_name)
VALUES('$category_name');
";
$message = 'Data Inserted';
}
fetch.php
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "ohmsp");
if(isset($_POST["main_id"]))
{
$query = "SELECT * FROM tbl_main_category WHERE cat_Id = '".$_POST["main_id"]."'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo json_encode($row);
}
?>
You have Fetched the value from $('#main_id').val(data.id) instead of $('#main_id').val(data.cat_Id);
You have fetched value of id instead of cat_Id
I am a novice to PHP. Now I am building a simple login-logout system. While trying to log in the system, I got the Internal Server Error with jquery.min.js:4. Here is my code:
Index:
<!-- Login Form -->
<form method="post" id="loginForm">
<div class="modal fade" id="login" tabindex="-1" role="dialog" aria-labelledby="#loginHeading" aria-hidden="true">
<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" id="loginHeading">Login Form</h4>
</div>
<div class="modal-body">
<div id="loginMessage"></div>
<div class="form-group">
<label for="email">Email: </label>
<input type="email" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="pass">Password: </label>
<input type="password" id="pass" name="pass" class="form-control" required>
</div>
<div class="row">
<div class="checkbox" >
<div class="pull-left" style="padding-left:20px">
Forget password?
</div>
<label class="pull-right" style="padding-right:20px"><input type="checkbox" name="remember" value=""> Remember me</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success pull-left" data-dismiss="modal" data-toggle="modal" data-target="#signUp">Register</button>
<button type="submit" class="btn myBtn">Login</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Script:
$("#loginForm").submit(function(event) {
event.preventDefault();
var dataPost= $(this).serializeArray();
$.ajax({
url: '4-logIn.php',
type: 'POST',
data: dataPost,
success:function(data){
if (data == "success") {
window.location("mainPageLogin.php");
}
else {
$("#loginMessage").html(data);
}
},
error: function(data){
$('#loginMessage').html('<div class="alert alert-danger"><h5>Error in connection with loginForm</h5></div>');
}
});
});
4-login.php:
``
<?php
session_start();
include '0-connection.php';
$error='';
$email=filter_var($_POST["email"],FILTER_SANITIZE_EMAIL);
$pass=filter_var($_POST["pass"],FILTER_SANITIZE_STRING);
// Query
$email=mysqli_real_escape_string($link,$email);
$pass=mysqli_real_escape_string($link,$pass);
$pass=hash('sha256',$pass);
$sql="SELECT * FROM users WHERE email='$email' AND password='$pass' AND activation='activated'";
$result=mysqli_query($link, $sql);
if (!$result) {
echo "<div class='alert alert-danger'>Error running the query to take user login</div>";
exit;
}
$count= mysqli_num_rows($result);
if ($count !== 1) {
$error="<div class='alert alert-danger'><strong>ERROR:</strong> Wrong username or password. Please try again or Do you want to <a href='#' data-dismiss='modal' data-target='#signUp' data-toggle='modal'>Sign up</a></div>";
echo $error;
}
else {
// Set session
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id']=$row['user_id'];
$_SESSION['username']=$row['username'];
$_SESSION['email']=$row['email'];
// Check remember me Box
if (empty($_POST['remember'])) {
echo "success";
}
else {
}
}
?>
This is my error:
demonstration
web response
Please be more specific in your answer because I am very new in programming. Thanks for reading.
Error in 4-logIn.php, if (!result) { must be changed as if (!$result) {
I have this index.php code:
<form role="form" id="submit_form" class="form-horizontal">
<div class="panel-body">
<div class="form-group has-feedback">
<div class="col-sm-2">
<label class="control-label">País</label>
</div>
<div class="col-sm-9">
<?
$array_pais = array('Selecione...', 'Alemanha', 'Angola', 'Argentina', 'Bolívia', 'Brasil', 'Camarões', 'Canadá', 'Chile', 'China', 'Colombia',
'Costa Rica', 'Cuba', 'Dinamarca', 'Equador', 'Espanha', 'Estados Unidos', 'França', 'Holanda', 'Inglaterra', 'Itália', 'Japão',
'México', 'Nigéria', 'Panamá', 'Paraguai', 'Peru', 'Porto Rico', 'Portugal', 'Rússia', 'Senegal', 'Taiwan', 'Uruguai', 'Venezuela'
);
echo '<select class="form-control" name="pais" id="pais">';
foreach ($array_pais as $valor) {
echo '<option>' . $valor . '</option>';
}
echo '</select>';
?>
</div>
</div>
<div class="form-group has-feedback">
<div class="col-sm-2">
<label class="control-label">Nome:</label>
</div>
<div class="col-sm-10">
<input id="nome" name="nome" class="form-control" type="text" placeholder="Digite o nome">
</div>
</div>
<div class="form-group has-feedback">
<div class="col-sm-2">
<label class="control-label">Empresa</label>
</div>
<div class="col-sm-10">
<input id="empresa" name="empresa" class="form-control" type="text" placeholder="Digite a empresa">
</div>
</div>
<div class="form-group">
<div class="col-sm-12 col-sm-offset">
<div style="float:left; padding-right:30px">
<button type="submit" class="btn btn-lg btn-primary" aria-label="Left Align">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Adicionar
</button>
</div>
<div style="float:right;">
<button class="btn btn-lg btn-warning" onClick="parent.location='exibir.php'">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="jumbotron">
<table data-toggle="table" data-cache="false" class="table" id="list">
<thead align="center">
<tr bgcolor="#FFFFFF">
<th>PAÍS</th>
<th>NOME</th>
<th>EMPRESA</th>
<th>AÇÕES</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="inserir_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<span class="glyphicon glyphicon-file"></span> Inserir
</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="editar_modal" role="dialog">
<div class="modal-dialog">
<form id="edit_form" class="form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<span class="glyphicon glyphicon-pencil"></span> Editar
</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label class="control-label">País:</label>
<input id="pais_input" name="nome" class="form-control" type="text" placeholder="Digite o pais">
</div>
<div class="form-group">
<label class="control-label">Nome:</label>
<input id="nome_input" name="nome" class="form-control" type="text" placeholder="Digite a empresa">
</div>
<div class="form-group">
<label class="control-label">Empresa:</label>
<input id="empresa_input" name="empresa" class="form-control" type="text" placeholder="Digite a empresa">
</div>
<input id="id_input" type="hidden" name="id">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" aria-label="Left Align">
<span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Gravar
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div>
</form>
</div>
</div>
<div class="modal fade" id="deletar_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<span class="glyphicon glyphicon-trash"></span> Exclusão
</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
<script>
function update_list() {
$.getJSON("get_list.php", function (data) {
if (data.response) {
$("#list").find("tbody").empty();
data.results.forEach(function (i) {
$("#list").find("tbody").append(
"<tr>" +
"<td>" + i.pais + "</td>" +
"<td>" + i.nome + "</td>" +
"<td>" + i.empresa + "</td>" +
"<td align='center'><a class='btn btn-primary glyphicon glyphicon-pencil' title='Editar' id='edit_link' href='" + JSON.stringify(i) + "'></a> | <a class='btn btn-danger glyphicon glyphicon-trash' title='Deletar' id='delete_link' href='" + JSON.stringify(i) + "'></a></td>" +
"</tr>"
);
});
}
});
}
$("#list").delegate('#edit_link', 'click', function (e) {
e.preventDefault();
var info = JSON.parse($(this).attr("href"));
var $modal = $("#editar_modal");
$modal.find("#pais_input").val(info.pais);
$modal.find("#nome_input").val(info.nome);
$modal.find("#empresa_input").val(info.empresa);
$modal.find("#id_input").val(info.id);
$modal.modal('show');
});
update_list();
$('#submit_form').submit(function () {
$.ajax({
url: "inserir.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#inserir_modal');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
$('#edit_form').submit(function () {
$.ajax({
url: "editar.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#inserir_modal');
$("#editar_modal").modal('hide');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
</script>
edit.php
<?php
require('conexao.php');
$id = $_POST['id'];
$pais = $_POST['pais'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$query = "UPDATE tb_visitas SET nome = '$nome', empresa = '$empresa', pais= '$pais' WHERE id = $id ";
$update = mysql_query($query);
if ($update) {
$res['response'] = true;
$res['message'] = "Registro atualizado com sucesso!";
} else {
$res['response'] = false;
$res['message'] = "Erro: " . $query . "<br>" . mysql_error();
}
echo json_encode($res);
?>
get_list.php
<?php
require('conexao.php');
$sql = "SELECT id, pais, nome, empresa FROM tb_visitas";
$table = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($table) > 0) {
$res['response'] = true;
while($row = mysql_fetch_assoc($table)) {
$res['results'][] = $row;
}
} else {
$res['response'] = false;
$res['message'] = "Erro: " . $sql . "<br>" . mysql_error($con);
}
echo json_encode($res);
?>
deletar.php
<?php
require('conexao.php');
$id = $_POST['id'];
$query = "DELETE FROM tb_visitas WHERE id = $id ";
if (mysql_query($query)) {
$res['response'] = true;
$res['message'] = "Registro deletado com sucesso!";
} else {
$res['response'] = false;
$res['message'] = "Erro: " . $query . "<br>" . mysql_error($con);
}
echo json_encode($res);
?>
and conexao.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$hostname = 'localhost';
$username = 'root';
$senha = '';
$banco = 'visitas';
$db = mysql_connect($hostname, $username, $senha);
mysql_set_charset('latin1',$db);
mysql_select_db($banco, $db) or die ("Não foi possível conectar ao banco MySQL");
?>
So, now I'd like to put a checkbox in each item for being able to select several records and delete them at once. Another question, when I edit a record if I put a text the field it's filled, but if I put a select it doesn't work. The idea is the select field has all options of countries and letting that item from the record already selected. I hope you understand what I need. Thanks.
From what I understand, you have two questions:
How to put checkboxes on your CRUD list in order to delete all items at once.
It seems that you are using update_list() to load all items on your table. Since thats the case, you need to add an extra <td> in that row to that iteration with the checkbox element.
data.results.forEach(function (i) {
$("#list").find("tbody").append(
"<tr>" +
"<td><input class='item_checkbox' type='checkbox'/></td>" +
"<td>" + i.pais + "</td>" +
"<td>" + i.nome + "</td>" +
"<td>" + i.empresa + "</td>" +
"<td align='center'><a class='btn btn-primary glyphicon glyphicon-pencil' title='Editar' id='edit_link' href='" + JSON.stringify(i) + "'></a> | <a class='btn btn-danger glyphicon glyphicon-trash' title='Deletar' id='delete_link' href='" + JSON.stringify(i) + "'></a></td>" +
"</tr>"
);
});
Once you have that set, you can then use jquery to collect all checkboxes by class .item_checkbox and run a delete function.
How to make sure the SELECT country field is pre-selected when you EDIT an item
Since you are using bootstrap modals, when you edit an item, that modal will popup showing that info. What you need to do is send that item's country ID to that modal's form so that it can be preselected, so do the following change:
first in #editar_modal
<div class="form-group">
<label class="control-label">País:</label>
<select id="pais_input" name="pais">
<?php foreach ($array_pais as $pais) { ?>
<option value="<?php echo $pais ?>"><?php echo $pais ?></option>
<?php } ?>
</div>
then in '#edit_link', 'click', function (e) add:
$modal.find("#pais_input").val(info.pais);