I have a webpage (php) that fetches data from mysql as in the figure
I managed to make it refresh but it reloads the whole page. But I just want it to refresh the database every second without reloading the whole page or a button. I understand that I have to use AJAX and JQuery, but I didn't understand how. Here is my php code for the two php files fetch.php and index.php.
If any body knows how that would be done I much appreciate it!
<?php
//fetch.php
$connect = mysqli_connect("localhost", "sid", "", "python");
$columns = array('timestamp', 'message', 'topic', 'start', 'End');
$query = "SELECT * FROM messages WHERE ";
if($_POST["is_date_search"] == "yes")
{
$query .= 'timestamp BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(message LIKE "%'.$_POST["search"]["value"].'%"
OR topic LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'
';
}
else
{
$query .= 'ORDER BY timestamp DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = $row["timestamp"];
$sub_array[] = $row["topic"];
$sub_array[] = $row["message"];
$sub_array[] = $row["start"];
$sub_array[] = $row["End"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM messages";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<!-- <meta http-equiv="refresh" content="10"> -->
<title> Automated System</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<style>
body
{
margin:0;
padding:0;
background-color:#f1f1f1;
}
.box
{
width:1270px;
padding:20px;
background-color:#fff;
border:1px solid #ccc;
border-radius:5px;
margin-top:25px;
}
</style>
</head>
<body>
<div class="container box">
<h1 align="center"> Automated System</h1>
<br />
<form method="post" action="export.php" align="center">
<input type="submit" name="export" value="CSV Export" class="btn btn-success" />
</form>
<br />
<div class="table-responsive">
<br />
<div class="row">
<div class="input-daterange">
<div class="col-md-4">
<input type="text" name="start_date" id="start_date" class="form-control" />
</div>
<div class="col-md-4">
<input type="text" name="end_date" id="end_date" class="form-control" />
</div>
</div>
<div class="col-md-4">
<input type="button" name="search" id="search" value="Search" class="btn btn-info" />
</div>
</div>
<br />
<table id="order_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Error Reported </th>
<th>Board No.</th>
<th>Status</th>
<th>Repairing Started</th>
<th>Finished Repairing</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#order_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
}
}
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#order_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
}
else
{
alert("Both Date is Required");
}
});
});
</script>
Related
Everthing is working I've tested it, my only problem is that how to transfer into Codeigniter.. please someone help and explain if can.. I have to add this on my school project but in Codeigniter framework. I'm newbie on Codeigniter and I want to learn more.
This is my "print.php"
<?php
require('fpdf/fpdf.php');
if(isset($_POST["from_date"], $_POST["to_date"]))
{
$connect = mysqli_connect("localhost", "root", "", "datedate");
$output = '';
$query = "SELECT * FROM tbl_order WHERE order_date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."' ";
$result = mysqli_query($connect, $query);
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','',10);
$pdf->Cell(50,10,'Date:'.date('d-m-Y').'',0,"R");
$pdf->Ln(15);
$pdf->SetFont('Arial','B',16);
$pdf->Cell(0,10,'USERS',1,1,"C");
$pdf->SetFont('Arial','B',12);
$pdf->Cell(10,8,'No.',1);
$pdf->Cell(45,8,'First Name',1);
$pdf->Cell(45,8,'Middle Name',1);
$pdf->Cell(45,8,'Last Name',1);
$pdf->Cell(45,8,'Birth Date',1);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result)){
$no=$no+1;
$pdf->Ln(8);
$pdf->SetFont('Arial','',12);
$pdf->Cell(10,8,$no,1);
$pdf->Cell(45,8,$row['order_customer_name'],1);
$pdf->Cell(45,8,$row['order_item'],1,0,"C");
$pdf->Cell(45,8,$row['order_value'],1);
$pdf->Cell(45,8,$row['order_date'],1);
}
}
}
$pdf->Output();
?>
this is my "index.php"
<?php
$connect = mysqli_connect("localhost", "root", "", "datedate");
$query = "SELECT * FROM tbl_order ORDER BY order_id asc";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>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:"print.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>
I think your code is currently in pure PHP, and you want to code it in CodeIgniter, right?
If so, please take a look at it's document. Or sample here: This link
I suggest your code will like this:
In models/order.php
Class Order {
public function detail($id) {
// Get and return your data here
}
}
In controllers/index.php
Class IndexController {
public function index() {
// load model here
$data = ... // call to Order->detail
// Return view here
}
}
In views/index.php
// Render your view, form here
In controllers/print.php
Class Print {
public function index() {
// Do your code after submit here
}
}
Hope this can help you.
I just want to share my details to another php file using POST with Ajax, in my code the post value not initiated to share,
Here is my code :
<?php
include('database_connection.php');
if(isset($_POST["action"]))
{
// some logic
// some logic
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<div class="col-sm-3 col-lg-4 col-md-3">
<div style="border:1px solid #ccc; border-radius:5px; padding:10px; margin-bottom:16px; height:300px;">
<audio controls controlsList="nodownload" style="padding: 10px 10px 10px 10px;margin-left: -21px;">
<source src="audio_sample/'. $row['voice_audio_file'] .'" alt="" class="img-responsive">
</audio>
<p align="center"><strong> '. $row['voice_name'] .'</strong></p>
<p style="font-size: 12px;">
Voice Id : '. $row['voice_id'].' <br />
Voice Name : '. $row['voice_name'].' <br />
Gender : '. $row['voice_gender'].' <br />
Genres : '. $row['voice_genres'].' <br />
Voice Modulation : '. $row['voice_voice_modulation'].' <br />
Languages : '. $row['voice_languages'].' <br />
Jingle Moods : '. $row['voice_jingle_moods'].' <br />
Ivr : '. $row['voice_ivr'].' <br /> </p>
<button type="button" class="btn btn-primary" style="padding: 5px 83px 5px 83px;
"data-voice-id="'.$row["voice_id"].'
" data-voice-name="'.$row["voice_name"].'
"data-voice-id="'.$row["voice_gender"].'">Add to Playlist</button>
</div>
</div>
';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
?>
<script>
$('.btn').on('click',function() {
var voice_id = $(this).data("voice_id");
var voice_name = $(this).data("voice_name");
var voice_gender = $(this).data("voice_gender");
$.ajax({
method : "POST",
url : "manage_cart.php",
datatype : "text",
data :
{
voice_id: voice_id, voice_name: voice_name, voice_gender: voice_gender
},
success: function(data)
{
// console.log(data);
console.log('success',data);
}
});
});
</script>
I want to share voice_id, voice_name, voice_gender to manage_cart.php,
my manage_cart.php file,
<?php
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$voice_id = '';
$voice_name = '';
$voice_gender = '';
if(isset($_POST['voice_id']) && isset($_POST['voice_name']) && isset($_POST['voice_gender']) )
{
$voice_id = $_POST['voice_id'];
$voice_name = $_POST['voice_name'];
$voice_name = $_POST['voice_gender'];
}
echo $voice_id ."&". $voice_name ."&". $voice_gender;
?>
Here my post value not pass to manage_cart.php.
How can i solve the issue?
Your button attribute doesn't have data-voice-gender. There are duplicate data-voice-id, and use the same style of variable like data-voice-id but in javascript you're using $(this).data('voice_id')
what happen in the code is that everytime i choose in multiple drop down it fetch the data what i want to happen is to click the button first then it will fetch the data...... thank u guys got the code in here https://www.webslesson.info/2018/05/ajax-live-data-search-using-multi-select-dropdown-in-php.html
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=db", "root", "");
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Live Data Search using Multi Select Dropdown in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/bootstrap-select.min.css" rel="stylesheet" />
<script src="js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Multi Select Dropdown in PHP</h2><br />
<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<input type="hidden" name="hidden_country" id="hidden_country" />
<div style="clear:both"></div>
<br />
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query='')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('tbody').html(data);
}
})
}
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
var query = $('#hidden_country').val();
load_data(query);
});
});
</script>
fetch.php
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=dbattendancelibrary", "root", "");
if($_POST["query"] != '')
{
$search_array = explode(",", $_POST["query"]);
$search_text = "'" . implode("', '", $search_array) . "'";
$query = "
SELECT * FROM tbl_customer
WHERE Country IN (".$search_text.")
ORDER BY CustomerID DESC
";
}
else
{
$query = "SELECT * FROM tbl_customer ORDER BY CustomerID DESC";
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<tr>
<td>'.$row["CustomerName"].'</td>
<td>'.$row["Address"].'</td>
<td>'.$row["City"].'</td>
<td>'.$row["PostalCode"].'</td>
<td>'.$row["Country"].'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5" align="center">No Data Found</td>
</tr>
';
}
echo $output;
?>
It fires an ajax call because of this code:
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
var query = $('#hidden_country').val();
load_data(query);
});
If you want to fire when clicking on a button, you will need to put in HTML for the button first. Then use the id for load_data event, for example you will have a button called '#btn_search':
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
});
$('#btn_search').click(function(e){
e.preventDefault();
var query = $('#hidden_country').val();
load_data(query);
});
Your full HTML above becomes like this:
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=db", "root", "");
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Live Data Search using Multi Select Dropdown in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/bootstrap-select.min.css" rel="stylesheet" />
<script src="js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Multi Select Dropdown in PHP</h2><br />
<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<input id="btn_search" type="button" value="Filter" />
<input type="hidden" name="hidden_country" id="hidden_country" />
<div style="clear:both"></div>
<br />
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query='')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('tbody').html(data);
}
})
}
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
});
$('#btn_search').click(function(e){
e.preventDefault();
var query = $('#hidden_country').val();
load_data(query);
});
});
</script>
I have a shopping cart that displays the different products the customer has selected to purchase. I need to INSERT each product selected as a single row with the same customer_id in the 'order_details' table.
Screenshot
code
<?php
session_start();
#mysql_connect("localhost","root","") or die("Could not connect to database");
#mysql_select_db("bookstore") or die("Could not select database");
$connection = mysqli_connect('localhost', 'root', '', 'bookstore');
include("admin/php/myFunctions.php");
$customer = $_SESSION['id_login'];
$order = $_SESSION['id_login'];
if(!empty($_GET['prodid'])){
$pid = $_GET['prodid'];
$wasFound = false;
$i = 0;
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$_SESSION["cart_array"]=array(0=>array("productID"=>$pid,"quantity"=>1));
}else{
foreach($_SESSION["cart_array"] as $each_product){
$i++;
while(list($key,$value)=each($each_product)){
if($key=="productID" && $value==$pid){
array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$pid,"quantity"=>$each_product ['quantity']+1)));
$wasFound=true;
}
}
}
if($wasFound==false){
array_push($_SESSION["cart_array"],array("productID"=>$pid,"quantity"=>1));
}
}
header("location:shoppingcart.php");
exit();
}
//-------------------------------------------------------------------------------------------------
#$submit = $_POST['btnUpdate'];
if($submit == "Update"){
$x = 0;
//echo $_POST['txtQuan2'];
//echo $_POST['txtHoldProdId0'];
foreach($_SESSION["cart_array"] as $each_product){
$i++;
$quantity = $_POST['txtQuan'.$x];
$prodStock = $_POST['txtHoldQuan'.$x];
$prodAdjustId = $_POST['txtHoldProdId'.$x++];
if($quantity<1){ $quantity = 1; }
if($quantity>$prodStock){ $quantity = $prodStock; }
while(list($key,$value)=each($each_product)){
array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$prodAdjustId,"quantity"=>$quantity)));
}
}
}
//-------------------------------------------------------------------------------------------------
if(!empty($_GET['cid']) || isset($_GET['cid'])){
$removeKey = $_GET['cid'];
if(count($_SESSION["cart_array"])<=1){
unset($_SESSION["cart_array"]);
}else{
unset($_SESSION["cart_array"]["$removeKey"]);
sort($_SESSION["cart_array"]);
}
}
//-------------------------------------------------------------------------------------------------
$cartTitle = "";
$cartOutput = "";
$cartTotal = "";
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartOutput="<h2 align='center'> Your shopping cart is empty </h2>";
}else{
$x = 0;
$cartTitle .= '<form name="shoppingcart_form" action="shoppingcart.php" method="post" /><table width="700px" cellspacing="0" cellpadding="5">
<tr bgcolor="#CCCCCC">
<th width="220" align="left">Image </th>
<th width="140" align="left">Name </th>
<th width="100" align="center">Quantity </th>
<th width="60" align="center">Stock </th>
<th width="60" align="right">Price </th>
<th width="60" align="right">Total </th>
<th width="90"> </th></tr>';
#Values in here need to go into database "order_details" table
$i = 0;
foreach($_SESSION["cart_array"] as $each_product){
$product_id = $each_product['productID'];
$sql=mysql_query("select * from tblproduct where prod_id='$product_id' limit 1");
while($row=mysql_fetch_array($sql)){
$prodNo = $row["prod_no"];
$prodID = $row["prod_id"];
$prodName = $row["prod_name"];
$prodPrice = $row["prod_price"];
$prodQuan = $row["prod_quan"];
}
$pricetotal=$prodPrice*$each_product['quantity'];
$cartTotal= number_format($pricetotal+$cartTotal,2);
$cartOutput .= '<tr><td><img style="border: 2px solid;" src="images/product/'.$prodNo.'.jpg" width="150" height="120" /></td>
<td>'.$prodName.'</td>
<td align="center"><input type="hidden" name="txtHoldProdId'.$i.'" value="'.$prodID.'" /><input name="txtQuan'.$i.'" type="text" value="'.$each_product['quantity'].'" style="width: 40px; text-align: center" /> </td>
<td align="center"><input type="hidden" name="txtHoldQuan'.$i.'" value="'.$prodQuan.'" /> '.$prodQuan .' pcs</td>
<td align="right">R '.$prodPrice.'</td>
<td align="right">R '.$pricetotal.'</td>
<td align="center"> <img src="images/remove_x.gif" alt="remove" /><br />Remove </td></tr>';
}
$_SESSION['checkoutCartTotal'] = $cartTotal;
$cartOutput .= '<tr>
<td colspan="3" align="right" height="40px">Have you modified your basket? Please click here to <input class="btn_upd" type="submit" name="btnUpdate" value="Update" /> </td>
<td align="right" style="background:#ccc; font-weight:bold"> Total: </td>
<td colspan="2" align="left" style="background:#ccc; font-weight:bold;">R '.$cartTotal.' </td>
<td style="background:#ccc; font-weight:bold"> </td>
</tr>
</table>
<div style="float:right; width: 215px; margin-top: 20px;">
</form>
</div></form>';
}
//---------------------------------------------------
$cTotal = $_SESSION['checkoutCartTotal'];
#$cName = $_POST['cardName'];
#$cNumber = $_POST['cardNum'];
#$cAdress = $_POST['cusAddress'];
#$cCity = $_POST['cusCity'];
#$cEmail = $_POST['cusEmail'];
#$cPhone = $_POST['cusPhone'];
foreach($_SESSION["cart_array"] as $each_product){
$product_id = $each_product['productID'];
$sql=mysql_query("select * from tblproduct where prod_id='$product_id' limit 1");
while($row=mysql_fetch_array($sql)){
$ProdID = $row["prod_id"];
$prodPrice = $row["prod_price"];
$ProdQuan = $row["prod_quan"];
}
$sqlinsert2 = ("INSERT INTO order_details (`order_id`, `prod_id`, `cus_id`, `quantity`, `price_per_unit`) VALUES ('$order', '$ProdID', '$customer', '$ProdQuan', '$prodPrice')");
}
$sqlinsert = "INSERT INTO tbl_order (`total_price`, `credit_card_number`, `fname`, `email`, `address`, `phone`, `city`,`date_ordered`) VALUES ('$cTotal','$cNumber', '$cName', '$cEmail', '$cAdress', '$cPhone', '$cCity',now())";
if (!mysqli_query($connection, $sqlinsert)) {
die(mysqli_error($connection));
}
$newrecord = "Thank you for making your purchase!";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Great Selling Book Store</title>
<link href="css/slider.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<script language="javascript" type="text/javascript">
function clearText(field)
{
if (field.defaultValue == field.value) field.value = '';
else if (field.value == '') field.value = field.defaultValue;
}
</script>
</head>
<body id="subpage">
<div id="main_wrapper">
<div id="main_header">
<div id="site_title"><h1>Great Selling book Store</h1></div>
<div id="header_right">
<div id="main_search">
<form action="products.php" method="get" name="search_form">
<input type="text" value="Search" name="keyword" onfocus="clearText(this)" onblur="clearText(this)" class="txt_field" />
<input type="submit" name="Search" value="" alt="Search" id="searchbutton" title="Search" class="sub_btn" />
</form>
</div>
</div> <!-- END -->
</div> <!-- END of header -->
<div id="main_menu" class="ddsmoothmenu">
<ul>
<li>Home</li>
<li>Books</li>
<li><a class="selected" href="shoppingcart.php">Cart</a></li>
<li>About</li>
</ul>
<br style="clear: left" />
</div> <!-- end of menu -->
<div class="cleaner h20"></div>
<div id="main_top"></div>
<div id="main">
<div id="sidebar">
<h3>Categories</h3>
<ul class="sidebar_menu">
<li>Children</li>
<li>Horror</li>
<li>Thriller</li>
</ul>
</div> <!-- END of sidebar -->
<div id="content">
<?php echo $cartTitle; ?>
<?php echo $cartOutput; ?>
</div> <!-- end of content -->
<div class="cleaner">
<form method ="post" action="shoppingcart.php">
<input type="hidden" name="submitted" value= "true" />
<fieldset>
<legend>Customer Checkout</legend>
<label>Enter your name as it is on the credit card: <input type="text" name="cardName"></label>
<label>Card Number: <input type="text" name="cardNum"></label>
<label>Adress: <input type="text" name="cusAddress"></label>
<label>City: <input type="text" name="cusCity"></label>
<label>Email: <input type="text" name="cusEmail"></label>
<label>Please, specify your reachable phone number. YOU MAY BE GIVEN A CALL TO VERIFY AND COMPLETE THE ORDER: <input type="text" name="cusPhone"></label>
</fieldset>
<div class="cleaner h50"></div>
<td> <input type="submit" class="more" value="Checkout!"></td>
</form>
</div>
</div> <!-- END of main -->
<?php
echo #$newrecord;
?>
<div id="main_footer">
<div class="cleaner h40"></div>
<center>
Copyright © 2048 DigitalNinja
</center>
</div> <!-- END of footer -->
</div>
<script type='text/javascript' src='js/logging.js'></script>
</body>
</html>
Below example for multiple inserts in a single query and its faster,
INSERT INTO example
(example_id, name, value, other_value)
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
Your Code with multiple insert option:
foreach($_SESSION["cart_array"] as $each_product){
$product_id = $each_product['productID'];
$sql=mysql_query("select * from tblproduct where prod_id='$product_id' limit 1");
while($row=mysql_fetch_array($sql)){
$Prods .= '('.$order.
','.$row["prod_id"].
','. $order.
','.$row["prod_quan"].
','.$row["prod_price"].
'),';//if text: ',"'.$row["prod_quan"].'"),';
}
$Prods = rtrim($Prods, ',');// this is to remove last comma from multiple inserts
$sqlinsert2 = ("INSERT INTO order_details (`order_id`, `prod_id`, `cus_id`, `quantity`, `price_per_unit`) VALUES $Prods");
mysql_query($sqlinsert2);
}
NOTE: you are not running mysql_query of insert, so it's not inserting data into the database.
WARNING: You should use mysqli with parameterized queries and you have created a severe SQL injection bug
I just want to ask your help about my table query, everytime when button is click, a new table will display. Instead of only a row will update to a table, an entire table display behind is the old table. Please help me review my code.Thanks
demo.insert.php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = 'thartpc';
$dbDatabase = 'hospital';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
$sql_check = mysql_query("SELECT * FROM messages order by med_id desc");
if(isSet($_POST['content2'])){
$content2=$_POST['content2'];
$content3=$_POST['content3'];
mysql_query("insert into messages(medname, quantity) values ('$content2','$content3')");
$sql_in= mysql_query("SELECT * FROM messages order by med_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<?php
require_once 'config.php';
$query = mysql_query("SELECT * FROM messages order by med_id desc") or die ("could not search");
$count = mysql_num_rows($query);
?>
<div class="container">
<div class="panel panel-info">
<div class="panel-heading" class="panel-title">
<h7>Name</h7>
</div>
<div class="panel-body" style="padding-top:30px">
<?php
echo "
<table class='table table-hover';>
<tr>
<td style='border:1px solid; color:gray' align='center'> ID</td>
<td style='border:1px solid; color:gray' align='center'>Name</td>
<td style='border:1px solid; color:gray' align='center'>Quantity</td>
</tr>";
while($row = mysql_fetch_array($query)){
echo "
<tr>
<td style='border:1px solid; color:gray' align='center'>".$row['med_id']." </td>
<td style='border:1px solid; color:gray' align='center'>".$row['medname']." </td>
<td style='border:1px solid; color:gray' align='center'>".$row['quantity']."</td>
</tr> ";
}
echo " </table>";
?>
</div>
</div>
</div>
inserting.php
<?php
session_start();
if(isset($_POST['search'])){
$globalpid = $_POST['search'];
$_SESSION['search'] = "$globalpid";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap- theme.min.css">
<title>Insert Record with jQuery and Ajax</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#v").click(function(){
var element = $(this);
var test2 = $("#content2").val();
var test3 = $("#content3").val();
var dataString = 'content2='+ test2+'&content3='+ test3;
if(test2==''){
alert("Please Enter Some Text");
}else{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content2').value='';
$("#flash").hide();
}
});
}
return false;
});
});
</script>
</head>
<body>
<?php
require_once 'pharmacyheader.php';
require_once 'pharmacysearch.php';
require_once 'patientquery.php';
?>
<div class="container">
<form method="post" name="form" action="">
<div class="col-md-6">
<div class="panel panel-info">
<div class="panel-heading"><h7>Name A - F</h7></div>
<div class="panel-body">
<select class="form-control" id="content2" name="content2">
<option id="0" style="width:100px"></option>
<?php
require_once 'config.php';
$medicine = mysql_query("SELECT * FROM medicine");
while ($row = mysql_fetch_array($medicine)) {
echo '<option id="' . $row['medicinename'] . '"';
echo ' value="' . $row['medicinename'] . '"';
if($row['brandid'] == $row['medicinename']) {
echo ' selected="selected"';
}
echo '>';
echo $row['medicinename'];
echo '</option>';
}
?>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-info">
<div class="panel-heading"><h7>Quantity</h7></div>
<div class="panel-body">
<select class="form-control" id="content3" name="content3">
<option id="0" style="width:100px"></option>
<?php
require_once 'config.php';
$quantity = mysql_query("SELECT * FROM quantity");
while ($row = mysql_fetch_array($quantity)) {
echo '<option id="' . $row['quantityname'] . '"';
echo ' value="' . $row['quantityname'] . '"';
if($row['quantityid'] == $row['quantityname']) {
echo ' selected="selected"';
}
echo '>';
echo $row['quantityname'];
echo '</option>';
}
?>
</select>
</div>
</div>
</div>
<div class="row"><br />
<div class="col-md-1">
<input type="submit" value="Add" id="v" name="submit" class="form-control" />
</div>
</div>
</form>
</div>
<div style="height:7px"></div>
<div id="flash" align="left" ></div>
<div id="display" align="left"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"> </script>
<script src="typeahead.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"> </script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.min.js"></script>
<script type="text/javascript" src="jquery.min.js"></script>
</body>
</html>
OK, so when looking at your code I can see this :
You use ajax to retrieve a table with content
You have a .display element which is supposed to receive the ajax data
SO, each time you call your .ajax, you receive a new complete table in return (check your demo_insert.php). To put the new content in the ".display" item, you use jquery ".after" (you should check how it works btw http://api.jquery.com/after/ )
.after is supposed to ADD something AFTER something else. So, it sounds logical that your ajax return (complete table) is added AFTER ".display" since you ask jquery to do that.
What you should do is just REPLACE your ".display" content with the .ajax response...
$('#display').html(html);
for example, or something like this...
Look at the below code,
echo "<table class='table table-hover';>
<tr>
<td style='border:1px solid; color:gray' align='center'> ID</td>
<td style='border:1px solid; color:gray' align='center'>Name</td>
<td style='border:1px solid; color:gray' align='center'>Quantity</td>
</tr>";
while($row = mysql_fetch_array($query))
{
echo "
<tr>
<td style='border:1px solid; color:gray' align='center'>".$row['med_id']." </td>
<td style='border:1px solid; color:gray' align='center'>".$row['medname']." </td>
<td style='border:1px solid; color:gray' align='center'>".$row['quantity']."</td>
</tr> ";
}
echo "</table>";
I think this code is executed each and every time ajax call is made.
The butter solution is that put "table" tag where you made ajax call and only append tr content from ajax response.
This may help you out.
Let me know if you have any query
Thanks