Update Selected Image Based on Checkbox check - javascript

I need to upload selected image but I don't have any idea to make it. Anyone could help me on this problem? Included code below. Thank you for helping in advance.
Test.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function myFunction1(isChecked2){
$('.chckbox1').change( function() {
var isChecked2 = this.checked;
if(isChecked2) {
$(this).parents("tr:eq(0)").find(".product_img").prop("disabled",false);
} else {
$(this).parents("tr:eq(0)").find(".product_img").prop("disabled",true);}
})};
</script>
</head>
<body>
<form method="post" action="UPDATE.php">
<div class="row">
<div class="col-xs-4">
<table id="simple-table" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th class="center">Select</th>
<th class="center">Product Image</th>
<th class="center">New Image</th>
</tr>
</thead>
<tbody>
<?php
//connect to database
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//select table from database
mysql_select_db("MBTR", $con);
$result = mysql_query("SELECT * from maray_product_img WHERE product_id='P100044'");
//query resutl
$countrow = 1;
//read result
while($row = mysql_fetch_array($result))
{
$img_id=$row['img_id'];
$p_id = $row['product_id'];
$product_img_name = $row['product_img_name'];
$product_img = $row['product_img'];
$product_img_path = $row['product_img_path'];
//$product_quantity = $row['product_quantity'];
?>
<tr>
<td class="center" style="vertical-align:middle"> <input name="img_id[]" type="checkbox" id="check[]" class="chckbox1 ace" value="<?php echo $img_id;?>" onclick="myFunction1(this)"/><span class="lbl red"><input type="hidden" name="product_id[<?php echo $img_id;?>]" value="<?php echo $p_id;?>"></span><input type="hidden" name="product_img_name[<?php echo $img_id;?>]" value="<?php echo $product_img_name;?>"></td>
<td class="center"><img src="<?php echo $row['product_img_path'];?>" width="60" height="60"></td>
<td class="center" style="vertical-align:middle"><input type="file" name="product_img[<?php echo $img_id;?>]" id="product_img[]" class="product_img form-control" disabled></td>
</tr>
<?php
$countrow++;
}
?>
</tbody>
</table>
</div><!-- /.span -->
</div><!-- /.row -->
<button type="submit" name="submit">Update</button>
</form>
</body>
</html>
UPDATE.php
<?php
error_reporting(E_ALL & ~E_NOTICE);
include ("dbconfig.php");
require_once('auth.php');
$product_img_name=$_FILES["product_img"]["name"];
if((isset($_POST['img_id'])))
{
$rand = rand(5,987897899);
foreach($_POST["img_id"] as $imgId)
{
//$product_img_name= $_POST['product_img_name'][$imgId];
$tmpName = $_FILES['product_img_name']['tmp_name'][$imgId];
$imagetmp=addslashes (file_get_contents($tmpName));
$name=basename($_FILES['product_img_name']['name'][$imgId]);
$t_name=$_FILES['product_img']['tmp_name'][$imgId];
$dir='upload';
$new_name= date('dmY')."_".$product_code."_".$rand."_".$name;
if(move_uploaded_file($t_name,$dir."/".$new_name))
{
$query = mysql_query("UPDATE maray_product_img set product_img_name='$imagename',
product_img_path='upload/$imagename', product_img='$imagetmp' where img_id='$imgId' LIMIT 1");
echo "<script>alert ('Successfull! Data has been changed.')</script>";
echo "<script>window.location = 'test.php'</script>";
}
else
{
echo "<script>alert ('Failed to update. Please try again')</script>";
}
}
}
?>
Hope experts can help me on this. I'm new to PHP. Some of the code which I got from others. Really need help. Thank you in advance.

Related

Filtering db table by date

My goals is to make filter for loading posts from 1 week ago, 1 month ago and two inputs from date from and date to ( if one of them is empty to be filled with current date( y-m-d h:m:s ) format
This is all i tried and could have made it to work, every answer is much appreciated, thank you
Tl:dr
Select filter for week ago, month ago
From date - to date ( if one of those is empty then use current date )
Index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM tbl_order ORDER BY order_id desc";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Ajax PHP MySQL Date Range Search using jQuery DatePicker</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">Ajax PHP MySQL Date Range Search using jQuery DatePicker</h2>
<h3 align="center">Order Data</h3><br />
<div class="col-md-3">
<input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" />
</div>
<div class="col-md-3">
<input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" />
</div>
<div class="col-md-5">
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" />
</div>
<div style="clear:both"></div>
<br />
<div id="order_table">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="30%">Customer Name</th>
<th width="43%">Item</th>
<th width="10%">Value</th>
<th width="12%">Order Date</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["order_id"]; ?></td>
<td><?php echo $row["order_customer_name"]; ?></td>
<td><?php echo $row["order_item"]; ?></td>
<td>$ <?php echo $row["order_value"]; ?></td>
<td><?php echo $row["order_date"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filter.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#order_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
And filter.php
<?php
//filter.php
if(isset($_POST["from_date"], $_POST["to_date"]))
{
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
$query = "
SELECT * FROM tbl_order
WHERE order_date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'
";
$result = mysqli_query($connect, $query);
$output .= '
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="30%">Customer Name</th>
<th width="43%">Item</th>
<th width="10%">Value</th>
<th width="12%">Order Date</th>
</tr>
';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'. $row["order_id"] .'</td>
<td>'. $row["order_customer_name"] .'</td>
<td>'. $row["order_item"] .'</td>
<td>$ '. $row["order_value"] .'</td>
<td>'. $row["order_date"] .'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Order Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
?>
Use something like this to make sure that you are getting the correct format from your datepicker:
$("#from_date").datepicker({ dateFormat: 'yy-mm-dd' }).val();
Make PHP variables to use in your query for the date:
$fromDate = !empty($_POST['from_date']) ? "'".mysqli_escape_string($_POST["from_date"])."'" : "CURDATE()";
$toDate = !empty($_POST["to_date"]) ? "'".mysqli_escape_string($_POST["to_date"])."'" : "CURDATE()";
$query =
"SELECT *
FROM tbl_order
WHERE order_date
BETWEEN $fromDate
AND $toDate";
NOTE: You should also add some logic in there to make sure that the from_date does not end up being before the to_date.
NOTE 2: This answer is making the assumption that you have not set up PDO. Always make sure to avoid SQL injection attacks in some way. Any values coming from the front end are unsafe and subject to SQL injection. PDO would be preferable, but escaping will work.
You can try casting your $_POST using CAST function to convert values to date.
$query = "SELECT * FROM tbl_order
WHERE order_date
BETWEEN CAST('".$_POST["from_date"]."' AS DATE)
AND CAST('".$_POST["to_date"]."' AS DATE)";
You can read about it on MySQLTutorial .
Also I recommend you to escape variables when working with database :-) Always expect user is up to no good.

create validation for offset in importing csv file in mysql and php

hi guys how can i create a validation so that when i import a csv file it will not give me a error offset(intentionally reduced the csv file column)
i got the code https://www.webslesson.info/2016/10/import-csv-file-data-into-mysql-database-using-php-ajax.html
here is the code in index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "db");
$query = "SELECT * FROM tbl_employee ORDER BY id desc";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Import CSV File Data into MySQL Database using PHP & Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">Import CSV File Data into MySQL Database using PHP & Ajax</h2>
<h3 align="center">Employee Data</h3><br />
<form id="upload_csv" method="post" enctype="multipart/form-data">
<div class="col-md-3">
<br />
<label>Add More Data</label>
</div>
<div class="col-md-4">
<input type="file" name="employee_file" style="margin-top:15px;" accept=".csv"/>
</div>
<div class="col-md-5">
<input type="submit" name="upload" id="upload" value="Upload" style="margin-top:10px;" class="btn btn-info" />
</div>
<div style="clear:both"></div>
</form>
<br /><br /><br />
<div class="table-responsive" id="employee_table">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="25%">Name</th>
<th width="35%">Address</th>
<th width="10%">Gender</th>
<th width="20%">Designation</th>
<th width="5%">Age</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["address"]; ?></td>
<td><?php echo $row["gender"]; ?></td>
<td><?php echo $row["designation"]; ?></td>
<td><?php echo $row["age"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#upload_csv').on("submit", function(e){
e.preventDefault(); //form will not submitted
$.ajax({
url:"import.php",
method:"POST",
data:new FormData(this),
contentType:false, // The content type used when sending data to the server.
cache:false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
if(data=='Error1')
{
alert("Invalid File");
}
else if(data == "Error2")
{
alert("Please Select File");
}
else if(data != 'Error1' && data != 'Error2')
{
$('#employee_table').html(data);
alert("Data Import Successfully");
}
}
})
});
});
</script>
and here is for import.php
<?php
if(!empty($_FILES["employee_file"]["name"]))
{
$connect = mysqli_connect("localhost", "root", "", "db");
$output = '';
$allowed_ext = array("csv");
$tmp = explode(".", $_FILES["employee_file"]["name"]);
$extension = end($tmp);
if(in_array($extension, $allowed_ext))
{
$file_data = fopen($_FILES["employee_file"]["tmp_name"], 'r');
fgetcsv($file_data);
while($row = fgetcsv($file_data))
{
$id = mysqli_real_escape_string($connect, $row[0]);
$name = mysqli_real_escape_string($connect, $row[1]);
$address = mysqli_real_escape_string($connect, $row[2]);
$gender = mysqli_real_escape_string($connect, $row[3]);
$designation = mysqli_real_escape_string($connect, $row[4]);
$age = mysqli_real_escape_string($connect, $row[5]);
$query = "
INSERT INTO tbl_employee
(id,name, address, gender, designation, age)
VALUES ('$id','$name', '$address', '$gender', '$designation', '$age')
";
mysqli_query($connect, $query);
}
$select = "SELECT * FROM tbl_employee ORDER BY id DESC";
$result = mysqli_query($connect, $select);
$output .= '
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="25%">Name</th>
<th width="35%">Address</th>
<th width="10%">Gender</th>
<th width="20%">Designation</th>
<th width="5%">Age</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["designation"].'</td>
<td>'.$row["age"].'</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
else
{
echo 'Error1';
}
}
else
{
echo "Error2";
}
?>
i put all the code so that every one can try it too.
Thanks for answer

Problems with Ajax when adding items to my shopping Cart PHP

I just started to learn how to program and I have been having issues with ajax when it comes to adding items to my cart. Everything is fine when it comes to adding items, its the ajax that is not working and my page constantly keeps refreshing. For the code since there is a lot of it I will put the things I think are the most important.
Index.php
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title></title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.add_to_cart', function(){
var product_id = $(this).attr("id");
var product_name = $('#name'+product_id+'').val();
var product_price = $('#price'+product_id+'').val();
var product_quantity = $('#quantity'+product_id).val();
if(product_quantity > 0)
{
$.ajax({
url:"index.php",
method:"POST",
data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity},
success:function(data)
{
alert("Item has been Added into Cart");
}
});
}
else
{
alert("lease Enter Number of Quantity");
}
});
});
</script>
</head>
<body>
<header>
<?php
include_once'widget/header.php';
if (isset($_SESSION['u_id'])) {
include_once"include/addcart.php";
include_once "widget/shoppingcart.php";
}
?>
</header>
<main>
<div class="item-container">
<?php
$item = mysqli_query($db,"SELECT * FROM itemlist ORDER BY title");
include_once 'widget/container.php';
?>
</div>
</main>
Addcart.php
<?php
$row_ids = array();
//session_destroy();
//check if Add to Cart button has been submitted
if(filter_input(INPUT_POST, 'add_to_cart')){
if(isset($_SESSION['shopping_cart'])){
//keep track of how mnay products are in the shopping cart
$count = count($_SESSION['shopping_cart']);
//create sequantial array for matching array keys to products id's
$row_ids = array_column($_SESSION['shopping_cart'], 'id');
if (!in_array(filter_input(INPUT_POST, 'id'), $row_ids)){
$_SESSION['shopping_cart'][$count] = array
(
'id' => filter_input(INPUT_POST, 'id'),
'name' => filter_input(INPUT_POST, 'name'),
'price' => filter_input(INPUT_POST, 'price'),
'quantity' => filter_input(INPUT_POST, 'quantity')
);
// header("Location:index.php?addedtocart");
}
else { //product already exists, increase quantity
//match array key to id of the product being added to the cart
for ($i = 0; $i < count($row_ids); $i++){
if ($row_ids[$i] == filter_input(INPUT_POST, 'id')){
//add item quantity to the existing product in the array
$_SESSION['shopping_cart'][$i]['quantity'] += filter_input(INPUT_POST, 'quantity');
// header("Location:index.php?multtocart");
}
}
}
}
else { //if shopping cart doesn't exist, create first product with array key 0
//create array using submitted form data, start from key 0 and fill it with values
$_SESSION['shopping_cart'][0] = array
(
'id' => filter_input(INPUT_POST, 'id'),
'name' => filter_input(INPUT_POST, 'name'),
'price' => filter_input(INPUT_POST, 'price'),
'quantity' => filter_input(INPUT_POST, 'quantity')
);
}
}
if (filter_input(INPUT_POST, 'delete')) {
//loop thru intil products in shop cart == variable
foreach ($_SESSION['shopping_cart'] as $key => $row) {
if ($row['id'] == filter_input(INPUT_POST, 'id')) {
unset($_SESSION['shopping_cart'][$key]);
}
}
$_SESSION['shopping_cart'] =array_values($_SESSION['shopping_cart']);
}
?>
Shoppingcart.php
<div class="cart-container" align="right">
<div class="table-responsive">
<table class="table">
<table class="table">
<tr><th colspan="5"><h5>Order Details</h5></th></tr>
<tr>
<th width="40%">Product Name</th>
<th width="10%">Quantity</th>
<th width="20%">Price</th>
<th width="15%">Total</th>
<th width="5%">Action</th>
</tr>
<?php
if(!empty($_SESSION['shopping_cart'])):
$total = 0;
foreach($_SESSION['shopping_cart'] as $key => $product):
?>
<tr>
<td><?php echo $product['name']; ?></td>
<td><?php echo $product['quantity']; ?></td>
<td>$ <?php echo $product['price']; ?></td>
<td>$ <?php echo number_format($product['quantity'] * $product['price'], 2); ?></td>
<td>
<form method="post">
<input class="delete" type="submit" name="delete" value="Delete">
<input type="hidden" name="id" value="<?php echo $product['id']; ?>">
</form>
</td>
</tr>
<?php
$total = $total + ($product['quantity'] * $product['price']);
endforeach;
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<tr>
<!-- Show checkout button only if the shopping cart is not empty -->
<td colspan="5">
<?php
if (isset($_SESSION['shopping_cart'])):
if (count($_SESSION['shopping_cart']) > 0):
?>
Checkout
<?php endif; endif; ?>
</td>
</tr>
<?php
endif;
?>
</table>
</div>
</div>
Container.php
<?php
while ($row = mysqli_fetch_assoc($item)) {
?>
<div class='item-box'>
<img class='item_img' src="itemimg/<?php echo $row['img']; ?>"><figcaption><?php echo $row['title']; ?></ficgcaption>
<form method="post" class="add-form">
<div class='input-group xs-2'>
<input class="form-control" type="text" id="quantity<?php echo $row['id'] ?>" name="quantity" value="1">
<input class="btn btn-outline-primary btn-sm add-btns add_to_cart" type="submit" id="<?php echo $row['id'] ?>" name="add_to_cart" value="Add To Cart">
</div>
<input type="hidden" id="name<?php echo $row['id'] ?>" name="name" value="<?php echo $row['title'] ?>">
<input type="hidden" id="price<?php echo $row['id'] ?>" name="price" value="<?php echo $row['price']; ?>">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
</div>
</form>
<?php
}
?>
Your page will refresh because you are not telling your form to not submit by the default method (which is to reload the page as a POST). To stop the page from reloading and let ajax do the submission, you need to inject the event and then use preventDefault():
$(document).on('click', '.add_to_cart', function(e){
// This will stop the form from submitting and allow the rest of the
// ajax to continue working. If you don't have this, you will immediately
// submit the form which negates the use of ajax
e.preventDefault();

How To Fix This JavaScript Function?

I want to add confirm box by using JavaScript. So, here is the code that I have used. When I click on the Delete button, it shows me a Confirmation message and when I click Ok, it doesn't delete my row.
What is wrong with this? How can I fix this?
Here is the Index Page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Bootstrap core CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row"> <!-- Start Of The Row Class -->
<div class="col-md-8 col-sm-4 hero-feature"> <!-- Start Of The Col Class -->
<br><br>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include('ksdb.php');
// get results from database
$result = mysql_query("SELECT * FROM academic")
or die(mysql_error());
?>
<table class='table table-bordered'>
<tr class='danger'>
<th>ID</th>
<th>Name</th>
<th>Username</th>
</tr>
<?php
// display data in table
while($row = mysql_fetch_array( $result )) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><a href="AdminChangePw.php?id=<?php echo $row['id']; ?>" alt="edit" >Change</a></td>
<td><a href="AdminEdit.php?id=<?php echo $row['id']; ?>" alt="edit" >Edit</a></td>
<td><input type="button" onClick="deleteme(<?php echo $row['id']; ?>)" name="Delete" value="Delete"></td>
</tr>
<script language="javascript">
function deleteme(delid)
{
if(confirm("Do you want Delete!")){
window.location="AdminDel.php?id=' +id+'";
return true;
}
}
</script>
<?php
}
?>
</table>
</div> <!-- End Of The Col Class -->
</div> <!-- End Of The Row Class -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></script>
</body>
</html>
Change the id to 'delid'. You are calling the function as deleteme(delid).
So You Must use delid, instead of id.
function deleteme(delid)
{
if(confirm("Do you want Delete!")){
window.location.href="AdminDel.php?id="+delid; /*Change id to 'delid'*/
return true;
}
}
Use
window.location.href
Instead of window.location
There are a couple of problems with your function:
function deleteme(delid) {
if(confirm("Do you want Delete!")){
window.location="AdminDel.php?id='+id+'";// this should be delid, also bad quotes, also you want to set the href, not the location
return true;
}
}
Fixed:
function deleteme(delid) {
if(confirm("Do you want Delete!")){
window.location.href="AdminDel.php?id=" + delid;
return true;
}
}

Print my table using javascript

Can anyone help me with this? I just want to print this table using javascript print mode. But how? Using also the print view in the web style. I really appreciate any help. Thank you in advance. :)
Here's my code.
<?php
if(isset($_POST['search'])) {
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM dailytimerecord WHERE CONCAT(Dtrec_ID, TimeIn, TimeOut) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
} else {
$query = "SELECT * FROM dailytimerecord";
$search_result = filterTable($query);
}
function filterTable($query) {
$connect = mysqli_connect("localhost", "root", "", "alqdb");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td {
border: 1px solid black;
}
</style>
</head>
<body>
<form method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<input type="button" name="print" value="Print"><br><br>
<table>
<tr>
<th>Name</th>
<th>Dtrec_ID</th>
<th>Date</th>
<th>Time In</th>
<th>Time Out</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td></td>
<td><?php echo $row['Dtrec_ID'];?></td>
<td><?php echo date("F j, Y", strtotime($row['TimeIn']));?></td>
<td><?php echo date("h:i, A", strtotime($row['TimeIn']))?></td>
<td><?php echo date("h:i, A", strtotime($row['TimeOut']));?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>

Categories

Resources