get value of checkbox submit to a variable - php

I'm trying to work out how to get the value of a checkbox submit it to a variable which is an id from a sql db.
Below is my current code:
-- Index.php
<?php
$sql = "SELECT * FROM `file`";
if (!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
?>
<form method="post">
<button class="btn btn-success">New</button>
<button type="submit" class="btn btn-warning">Edit</button>
<button class="btn btn-danger">Delete</button>
<table class="table table-condensed">
<thead>
<th>#</th>
<th>Name</th>
<th>Category</th>
<th>Date</th>
</thead>
<tbody>
<?php while($row = $result->fetch_assoc()){ ?>
<td><input type="checkbox" name="id_grab" value="<?php echo $row['file_id']; ?>"></td>
<td><?php echo $row['file_name']; ?></td>
<td><?php echo $row['file_category']; ?></td>
<td><?php echo date('d-m-y', strtotime($row['file_date'])); ?></td>
</tbody>
<?php } ?>
</table>
</form>
-- file_edit.php
<?php include('../db_connect.php') ;
$id=isset($_POST['id_grab']);
$sql = "SELECT * FROM `file` WHERE file_id = $id";
if (!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
$row = $result->fetch_assoc();
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Edit Invoice / Receipt</h4>
</div>
<div class="modal-body">
<form action="../includes/file_update.php" method="post" role="form" enctype="multipart/form-data">
<div class="form-group">
<label for="File_Name">Name</label>
<input type="text" name="file_name" class="form-control" id="file_name" value="<?php echo $row['file_name']; ?>">
</div>
<div class="form-group">
<lable for="File_Category">Category</label>
<input type="text" name="file_category" class="form-control" id="file_category" placeholder="Financial">
</div>
<div class="form-group">
<label for="file_tag">Tag</label>
<input type="text" name="file_tag" class="form-control" id="file_tag" placeholder="statement">
</div>
<div class="form-group">
<label for="file_description">Description</label>
<input type="text" name="file_description" class="form-control" id="file_description">
</div>
<div class="form-group">
<label for="file_date">Date</label>
<input type="date" name="file_date" class="form-control" id="file_date">
</div>
<div class="form-group">
<label for="file_location">File</label>
<input type="file" class="form-control" name="file_location" value="file">
<p class="help-block">Select appropriate file for upload.</p>
</div>
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success">Upload</button>
</form>
</div>
I can't work it out, spent hours looking online... My concern is at it's using Bootstraps Modal I wasn't sure if it would be able to grat the POST data... As if I enter the ID manually it works...
Any assistance would be greatly appreciated.

change this
$id=isset($_POST['id_grab']);
to
$id=isset($_POST['id_grab'])?$_POST['id_grab']:'';
//if id_grab dont have a value then $id value will be ''
isset() Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

Related

PHP move A variable to another document

Hello so I am having a slight problem at the moment Basically I have a while loop that outputs a table called job from database along with a bid button that links to bid.php. When the button takes me to the page I want it to carry over the jobid of the row that the button was clicked so I can enter the specific value into my database does anyone have any ideas on how to move over currently I am trying to do it using POST but I keep getting errors and the variable dosnt seem to be moving over.I just get a blank page and the id is not displayed.
Here is findjob22.php:
<?php
require 'config.php';
if(isset($_POST['submit']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `job` WHERE CONCAT(`job_id`,`location`, `description`, `budget`, `duedate`,`title`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `job`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "bid4myjob");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html lang="en">
<!-- PAGE CONTENT -->
<div class="page-content page-search-result">
<div class="container">
<!-- Search Form -->
<form class="form form-horizontal" action="bid.php" method="post">
<div class="input-group input-group-lg">
<div class="input-group-btn">
<!--<select id="search-type-select" name="valueToSearch" class="multiselect multiselect-single-lg search-type-select">
<option value="all" selected="selected">All</option>
<option value="page">Page</option>
<option value="task">Task</option>
<option value="user">User</option>
<option value="image">Image</option>
</select>
</div>-->
<input class="form-control input-lg" type="text" name="valueToSearch" placeholder="type keyword ..." />
<span class="input-group-btn">
<button type="submit" name= "submit" value="Search" class="btn btn-primary btn-lg"><i class="icon ion-android-search"></i> Go</button>
</span>
</div>
</form>
<!-- End Search Form -->
</div>
</div>
<div>
<table>
<tr>
<th>id</th>
<th>Title</th>
<th>Location</th>
<th>Description</th>
<th>Budget</th>
<th>Due date</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<?php //$jid= $row['job_id']; ?>
<td><?php echo $row['job_id']; ?></td>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['description'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['duedate'];?></td>
<td><form method="post" action="bid.php" class="form-horizontal">
<?php //echo _("Enter ") . ' ' . $last_bid_plus . ' ' . _('or more'); ?>
<!--<div class="input-group ">
<input type="number" value="bid" class="form-control" name="bid" id= "bid" required/>
</div>
<br/>-->
<input type="submit" name="job_id" value="<?php $row['job_id']; ?>"
class="btn btn-xlarge btn-block btn-primary">bid</input>
<br/>
</form></td>
</tr>
<?php endwhile;?>
</table>
</div>
<!-- END PAGE CONTENT -->
</body>
</html>
Here is bid.php where I am trying to get the specific id of the row from findjob22.php:
<?php
// include "job.php"
$jobid = $_POST['job_id'];
echo "$jobid"
?>
<!--<html>
<div class="col-xs-8">
<div class="page-header white-content">
<h1><?= _('Your Bid') ?>.</h1>
</div>
<div class="white-content">
<div class="well">
<br/><br/>
<form method="post" action="/listings/bid/<?//=$listingID; ?>/confirm" class="form-horizontal">
<input type="hidden" value="<?=//$bid_amount?>" class="input-medium" name="bid_amount"/>
<input type="submit" name="sb_bid" value="<?php// echo _('I agree and I confirm my BID'); ?>" class="btn btn-medium btn-green" />
</form>
</div>
</div>
</div>
</html>-->
I am not sure you can pass values in the submit button, but you can use a hidden input to pass the value.
<input type="hidden" value="<?php echo $row['job_id']; ?>" name="job_id" />
<input type="submit" class="btn btn-xlarge btn-block btn-primary">bid</input>
If you want it to work like you have it use a button.
<button type="submit"
name="job_id"
value="<?php echo $row['job_id']; ?>"
class="btn btn-xlarge btn-block btn-primary">
bid
</button>
if you want to also pass some data:
<form method="post"
action="bid.php"
class="form-horizontal">
<div class="input-group">
<input type="text"
class="form-control"
name="bid"
id="bid" required />
</div>
<button type="submit"
name="job_id"
value="<?php echo $row['job_id']; ?>"
class="btn btn-xlarge btn-block btn-primary">
bid
</button>
<br/>
</form>
Then you will have a $_POST["job_id"] and $_POST["bid"] in bid.php

EDIT DATA in TABLE using php

**I want to edit data in my table using modal but i can only call ID=1 i cant edit the others and also i need to refresh my web before i can see the changes?
// my update code
<?php
$id= "1";
$mysqli = new mysqli('127.0.0.1','root','','books');
$query = $mysqli->query("select * from bookrecords where ID='$id' ");
$row = $query->fetch_assoc();
if(isset($_POST['update'])) {
$id = $_POST['id'];
$nm = $_POST['nm'];
$is = $_POST['is'];
$pb = $_POST['pb'];
$au = $_POST['au'];
$result = $mysqli->query("UPDATE bookrecords set BookName='$nm', ISBN='$is', Publisher='$pb', Author='$au' where ID='$id'");
if($result){
?>
<div class="alert-success" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="close"><span aria-hidden="true">&times</span></button>
<strong>Success!</strong> your data has been updated.
</div>
<?php
} else{
?>
<div class="alert-failed" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="close"><span aria-hidden="true">&times</span></button>
<strong>Failed!</strong> Error updating. Try Again!
</div>
<?php
}
}
?>
** and this is my Modal form....
<div class="form-group">
<label for="id">ID:</label>
<input type="text" class="form-control" id="id" name="id" value="<?php echo $row['ID']?>" readonly>
</div>
<div class="form-group">
<label for="nm">BookName:</label>
<input type="text" class="form-control" id="nm" name="nm" value="<?php echo $row['BookName']?>">
</div>
<div class="form-group">
<label for="is">ISBN:</label>
<input type="text" class="form-control" id="is" name="is" value="<?php echo $row['ISBN']?>">
</div>
<div class="form-group">
<label for="pb">Publisher:</label>
<input type="text" class="form-control" id="pb" name="pb" value="<?php echo $row['Publisher']?>">
</div>
<div class="form-group">
<label for="au">Author:</label>
<input type="text" class="form-control" id="au" name="au" value="<?php echo $row['Author']?>">
</div>
<button type="submit" name="update" class="btn-primary">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
<div class="modal-footer">
</div>
</div>
**so how can i call any of my item/data in table? Please help me.
Your HTML form must have a hidden field with the id of book record, which will be send to the PHP script when pressing the "Update" button. The hidden field should look like this:
<input type="hidden" name="bookrecordId" value="ID_OF_BOOKRECORD_HERE" />
You can access the value of the transfered id with $_POST['bookrecordId'] in your receiving PHP script. Use it to build one or two prepared statements which will check if the row exists and then run an UPDATE query to update the values.

How to get/pass the value to modal

How can I pass the value of order_id from order.php to ordermodal.php, So I can use it in my query.
This is the order.php
UI of order.php
<?php
session_start();
$order_id = $_SESSION['order_id'];
if (!isset($_SESSION['user_id']))
{
header("Location: index.php");
}
$_SESSION['navMenu'] = "order";
ini_set('display_errors', 'On');
require_once 'includes/database.php';
include_once 'system_menu.php';
include_once 'ordermodal.php';
$sql2 = "SELECT * FROM cart_tbl";
$sql = "SELECT * FROM order_tbl WHERE order_status = 'Accepted' or order_status = 'Dispatched' or order_status = 'Pending' ORDER BY order_datetime DESC";
/*** * SET UP COMBO BOX FOR SEARCH */
$comboBox = isset($_REQUEST['comboBoxVal']) ? trim($_REQUEST['comboBoxVal']) : '';
$search_by = isset($_REQUEST['search_by']) ? addslashes($_REQUEST['search_by']) : 0;
$users = null;
if ($comboBox != '') { switch ($search_by) {
case 1://Order ID
$sql .= " WHERE order_id LIKE '%{$comboBox}%' ";
break;
}
}
$carts = mysqli_query(connection(), $sql2);
$orders = mysqli_query(connection(), $sql);
$search_filters = array(1 => 'Order ID');
/*** * END SET UP COMBO BOX */ ?>
<html>
<head>
<title>ORDERS</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<style type="text/css">
body {
background:url(images/jerica.jpg)fixed no-repeat center;
background-size:cover;
}
.asd {
color: white;
}
</style>
</head>
<body>
<?php
if (isset($_SESSION['message'])) {
$message = $_SESSION['message']; unset($_SESSION['message']);
}
else {
$message = "";
}
?> <div class="container" >
<h1 class="asd">Orders</h1>
</div> <div class="container" >
<div class="panel panel-default" >
<div class="panel-heading"> <form method="post"> <div class="input-group">
<div class="input-group-addon"> <select name="search_by">
<?php
foreach ($search_filters as $key => $value): ?>
<option value="<?= $key ?>" <?= $key == $search_by ? 'selected' : '' ?> > <?= $value ?> </option>
<?php
endforeach;
?>
</select>
</div>
<input type="search" name="comboBoxVal" value="<?= $comboBox ?>" class="form-control" placeholder="Search">
</div>
</form>
</div>
<div class="panel-body">
<?php
if ($message != ''): ?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true"> ×</span></button>
<?= $message ?> </div>
<?php endif; ?>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Order ID</th>
<th>User ID</th>
<th>Order Date</th>
<th>Order Time</th>
<th>Delivery Charge</th>
<th>Total Amount</th>
<th>Address</th>
<th>Coordinates</th>
<th>Driver Number</th>
<th>Order Status</th>
<th>Action</th>
</tr>
</thead>
<?php
/*** * DISPLAY TABLE */
?>
<tbody>
<?php if ($orders): ?>
<?php
while ($order = mysqli_fetch_array($orders, MYSQLI_BOTH)):
?>
<?php
$order_datetime = $order['order_datetime'];
$date = date('Y-m-d', strtotime($order_datetime));
$time = date('H:i:s', strtotime($order_datetime));
?>
<tr>
<td><?= $order['order_id'] ?></td>
<td><?= $order['user_id'] ?></td>
<td><?= $date ?></td>
<td><?= $time ?></td>
<td><?= $order['order_deliveryCharge'] ?></td>
<td><?= $order['order_totalAmount'] ?></td>
<td><?= $order['address'] ?></td>
<td><?= $order['coordinates'] ?></td>
<td><?= $order['driver_number'] ?></td>
<td><?= $order['order_status'] ?></td>
<td><button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal" onclick="viewOrder( '<?= $order['order_id'] ?>', '<?= $order['order_id'] ?>', '<?= $date ?>', '<?= $time ?>', '<?= $order['order_deliveryCharge'] ?>', '<?= $order['order_totalAmount'] ?>', '<?= $order['address'] ?>', '<?= $order['coordinates'] ?>', '<?= $order['driver_number'] ?>', '<?= $order['order_status'] ?>')"> View Order </button>
</td>
</tr>
<?php endwhile; ?>
<?php endif; ?>
</tbody>
</table>
</div>
<div class="panel-footer">
</div>
</div>
</div>
<script>
function viewOrder(order_id, user_id, order_date, order_time, order_deliveryCharge, order_totalAmount, address, coordinates, driver_number, order_status) {
document.getElementById("titleModal").innerHTML = "viewOrder";
document.getElementsByName("order_id")[0].setAttribute("value", order_id);
document.getElementsByName("user_id")[0].setAttribute("value", user_id);
document.getElementsByName("order_date")[0].setAttribute("value", order_date);
document.getElementsByName("order_time")[0].setAttribute("value", order_time);
document.getElementsByName("order_deliveryCharge")[0].setAttribute("value", order_deliveryCharge);
document.getElementsByName("order_totalAmount")[0].setAttribute("value", order_totalAmount);
document.getElementsByName("address")[0].setAttribute("value", address);
document.getElementsByName("coordinates")[0].setAttribute("value", coordinates);
document.getElementsByName("driver_number")[0].setAttribute("value", driver_number);
document.getElementsByName("order_status")[0].setAttribute("value", order_status);
document.getElementsByName("viewOrder")[0].setAttribute("name", "viewOrder");
/*x = document.getElementsByName("order_status").value;
if(x == "Accepted"){
document.getElementsByName("submitAccept").disabled = true;
}*/
}
</script?
</body>
</html>
And this is the ordermodal.php
UI of ordermodal.php
<?php
/** *ordermodal.php **/
$id = "";
$order_date = "";
$order_time = "";
$order_id = "";
$order_deliverCharge = "";
$order_status = "";
$order_totalAmount= "";
$coordinates = "";
$driver_number = "";
$address = "";
$food_name="";
$special_request="";
$quantity="";
$amount="";
$orders="";
?>
<!-- MODALS --> <!-- DETAILS -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form action="" method="post" class="form-horizontal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><center>×</button>
<h4 class="modal-title" id="titleModal"></h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="order_id" class="col-sm-2 control-label">Order ID</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_id" id="order_id" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="id" class="col-sm-2 control-label">ID</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="user_id" id="user_id" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_date" class="col-sm-2 control-label">Order Date</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_date" id="order_date" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_time" class="col-sm-2 control-label">Order Time</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_time" id="order_time" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_deliverCharge" class="col-sm-2 control-label">Delivery Charge</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_deliveryCharge" id="order_deliveryCharge" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_totalAmount" class="col-sm-2 control-label">Total Amount</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_totalAmount" id="order_totalAmount" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">Address</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="address" id="address" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="coordinates" class="col-sm-2 control-label">Coordinates</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="coordinates" id="coordinates" placeholder="" value="" required="required" maxlength="11" readonly>
</div>
</div>
<div class="form-group">
<label for="driver_number" class="col-sm-2 control-label">Driver Number</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="driver_number" id="driver_number" placeholder="" value="" required="required" readonly>
</div>
</div>
<div class="form-group">
<label for="order_status" class="col-sm-2 control-label">Order Status</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="order_status" id="order_status" placeholder="" value="" required="required" readonly>
</div>
</div>
<?php
// This is where I want to get the value of oder_id from order.php page
$sql = "SELECT food_name, special_request, quantity, amount
FROM cart_tbl
WHERE order_id=$order_id";
$result = mysqli_query(connection(), $sql);
?>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Food</th>
<th>Special Request</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
<?php
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["food_name"];?></td>
<td><?php echo $row["special_request"];?></td>
<td><?php echo $row["quantity"];?></td>
<td><?php echo $row["amount"];?></td>
</tr>
<?php
}
}
?>
</table>
<tbody>
</div>
<div class="modal-footer">
<button type="submit" name="showOrder" id="showOrder" class="btn btn-secondary" onclick="" > Show Order </button>
<button type="submit" name="submitAccept" id="submitAccept" class="btn btn-primary" onclick="if(!confirm('Are you sure you want to accept order?')){return false;}" > Accept </button>
<button type="submit" name="submitSent" class="btn btn-primary"onclick="if(!confirm('Are you sure you want to send order?')){return false;}" >Sent</button>
<button type="submit" name="submitCancel" class="btn btn-danger" onclick="if(!confirm('Are you sure you want to cancel order?')){return false;}">Cancel</button>
<?php
if(isset($_POST['showOrder'])){
$order_id = trim(addslashes($_POST['order_id']));
}
if(isset($_POST['submitAccept'])){
$order_id = trim(addslashes($_POST['order_id']));
$query = "UPDATE order_tbl SET `order_status`='Accepted' WHERE `order_id` = $order_id";
if (mysqli_query(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Accepted"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "ROLLBACK");
}
}
if(isset($_POST['submitSent'])){
$order_id = trim(addslashes($_POST['order_id']));
$query = "UPDATE order_tbl SET `order_status`='Dispatched' WHERE `order_id` = $order_id";
if (mysqli_query(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Dispatched"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "ROLLBACK");
}
}
if(isset($_POST['submitCancel'])){
$order_id = trim(addslashes($_POST['order_id']));
$query = "UPDATE order_tbl SET `order_status`='Cancelled' WHERE `order_id` = $order_id";
if (mysqli_query(connection(), $query)) {
mysqli_query(connection(), "COMMIT");
$_SESSION['message'] = "Order Cancelled"; }
else {
$_SESSION['message'] = mysqli_error(connection());
mysqli_query(connection(), "ROLLBACK");
}
}
?>
</div>
</form>
</div>
</div>
</div>
So the function of this as the moment is when clicked the view order the value of the order_id from order.php didnt get, you need first to click the button inside the ordermodal.php(accept,send,cancel) in order to get the value of order_id.
"When I click the view order, I'll get right away the value of order_id so that I can use it in my sql query. This is what supposed to be the real output."
Hope you guys can help me, I stacked at this error for a couple of days already. TIA!
Couldn't you still use the session var you did in the first chunk...unless you are reseting that value - but didn't see that...
Alternatively... the url you are calling to get the url for the modal you could put a query param of OID=# and than do the typical...
$orderID = $_GET['old'] ? $_GET['old'] : $_POST['old']; // not sure if your posting or just doing a get....
Also no sure if your pulling this in through an iframe or what not but either way query param or session var should work.
Hope this helps.

How to pass value from table to bootstrap modal to PHP?

I've fetched rows from MySQL and looped it with Bootstrap modal and I've made a form in modal from which the data is being sent to PHP script (update.php) with the help of ajax. But in return I am getting the output of last row only.
I need to get the record of specific student with its unique ID.
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
while($row = mysqli_fetch_assoc($query_run)){
$id = $row['id'];
$name = $row['name'];
$rollno = $row['rollno'];
$contact = $row['contact'];
$address = $row['address'];
echo "<tr>";
echo '<td>' . $name . '</td>';
echo '<td>' . $rollno . '</td>';
echo '<td>' . $contact . '</td>';
echo '<td>' . $address . '</td>';
echo "<td><button class='btn btn-link btn-custom dis' data-toggle='modal' data-target='#myModal$id'>
EDIT</button> </td>";
echo '</tr>';
?>
<div class="modal fade" id="myModal<?php echo $id; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="name" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="rollno" value="<?php echo $rollno; ?>">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="contact" value="<?php echo $contact; ?>">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="address"><?php echo $address; ?></textarea>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php }
}?>
</tbody>
</table>
</body>
</html>
JS:
$(document).ready(function(){
var values, url;
$('#updateValues').submit(function(e){
e.preventDefault();
values = $(this).serialize();
url = $(this).attr('action');
$.post(url, values, function(data){
$('#results').html(data);
});
});
});
Update.php:
<?php
if(isset($_POST['name'])&&isset($_POST['rollno'])&&isset($_POST['contact'])&&isset($_POST['address'])){
$id = $_POST['id'];
$name = $_POST['name'];
$rollno = $_POST['rollno'];
$contact = $_POST['contact'];
$address = $_POST['address'];
echo "$id $name $rollno $contact $address";
}else{
echo 'ERROR!';
}
?>
This is not tested/debugged but refactor your code similar to this:
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
$out = '
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
';
while($row = mysqli_fetch_assoc($query_run)){
$out .= '<tr class="trID_' .$row['id']. '">';
$out .= '<td class="td_name">' . $row['name'] . '</td>';
$out .= '<td class="td_rollno">' . $row['rollno'] . '</td>';
$out .= '<td class="td_contact">' . $row['contact'] . '</td>';
$out .= '<td class="td_address">' . $row['address'] . '</td>';
$out .= "<td><button class='td_btn btn btn-link btn-custom dis'>EDIT</button> </td>";
$out .= '</tr>';
}
$out .= '</tbody></table>
echo $out;
?>
<script>
$(document).ready(){
$('.td_btn').click(function(){
var $row = $(this).closest('tr');
var rowID = $row.attr('class').split('_')[1];
var name = $row.find('.td_name').val();
var rollno = $row.find('.td_rollno').val();
var contact = $row.find('.td_contact').val();
var address = $row.find('.td_address').val();
$('#frm_id').val(rowID);
$('#frm_name').text(name);
$('#frm_rollno').text(rollno);
$('#frm_contact').text(contact);
$('#frm_address').text(address);
$('#myModal').modal('show');
});
});//END document.ready
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="frm_name">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="frm_rollno">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="frm_contact">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="frm_address"></textarea>
</div>
<input type="hidden" name="frm_id">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php
}
}
?>
Notes:
(1) Create the entire table in a variable, then output the variable all at once.
(2) You only need one modal, not one modal for each table row. Therefore, remove modal creation from inside while loop.
(3) Use jQuery to:
(a) detect button click in row
(b) get table data for that row
(c) populate fields in modal
(d) display modal
You are using Bootstrap, which uses jQuery, so it makes sense to use jQuery to do this.
(4) Using jQuery to get values from table cells vs. input fields:
(a) .text() - from table cells
(b) .val() - from <input> or <textarea>
Here is a jsFiddle Demo you can play with that demonstrates how you can use jQuery to populate the modal depending on the row that was clicked.

Submit INPUT to the database to return as a Table PHP jQuery MySQL

I'm trying to refresh a data input into an INPUT through a form and then SUBMIT this to the database to return it as a table on the same page. I want it to do this without showing the refresh of the page.
This is what I have currently. When I put data into any of the INPUT fields and click SUBMIT nothing happens and nothing shows for an error.
<?php
session_start();
error_reporting (E_ALL);
require '../core/cnn.php';
if(isset($_POST['submitsearchprojno'])) {
$searchprojno = $_POST["searchprojno"];
}
if(isset($_POST['submitsearchadd'])) {
$searchaddress = $_POST["searchaddress"];
}
if(isset($_POST['submitsearchpc'])) {
$searchpostcode = $_POST["searchpostcode"];
}
$searchpostcode = mysql_real_escape_string($searchpostcode);
$searchaddress = mysql_real_escape_string($searchaddress);
$searchprojno = mysql_real_escape_string($searchprojno);
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Search Projects</h4>
</div>
<div class="modal-body">
<form class="modal-form" id="searchform" name="searchform" action="" method="post">
<div class="form-group">
<label class="col-md-4 control-label">Project Number</label>
<div class="col-md-6">
<input type="text" class="form-control input-inline input-medium" name="searchprojno" id="searchprojno" placeholder="Enter Project Number">
</div>
<button type="submit" class="btn blue" id="submitsearchprojno" name="submitsearchprojno" >Search <i class="m-icon-swapright m-icon-white"></i></button>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<input type="text" class="form-control input-inline input-medium" name="searchaddress" id="searchaddress" placeholder="Enter Address">
</div>
<button type="submit" class="btn blue" id="submitsearchadd" name="submitsearchadd" >Search <i class="m-icon-swapright m-icon-white"></i></button>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Postcode</label>
<div class="col-md-6">
<input type="text" class="form-control input-inline input-medium" name="searchpostcode" id="searchpostcode" placeholder="Enter Postcode">
</div>
<button type="submit" class="btn blue" id="submitsearchpc" name="submitsearchpc" >Search <i class="m-icon-swapright m-icon-white"></i></button>
</div>
<div class="form-group">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-striped table-bordered table-advance table-hover">
<thead>
<tr>
<th class="col-md-9"><i class="fa fa-list-alt"></i> Address</th>
<th class="col-md-3"></th>
</tr>
</thead>
<tbody>
<tr>
<?php $searchrs = mysql_query("SELECT ProjectNo, CONCAT(COALESCE(HouseNoName, ''), ' ', COALESCE(StreetName, ''), ' ',
COALESCE(TownOrCity, ''), ' ', COALESCE(Postcode, '')) AS Display, PropID, AreaID, AWGMember, Householder, HouseNoName,
StreetName, TownOrCity, Postcode, ContactTelephone, AlternatePhone, Email, PropertyTenure, PropertyNotes
FROM prop_property
WHERE IsActive = 1
AND (Postcode = '".$searchpostcode."'
OR StreetName = '".$searchaddress."'
OR ProjectNo = '".$searchprojno."')
") or die(mysql_error());
$checkrs = mysql_query("SELECT * FROM prop_property WHERE IsActive = 0");
if(!mysql_num_rows($checkrs) > 0) {
echo '<td> No record found!</td><td></td>';
}
else {
while ($results = mysql_fetch_array($searchrs)) {
echo '
<td id="displayadd">'.$results['Display'].'</td>
<td>
<form action="../jobdetails.php" method="post">
<input type="hidden" name="searchhouse" value=" '.$results['HouseNoName'].'" >
<input type="hidden" name="searchstreet" value=" '.$results['StreetName'].'" >
<input type="hidden" name="searchtown" value=" '.$results['TownOrCity'].'" >
<input type="hidden" name="searchpostcode" value=" '.$results['Postcode'].'" >
<input type="hidden" name="searchpropid" value=" '.$results['PropID'].'" >
<input type="hidden" name="searchprojectno" value=" '.$results['ProjectNo'].'" >
<button type="submit" class="btn default btn-xs blue-stripe" id="viewsearch" name="viewsearch">View Address</button>
</form>
</td>';
}
}?>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</form>
<div class="modal-footer right">
<button type="button" data-dismiss="modal" class="btn default">Cancel</button>
</div>
<script type="text/javascript">
$(function(){
$('#searchform').on('submit', function(e){
e.preventDefault();
//alert($('#searchpostcode').val())
$.post('includes/jobdetailssearch.php',
$('#searchform').serialize(),
function(data, status){
$('.table-responsive #displayadd').html(data.Display);
//$("#table-responsive td").last().append(data);
console.log("done");
}).fail(function () {
console.log("fail");
});
});
});
</script>
How can I get it to POST the INPUT to the database and return in the table?

Categories