Is it possible to call a function when a different option value is select from a select box? the select box consists of 'approved' 'pending' and 'dissapproved'. I have a form which will automatically flag the submission as 'pending' when entered in the database.
When changed by an admin from 'pending' to 'approved' or 'disapproved' this will run a SQL query to update the information in the table. What table structure would be best suited to this? and how can I ensure that when the option value is changed a CSS class is applied to the affected row of table cells. Which will remain the same unless changed. I have tried with jQuery however I do not feel it meets my requirements
Code:
<?php
$result = mysql_query("SELECT * FROM Orders")
or die (mysql_error());
?>
<form method ="post" action="sendemail.php">
<table style ="background-color:#ffffff;">
<tr>
<th>Order Number</th>
<th>Order Date</th>
<th>Ordered By</th>
<th>Supplier</th>
<th>Total Price</th>
<th>Requested By</th>
<th>Status</th>
</tr>
<?php
while ($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td><input type="text" name="order_n`enter code here`o[]" value="' . $row['Orderno'] . '"/> </td>';
echo '<td><input type="text" name="order_date[]" value="' . $row['Orderdate'] . '"/></td>';
echo '<td><input type="text" name="order_ordered_by[]" value="' . $row['Orderedby'] . '"/></td>';
echo '<td><input type="text" name="order_supplier[]" value="' . $row['Supplier'] . '"/></td>';
echo '<td><input type="text" name="order_total_price[]" value="' . $row['totalprice'] . '"/></td>';
echo '<td><input type="text" name="order_requested_by[]" value="' . $row['requestedby'] . '"/></td>';
echo '<td>';
echo '<select name="order_status[]">';
echo '<option></option>';
echo '<option>Approved</option>';
echo '<option>Pending</option>';
echo '<option>Dissaproved</option>';
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
Current jQuery to change table row colour, however I would like to add a CSS class to each option value and when the status is changed, this is reflected in the database, applying the correct class.
<script type="text/javascript">
$(document).ready(function() {
var color = ['none', '#DEF3CA', '#EECFA1', '#FFCCCC'];
$('table').on('change','select', function() {
$(this).parents('tr').css('background', color[$(':selected', this).index()]);
});
});
</script>
Table CSS:
<style type = "text/css">
table,td {
border:1px solid #999;
font-family: Tahoma,Arial,verdana;
font-size: 12px;
width:auto;
font-weight: none;
line-height: 1.4em;
font-style: normal;
border-collapse:separate;
}
td {
width:250px;
padding:15px;
color:#000;
border:1px solid;
border-bottom:1px solid;
}
</style>
SendEmail script to email each person based on 'Requestedby'
<?php
if(isset($_POST['order_requested_by']))
{
$row_count = count($_POST['order_requested_by']);
for($i=0; $i<$row_count; $i++)
{
$to = $_POST['order_requested_by'][$i];
$subject = "Order Status";
$message = "Your order number: " . $_POST['order_no'][$i] ." ". "is" ." ". $_POST['order_status'][$i];
$orderdate = "Order date: " . $_POST['order_date'][$i];
$from = "no-reply#.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$orderdate,$headers);
echo "Mail Sent.";
}
?>
Send the selection value to another page via a variable and then
$selection = $_POST['variable']
if ($selection == "1") {
....
}
elseif ($selection == "2") {
....
}
Related
Here I have HTML, PHP and Jquery code with where I can edit all my record using the modal, the problem is that it keeps disappearing after I click on my update button, the modal only shows for about half a second. Can you help me? I'm actually new and just learning Jquery
this is the front view
<?php
include 'php/header.php';
require_once 'php/connect.php';
?>
<script>
$(document).ready(function(){
$("#input").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#body tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<style>
table, th, td {
border: 1px solid black;
color: black;
width: auto;
margin: auto;
}
td {
text-align: center;
}
.edit {
background-color: blue;
font-family: algerian;
color: lime;
border-radius: 30px;
}
.edit:hover {
cursor: pointer;
background-color: yellow;
color: black;
}
.delete {
color: white;
background: black;
font-family: algerian;
}
.delete:hover {
color: black;
background: yellow;
}
</style>
<h1 style=" font-family: algerian; color: lime" align="center">Assets</h1>
<div class="filter">
<input style="height: 23px; float: right;" id="input" type="text" placeholder="Search.." autocomplete="off"></div>
<br>
<br>
<table align="center">
<tr>
<a onclick="" href=""></a>
<thead>
<th>Asset Num</th>
<th>FA num</th>
<th>Employee</th>
<th>Team</th>
<th>Contractor</th>
<th>Status</th>
<th>Category</th>
<th>Disposed</th>
<th colspan="2">Actions</th>
</thead>
<tbody id="body">
<?php
$sql = " SELECT * FROM assets
LEFT JOIN team
ON assets.team_id = team.team_id
LEFT JOIN contractor
ON assets.contractor_id = contractor.contractor_id
LEFT JOIN employee
ON assets.employee_id = employee.employee_id
LEFT JOIN item_status
ON assets.status_id = item_status.status_id
LEFT JOIN category
ON assets.category_id = category.category_id
ORDER BY category ";
$result = mysqli_query($conn, $sql);
if ($result->num_rows> 0) {
while($row = $result->fetch_assoc())
{
if (empty($row["disposal_status_id"])) {
$row["disposal_status_id"] = "NO"; }
else {
$row["disposal_status_id"] = "YES";
}
echo "<tr>";
echo "<td>". $row["asset_num"] ."</td>" ;
echo "<td>". $row["fa_num"]."</td>";
echo "<td>". $row["first_name"]. " " .$row["last_name"]. "</td>";
echo "<td>". $row["team"]."</td>";
echo "<td>". $row["F_name"]."</td>";
echo "<td>". $row["item_status"]."</td>";
echo "<td>". $row["category"]."</td>";
echo "<td>". $row["disposal_status_id"] ."</td>";
echo "<td><form method='POST' id='form'><button name='edit' class='edit' value=". $row['assets_id'] . " >Update</button></form>";
echo "<td><a class='delete' onclick=\"return confirm('Are you sure you want to delete this record?')\"
href='php/delete_asset.php?id=".$row['assets_id']."'>Delete</a>";
echo "</tr>";
}
}
else {
echo "<p style='font-family: algerian; font-size: 30px; margin-left: 45%; color: yellow ' >No Record</p>";
}
?>
</tbody>
</table>
and this is the modal view
<script>
$(document).ready(function() {
$(".edit").click(function(){
$("#modal").css('display', 'block');
});
});
</script>
<script>
$(document).ready(function() {
$("#cancel").click(function(){
$("#modal").css("display", "none");
});
});
</script>
<script>
$(document).ready(function(){
$("#form").submit(function() {
var edit = $(this).val();
$.ajax({
type: "POST",
data: {edit:edit},
});
});
});
</script>
<?php
include 'php/connect.php';
$id = $_POST['edit'];
$d = mysqli_query($conn, " SELECT * FROM assets
LEFT JOIN employee
ON assets.employee_id = employee.employee_id
LEFT JOIN team
ON assets.team_id = team.team_id
LEFT JOIN contractor
ON assets.contractor_id = contractor.contractor_id
LEFT JOIN item_status
ON assets.status_id = item_status.status_id
LEFT JOIN category
ON assets.category_id = category.category_id
LEFT JOIN disposal_status
ON assets.disposal_status_id = disposal_status.disposal_status_id
WHERE assets_id = '$id'");
$check = mysqli_fetch_array($d);
function load_employee()
{
include 'php/connect.php';
$output = '';
$sql = "SELECT * FROM employee ORDER BY first_name";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='" . $row['employee_id'] ."'>"
. $row['first_name'] . " "
. $row['last_name'] . " </option>";
}
return $output;
}
?>
<div id="modal">
<script>
$(document).ready(function(){
$('#employee').change(function(){
var employee_id = $(this).val();
$.ajax({
url:"php/get_employee_team.php",
method: "POST",
data: {employee_id:employee_id},
dataType:"text",
success:function(data)
{
$('#team').html(data);
}
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="../mystyle.css">
<style>
#modal {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0%;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
z-index: 2;
cursor: pointer;
background-color: rgba(0,0,0,0.8); /* Black w/ opacity */
}
</style>
<form method="POST" action="php/update_assets.php" >
<table align="center">
<th colspan="4" >Update Asset # <?php echo $check['assets_id']; ?></th>
<tr></tr>
<input style="display: none" type="text" name="assets_id" value="<?php echo $check['assets_id'] ?>">
<td>Asset Num:</td>
<td><input type="text" name="asset_num" value="<?php echo $check['asset_num'] ?>" autocomplete="off" required></td>
<td>Unit Condition:</td>
<td><input type="text" name="condition" value="<?php echo $check['condition'] ?>" autocomplete="off" ></td>
<tr></tr>
<td>FA Num:</td>
<td><input type="text" name="fa_num" value="<?php echo $check['fa_num'] ?>" autocomplete="off" required></td>
<td>Audit Date:</td>
<td><input type="date" name="audit" value="<?php echo $check['audit_date'] ?>" autocomplete="off"></td>
<tr></tr>
<tr>
<td>Employee:</td>
<td>
<select id="employee" name="employee" >
<?php
echo "<option value='" . $check['employee_id'] ."'>"
. $check['first_name'] . " "
. $check['last_name'] . " </option>";
?>
<option><?php echo load_employee(); ?></option>
</select>
</select></td>
<td>Location:</td>
<td><input type="text" name="location" value="<?php echo $check['location'] ?>" autocomplete="off"></td>
</tr>
<tr>
<td>Team:</td>
<td>
<select style="color: black" id="team" name="team" readonly>
<option value= "<?php echo $check['team_id'] ?>" ><?php echo $check['team'] ?></option>
</select>
</td>
<td>Insurance Date:</td>
<td><input type="date" name="insurance" value="<?php echo $check['audit_date'] ?>"></td>
</tr>
<td>Contractor:</td>
<td><select name="contractor">
<?php
echo "<option value='" . $check['contractor_id'] ."'>"
. $check['F_name'] . " "
. $check['L_name'] . " </option>";
?>
<option>
<?php
$sql = "SELECT * FROM contractor" ;
$result = mysqli_query($conn, $sql);
while ($row =mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['contractor_id'] ."'>"
. $row['F_name'] . " "
. $row['L_name'] . " </option>";
}
?>
</option>
</select> </td>
<td>Comments:</td>
<td><input style="overflow: scroll;" type="text" name="comments" value="<?php echo $check['comments'] ?>" autocomplete="off"></td>
<tr></tr>
<td>Status:</td>
<td><select name="status">
<?php
echo "<option value='" . $check['status_id'] ."'>"
. $check['item_status'] . " </option>";
?>
<option>
<?php
$sql = "SELECT * FROM item_status " ;
$result = mysqli_query($conn, $sql);
while ($row =mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['status_id'] ."'>"
. $row['item_status'] . " </option>";
}
?>
</option>
</select>
</td>
<td colspan="2"> <br></td>
<tr></tr>
<td>Asset Category:</td>
<td>
<select name="category">
<?php
echo "<option value='" . $check['category_id'] ."'>"
. $check['category'] . " </option>";
?>
<option>
<?php
$sql = "SELECT * FROM category" ;
$result = mysqli_query($conn, $sql);
while ($row =mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['category_id'] ."'>"
. $row['category'] . " </option>";
}
?>
</option>
</select>
</td>
<td colspan="2"> <br></td>
<tr></tr>
<td>Description:</td>
<td><input type="text" name="description" value="<?php echo $check['description'] ?>" autocomplete="off">
<td colspan="2" style="text-align: center; color: blue; font-family: algerian" >DISPOSAL DETAILS</td>
<tr></tr>
<td>Serial Number:</td>
<td><input type="text" name="serial" value="<?php echo $check['serial_num'] ?>" autocomplete="off"></td>
<td>Disposal Location</td>
<td><input type="text" name="disposal_loc" value="<?php echo $check['disposal_location'] ?>" autocomplete="off"></td>
<tr></tr>
<td>Date Aquired:</td>
<td><input type="date" name="acquired" value="<?php echo $check['date_get'] ?>" autocomplete="off"></td>
<td>Date Disposed</td>
<td><input type="date" name="disposal_date" value="<?php echo $check['disposal_date'] ?>" autocomplete="off"></td>
<tr></tr>
<td>Purchase Price:</td>
<td><input type="text" name="price" value="<?php echo $check['purchase_price'] ?>" autocomplete="off"></td>
<td>Disposed Status</td>
<td>
<select id="dept" name="disposal_status">
<?php
if ($check['disposal_status_id'] == 0) {
echo "<option value='". $checl['disposal_status_id'] ."' >";
echo "NOT YET";
echo "</option>";
}
?>
<?php
$sql = "SELECT * FROM disposal_status " ;
$result = mysqli_query($conn, $sql);
while ($row =mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['disposal_status_id'] ."'>"
. $row['status'] . " </option>";
}
?>
</select>
</td>
<tr></tr>
<br>
<td style="text-align: center;" colspan="4"><button type="submit" name="btn" class="submit" >Submit</button>
<p class="submit" id="cancel">Cancel</p></form>
</td>
</table>
</div>
I try to send the data in the same page and try to change the CSS code when I click on the Update button, sending the id and fetching the data required using ajax Jquery, Hope someone can help me, thanks in advance
I think you need to use preventDefault() function because the nature of submiting form is to refresh the page that's also the reason why the modal is appearing just a couple of seconds only or sometimes it is not appearing.
Please try these line of code.
$("#form").on("submit",function(event) {
event.preventDefault();
var edit = $(this).val();
$.ajax({
type: "POST",
data: {edit:edit},
});
});
});
I am just starting with SQL, PHP, and HTML and I plan to take some courses, but I need a basic working model before I can move forward. I have an SQL database that has a few fields. I can display this data without a problem. I would like to filter this data with a drop-down box. Currently, I have the drop-down box populated with a Select Distinct command. I can not seem to figure out the syntax to modify my SQL Select command to only show records that match my pull-down box. Ha, I will be the first to admit that I have no clue what I am doing, but my problem is that I might not know the term I need to look up how to solve my problem. Google and I are tight, but we just can't put our finger on this one. Can you point me in the right direction? Thanks!
<!DOCTYPE html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even){
background-color: #dddddd;
}
</style>
<body>
<form action='new1.php' method="get" name='fPIC'>
<select class="form-dropdown validate[required]" style="width:150px" id="input_PIC" name="sPIC">
<?php
$link = mysqli_connect("localhost", "root", "**********", "pd4poc");
mysqli_select_db($link,'pd4poc');
$query = "SELECT DISTINCT PIC FROM dummydata order by PIC asc";
$result = mysqli_query($link,$query);
$menu=" ";
while($row = mysqli_fetch_array($result))
{
$menu .= "<option value=".$row['PIC'].">" .$row['PIC']. "</option>";
}
echo $menu;
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['PIC'] . "<td><td>" , $row['Reason'] . "<td><td>", $row['Status'] . "</td></tr>";
}
echo "</table>";
mysqli_close($link);
?>
</select>
<input type="submit" name="nPIC" value="Filter">
</form>
<?php
$link = mysqli_connect("localhost", "root", "**********", "pd4poc");
mysqli_select_db($link,'pd4poc');
$query = "SELECT * FROM dummydata"; //need to be picked from the pull down
$result = mysqli_query($link,$query);
echo "<table>";
echo "<tr>
<th>PIC</th>
<th>Reason</th>
<th>PlanApply</th>
<th>HOT</th>
<th>Status</th>
<th>Comments</th>
</tr>\n";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" .
$row['PIC'] . "<td>",
$row['Reason'] . "<td>",
$row['PlanApply'] . "<td>",
$row['HOT'] . "<td>",
$row['Status'] . "<td>",
$row['Comments'] . "</td>\n</tr>";
}
echo "</table>";
mysqli_close($link);
?>
</body>
</head>
Hi I have a table generated from php, it is editable, I want to save edited values to database. I have no Idea how can I do this as there are many rows(dynamic) on a page.
Here is a screen-shot:-
Please suggest
Edit:-
My code is
echo "<table border='1'>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>";
while($row = $result->fetch_assoc())
{
echo "<tr contenteditable>";
echo "<td>" . $row["Row Number"]. "</td>";
echo "<td>" . $row["Product Id"]. "</td>";
echo "<td>" . $row["Product Name"]. "</td>";
echo "<td>" . $row["Product Catagory"]. "</td>";
echo "<td>" . $row["Retal Price"]. "</td>";
echo "<td>" . $row["Max Price"]. "</td>";
echo "<td>" . $row["Min Price"]."</td>";
echo "<td>" . $row["Initial Stock"]."</td>";
echo "<td>" . $row["Quantity Sold"]. "</td>";
echo "<td>" . $row["Current Stock"]."</td>";
echo "<td>" . $row["Last Order"]."</td>";
echo "<td contenteditable = 'false'><button href = '#'>Update</a></td>";
echo "</tr>";
}
Let me give you with the best way
First your database tables have spaces: correct that e.g.
from $row["Initial Stock"] to $row["Initial_Stock"]
Then i will propose you use ajax instead of wasting time clicking buttons
The HTML Page
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script>
$(function(){
$("#loading").hide();
//acknowledgement message
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('update.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},1000);
}
});
});
});
</script>
<style>
table.zebra-style {
font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
text-align:left;
border:1px solid #ccc;
margin-bottom:25px;
width:100%
}
table.zebra-style th {
color: #444;
font-size: 13px;
font-weight: normal;
padding: 5px 4px;
}
table.zebra-style td {
color: #777;
padding: 4px;
font-size:13px;
}
table.zebra-style tr.odd {
background:#f2f2f2;
}
#status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
#loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
</style>
<div id="status"> </div>
<div id="loading"></div>
<table id="tableID" border="0" class="sortable table zebra-style">
<thead>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>
</thead>
<tbody class="list">
<?php do { ?>
<tr>
<td contenteditable="true" id="Row_Number:<?php echo $row["Row_Number"]; ?>"><?php echo $row["Row_Number"]; ?></td>
<td contenteditable="true" id="Product_Id:<?php echo $row["Product_Id"]; ?>"><?php echo $row["Product_Id"]; ?></td>
<td contenteditable="true" id="Product_Name:<?php echo $row["Product_Name"]; ?>"><?php echo $row["Product_Name"]; ?></td>
<td contenteditable="true" id="Product_Catagory:<?php echo $row["Product Id"]; ?>"><?php echo $row["Product_Catagory"]; ?></td>
<td contenteditable="true" id="Retal_Price:<?php echo $row["Retal_Price"]; ?>"><?php echo $row["Retal_Price"]; ?></td>
<td contenteditable="true" id="Max_Price:<?php echo $row["Max_Price"]; ?>"><?php echo $row["Max_Price"]; ?></td>
<td contenteditable="true" id="Min_Price:<?php echo $row["Min_Price"]; ?>"><?php echo $row["Min_Price"]; ?></td>
<td contenteditable="true" id="Initial_Stock:<?php echo $row["Initial_Stock"]; ?>"><?php echo $row["Initial_Stock"]; ?></td>
<td contenteditable="true" id="Quantity_Sold:<?php echo $row["Quantity_Sold"]; ?>"><?php echo $row["Quantity_Sold"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable = 'false'></td>";
</tr>
<?php } while($row = $result->fetch_assoc()) ?>
</tbody>
</table>
And the update php page
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8',
'username',
'password',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
?>
<?php
if(!empty($_POST))
{
//database settings
foreach($_POST as $field_name => $val)
{
//clean post values
$field_id = strip_tags(trim($field_name));
//from the fieldname:user_id we need to get user_id
$split_data = explode(':', $field_id);
$product_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($product_id) && !empty($field_name) && !empty($val))
{
$affected_rows = $db->exec("UPDATE yourtable SET $field_name = '$val' WHERE product_ID = $product_id");
echo $affected_rows;
echo "Updated";
} else {
echo "Invalid Requests";
}
}
}
else {
echo "Invalid Requests";
}
?>
To save the whole table, you could leave the row-level update buttons out, and have a single save button:
<button id="save">Save</button>
<div id="msg"></div>
The msg area is to display feed-back from the server when the save-operation is performed.
Then you would add this JavaScript to handle the click of the save button:
$('#save').click(function() {
var data = [];
$('td').each(function() {
var row = this.parentElement.rowIndex - 1; // excluding heading
while (row >= data.length) {
data.push([]);
}
data[row].push($(this).text());
});
$.post('savetable.php', {table: data}, function (msg) {
$('#msg').text(msg);
});
});
This will transform the HTML table contents, without header row, to a JavaScript matrix, which then is sent to savetable.php for processing.
In PHP you would then use $_POST['table'] to access that array. When you implement this, first debug, and do a var_dump($_POST['table']) to make sure the data was transferred correctly, and it has the array structure you expect.
Then loop over that array to insert the rows into your database. You can use mysqli or PDO for this.
The PHP script savetable.php should only echo one message: a confirmation ("the table was saved successfully") or an error message ("a problem occurred. Your data was not saved.").
It should not reproduce the HTML of the table, since that is already displayed in the browser. Whatever PHP prints will be used by the JavaScript code to be displayed below the save button.
Here is how savetable.php could look like. But please debug carefully, I did not test this code. And before it works, you first need to set up your database model of course:
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4',
'username', 'password');
// Configure that all database errors result in an exception:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// Make a transaction: this allows to rollback any of the changes
// if anything goes wrong before the end of it.
$db->beginTransaction();
// First delete all rows.
$db->exec("DELETE FROM mytable");
// Prepare a statement that will be executed for each row.
// Needs to be extended for all columns:
$stmt = $db->prepare("INSERT INTO mytable (sl_num, product_id, product_name)
VALUES (?, ?, ?)");
foreach ($_POST('table'] as $row) {
$stmt->execute($row); // the columns are passed to the prepared statement.
}
// All went well: commit the changes.
$db->commit();
echo "Table saved successfully";
} catch(PDOException $e) {
// Something went wrong: roll back any changes made
$db->rollback();
echo "An error occurred: " . $e->getMessage();
}
What you can do is ajax call to a php with the id of the row you want to save and the new data. Then use PDO to connect to the database and update the information. After that is done, use javascript to edit the table itself.
So what you need to do is look up how to use ajax calls and use PDO. I suggest when you echo the table itself
<button href = '#' onclick="updateRow('. $row['Row Number'] .')">Update</a></td> where Row Number is the ID in the database and updateRow() is the javascript function you will create to get the new information and send it via ajax. Don't use mysql_*, because it is not supported in php 7 and it will die soon. Look up PDO instead.
I have a php file which selects a large amount of data from mutiple sql table. Naturally it takes a long time to complete the whole process. I want to display a progress bar which will express the progress of the script running. How to display a progress bar? The script below shows a portion of the php file.
<?php
//RIGHT(AdmitCode,1), PartCode, MID(AdmitCode,2,2), MID(AdmitCode,1,1) DESC, RollCode
$query = "SELECT * FROM students1 ORDER BY PartCode, AdmitCode, yearcode desc, RollCode";
$result = mysql_query($query);
// start a table tag in the HTML
echo "<table border='1' align='center' style='border-collapse:collapse' width='110%'>";
echo "<caption>
<h2>List of candidates for Three year Degree
(Honours/General) Programme Examination-".$bx1." (".$bx2.")
</h2>
</caption>";
//$row['index'] the index here is a field name
echo "<tr bgcolor=''>
<th> Sl. No </th>
<th>ID </th>
<th> Semester </th>
<th> Roll No </th>
<th> Registration No</th>
<th> Name </th>
<th> Honours </th>
<th> Elective-1 </th>
<th> Elective-2 </th>
<th> Elective-3 </th>
<th> MIL </th>
<th> Foundation </th>
<th> Soft studies </th>
<th> Syllabus </th>
</tr>";
$ty=0;
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
$ty++;
if ($ty%2==0)
echo "<tr bgcolor='pink'>";
else
echo "<tr>";
echo "<td align='center'>$ty</td>
<td align='center'>" . $row['StudentID']." </td>
<td align='center'>" . $row['PartCode']."</td>
<td align='center'>" . $row['AdmitRollNo'] . "</td>
<td align='center'>" . $row['RegistrationNo']. "</td>
<td align='left'>" . $row['Name'] . "</td>
<td align='center'>" . $row['HonoursSubject'] . "</td>
<td align='center'>". $row['ElectiveSubject1'] . "</td>
<td align='center'>". $row['ElectiveSubject2'] . "</td>
<td align='center'>". $row['ElectiveSubject3'] . "</td>
<td align='center'>". $row['MIL'] . "</td>
<td align='center'>". $row['Foundation'] . "</td>
<td align='center'>". $row['SoftStudies'] . "</td>
<td align='center'>". $row['Syllabus'] . "</td>
</tr>";
}
echo "</table>"; //Close the table in HTML
Generally, to implement a good progress bar, you need a progress indicator from the layer which does the work, i.e. the mysql database. I am not aware, that mysql provides such a feature.
So you are stuck with estimating how long the operation will probably last (i.e. from past queries or derive it from the query parameters) and just implement a javascript progress bar (JQueryUI provides a good one), which is just time based.
Alternatively, you could just use a spinner to indicate, that you do not know how long this process really runs.
you can add div coantainer for the table and has id page and add css this show the loading image until page full load.
eg.
<div id="page">
<table>
</table>
</div>
css
<style>
#page {
display: none;
}
#loading {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100vw;
height: 100vh;
// background-image: url(loading_spinner.gif);
background-image:url("loading_spinner.gif");
background-repeat: no-repeat;
background-position: center;
}
</style>
<script>
$(window).load(function() {
$('#page').show();
$('#loading').hide('slow');
});
</script>
add this js code in your page this will help you.
You can use the following simple code
<?php
//header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
//long_process.php
for($i=1;$i<=3;$i++){
//do something
echo '<br>processing...';
ob_flush();
flush();
sleep(1);
}
echo 'CLOSE', 'Process complete';
?>
Or use as following
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<br />
<input type="button" onClick="startTask()" value="Start Long Task" />
<input type="button" onClick="stopTask();" value="Stop Task" />
<br />
<br />
<p>Results</p>
<br />
<div id="results" style="border:1px solid #000; padding:10px; width:300px; height:250px; overflow:auto; background:#eee;"></div>
<br />
<progress id='progressor' value="0" max='100' style=""></progress>
<span id="percentage" style="text-align:right; display:block; margin-top:5px;">0</span>
</body>
</html>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
var es;
function startTask() {
es = new EventSource('bar2.php');
//a message is received
es.addEventListener('message', function(e) {
var result = JSON.parse( e.data );
addLog(result.message);
if(e.lastEventId == 'CLOSE') {
addLog('Received CLOSE closing');
es.close();
var pBar = document.getElementById('progressor');
pBar.value = pBar.max; //max out the progress bar
}
else {
var pBar = document.getElementById('progressor');
pBar.value = result.progress;
var perc = document.getElementById('percentage');
perc.innerHTML = result.progress + "%";
perc.style.width = (Math.floor(pBar.clientWidth * (result.progress/100)) + 15) + 'px';
}
});
es.addEventListener('error', function(e) {
addLog('Error occurred');
es.close();
});
}
function stopTask() {
es.close();
addLog('Interrupted');
}
function addLog(message) {
var r = document.getElementById('results');
r.innerHTML += message + '<br>';
r.scrollTop = r.scrollHeight;
};
</script>
Then create the following page. It has called in the index.php
bar.php
<?php
header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
function send_message($id, $message, $progress) {
$d = array('message' => $message , 'progress' => $progress);
echo "id: $id" . PHP_EOL;
echo "data: " . json_encode($d) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
//LONG RUNNING TASK
for($i = 1; $i <= 10; $i++) {
send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
sleep(1);
}
send_message('CLOSE', 'Process complete');
I'm making a page to register damage mobile phones. I made a search query to search data in database which matched datepicker's date. Here is my source code. (Only relevant to this question, )
<?php
$con = mysql_connect("localhost", "root", "");
if ($con) {
$db = mysql_select_db('mobile', $con);
} else {
die('Could not connect: ' . mysql_error());
}
if (array_key_exists('myday', $_POST)) {
$mydate = $_POST['mydate'];
$myday = "SELECT * FROM mobile_rep WHERE sdate='{$mydate}' ";
}
mysql_close($con)
?>
<html>
<head> </head>
<body>
<form action="index.php" method="POST" class="form-inline">
<div class="span12" style="border-radius: 5px; border-style: solid; border-width: 1px; margin-left: 20px;" >
<h5 style="margin-left: 10px; "> <b> Current User List </b></h5>
Select By Date
<input type="date" name="mydate" id="mydate" class="input-medium" />
<input type="submit" class="btn-primary " name="myday" value="Search by date" id='myday' />
<br/> <br/>
<table border="1" width="300" cellspacing="1" cellpadding="1" class="table table-striped" style=" border-radius: 5px; border-style: solid; border-width: 1px; ">
<thead>
<tr>
<th>sdate</th>
<th>model_no</th>
<th>fault</th>
<th>rp_fee</th>
<th>sp_fee</th>
<th>total</th>
</tr>
</thead>
<tbody>
<?php
while ($row1 = mysql_fetch_array($myday)) {
echo "<tr>";
echo "<td>" . $row1['sdate'] . "</td>";
echo "<td>" . $row1['model_no'] . "</td>";
echo "<td>" . $row1['fault'] . "</td>";
echo "<td>" . $row1['rp_fee'] . "</td>";
echo "<td>" . $row1['sp_fee'] . "</td>";
echo "<td>" . $row1['total'] . "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</form>
</body>
</html>
And I'm having
Undefined variable: myday in C:\wamp\www\mobile\index.php on line 227
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\wamp\www\mobile\index.php on line 227
Line 227 means while ($row1 = mysql_fetch_array($myday)) {
I also uploaded an image of my page too.
Please help me.
When you enter your page first time, $myday variable is not set. If you send your POST code then if (array_key_exists('myday', $_POST)) { } is executed and $myday is created.
Just check before while loop if your variable exists, otherwise it pass null value to mysql_fetch_data function
if(isset($myday)) { while ($row1 = mysql_fetch_array($myday)) ... }