I'm not getting values from session variable set for results - php

I have created the following pages.
1. questions.php
2. functions.php
3. result.php
i have set the values of session variables on page function.php when the question form on questions.php form is submitted the functions.php code runs and the i have echo the values of session variables on result.php page. but i'm unable to get the session values result.the sessions values are resulting empty .anyone help please.
functions.php
if(isset($_POST['question_form']))
{
global $conn;
if (!isset($_SESSION['result'])) {
$result = 0;
$_SESSION['result'] = 0;
}
if (!isset($_SESSION['attempted'])) {
$attempted = 0;
$_SESSION['attempted'] = 0;
}
$resArray = array();
$resArray['message'] = '';
$resArray['status'] = '';
$no = $_POST['no'];
$postedAnswer = $_POST['answer_'.$no];
$question_id = $_POST['question_id'];
$subject_id = $_POST['subject_id'];
$sql = "SELECT True_answer FROM question WHERE QuestionId = '$question_id' AND SubjectId = '$subject_id'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$True_answer = $row['True_answer'];
if($postedAnswer === $True_answer)
{
$result = $_SESSION['result'];
$result++;
$_SESSION['result'] = $result;
}
$attempted = $_SESSION['attempted'];
$attempted++;
$_SESSION['attempted'] = $attempted;
$resArray['status'] = true;
//$resArray['q_id'] = $no;
$resArray['message'] = 'Submitted Successfully';
echo json_encode($resArray);
exit();
}
=====questions.php========
<form action="includes/functions.php" id="question_form_<?php echo $j; ?>" >
<div class='container' >
<div class='row'>
<div class='col-lg-12'>
<div class='thumbnail'>
<p id="question_description">Q.<?php echo $i; ?><br><?php echo $row['QuestionDescription']; ?></p>
<div class="questions_options">
<label><input type="radio" id="btn_radio" name="answer_<?php echo $j; ?>" value="<?php echo $row['Option1']; ?>"><?php echo $row['Option1']; ?></input></label><br>
<label><input type="radio" id="btn_radio" name="answer_<?php echo $j; ?>" value="<?php echo $row['Option2']; ?>"><?php echo $row['Option2']; ?></input></label><br>
<label><input type="radio" id="btn_radio" name="answer_<?php echo $j; ?>" value="<?php echo $row['Option3']; ?>"><?php echo $row['Option3']; ?></input></label><br>
<label><input type="radio" id="btn_radio" name="answer_<?php echo $j; ?>" value="<?php echo $row['Option4']; ?>"><?php echo $row['Option4']; ?></input></label><br><br>
<input type="hidden" name="question_id" value="<?php echo $row['QuestionId'] ?>">
<input type="hidden" name="subject_id" value="<?php echo $row['SubjectId'] ?>">
<input type="hidden" name="question_form" value="question_form">
<input type="hidden" name="no" value="<?php echo $j; ?>">
<button class="btn btn-primary btn-sm" id="btn_submit">Submit<i class="glyphicon glyphicon-arrow-right" >
</i></button>
</div>
</div>
</div>
</div>
</div>
</form>
============result.php===============
<table class="table table-striped table-hover" id="result_table" >
<thead>
<tr>
<th style="text-align: center;">Total Questions</th>
<th style="text-align: center;">Attempted Questions</th>
<th style="text-align: center;">Total Marks</th>
<th style="text-align: center;">Obtained Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;"><?php echo $number_of_questions;?></td>
<td style="text-align: center;"><?php echo $_SESSION['attempted']; ?></td>
<td style="text-align: center;"><?php if(!isset($_SESSION['result']))
{
echo "empty";
}
else
{
echo $_SESSION['result'];
}
?></td>
<td style="text-align: center;"><?php echo $marks_obtained;?></td>
</tr>
</tbody>
</table>

Please start the session using session_start() function

Related

online quiz Question id not insert in to database

Hey Guys i am new here anyone help me ...my problem is that i am working on a online quiz exam with php and ajax ..problem is that i am inserting Question ID into database so anyone help me solve this problem ...i show you my codes..
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var stu_ans=$(this).val();
var stu_id ="<?php echo $_GET['sid'];?>";
var q_id = $('#qname').val();
$.ajax({
url:"insert1.php",
method:"POST",
data:{stu_ans:stu_ans, stu_id:stu_id,q_id:q_id},
success:function(data){
$('#result').html(data);
}
});
});
});
</script>
<script>
$('.cont').addClass('hide');
$('#question_splitter_1').removeClass('hide');
$(document).on('click','.next',function(){
last=parseInt($(this).attr('id')); console.log( last );
nex=last+1;
$('#question_splitter_'+last).addClass('hide');
$('#question_splitter_'+nex).removeClass('hide');
});
$(document).on('click','.previous',function(){
last=parseInt($(this).attr('id'));
pre=last-1;
$('#question_splitter_'+last).addClass('hide');
$('#question_splitter_'+pre).removeClass('hide');
});
</script>
<style>
input[type="radio"] {
-ms-transform: scale(1.5); /* IE 9 */
-webkit-transform: scale(1.5); /* Chrome, Safari, Opera */
transform: scale(1.5);
}
</style>
<div class="container-fluied">
<div class="col-xs-12">
<hr>
<form role="form" id='formid' method="post" action="result.php?s_id=<?php echo $_GET['sid'];?>">
<?php
$number_question = 1;
$row = mysqli_query( $con, "select * from question where subject_id='$category' ORDER BY RAND()");
$rowcount = mysqli_num_rows( $row );
$remainder = $rowcount/$number_question;
$i = 0;
$j = 1; $k = 1;
?>
<h4>Total Question:-<?php echo $rowcount;?></h4>
<?php while ( $result = mysqli_fetch_assoc($row) ) {
if ( $i == 0) echo "<div class='cont' id='question_splitter_$j'>";?>
<div id='question<?php echo $k;?>' >
<p class='questions' id="qname<?php echo $j;?>" style="font-size:20px;font-weight:bold;color:green"> (<?php echo $k?>).<?php echo $result['que'];?></p>
<input type="hidden" value="<?php echo $result['que'];?>" name="qname<?php echo $j;?>" id="qname">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>(A)<?php echo trim($result['o1']);?></td>
<td colspan="5"><input type="radio" value="<?php echo $result['o1'];?>" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'></td>
</tr>
<tr>
<td>(B)<?php echo $result['o2'];?>
</td>
<td colspan="5"><input type="radio" value="<?php echo $result['o2'];?>" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/></td>
</tr>
<tr>
<td>(C)<?php echo $result['o3'];?></td>
<td colspan="5"><input type="radio" value="<?php echo $result['o3'];?>" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
</td>
</tr>
<tr>
<td>(D)<?php echo $result['o4'];?></td>
<td colspan="5"><input type="radio" value="<?php echo $result['o4'];?>" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
</td>
</tr>
</tbody>
</table>
</div>
<input type="radio" checked='checked' style='display:none' value="5" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
<br/>
</div>
<?php
$i++;
if ( ( $remainder < 1 ) || ( $i == $number_question && $remainder == 1 ) ) {
echo "<button id='".$j."' class='next btn btn-success' type='submit'>Finish</button>";
echo "</div>";
} elseif ( $rowcount > $number_question ) {
if ( $j == 1 && $i == $number_question ) {
echo "<button id='".$j."' class='next btn btn-success' type='button'>Next</button>";
echo "</div>";
$i = 0;
$j++;
} elseif ( $k == $rowcount ) {
echo " <button id='".$j."' class='previous btn btn-success' type='button'>Previous</button>
<button id='".$j."' class='next btn btn-success' type='submit'>Finish</button>";
echo "</div>";
$i = 0;
$j++;
} elseif ( $j > 1 && $i == $number_question ) {
echo "<button id='".$j."' class='previous btn btn-success' type='button'>Previous</button>
<button id='".$j."' class='next btn btn-success' type='button' >Next</button>";
echo "</div>";
$i = 0;
$j++;
}
}
$k++;
} ?>
</form>
</div>
</div>
<?php
session_start();
include('db_connect.php');
include('db_connection.php');
$stu_id=$_SESSION['sid'];
echo $gender=$_POST['stu_ans'];
echo $que=$_POST['q_id'];
$q=mysqli_query($con,"SELECT * FROM question where id='$que'");
$ro=mysqli_fetch_array($q);
//$que=$ro['id'];
$date=date('d/m/y');
$right_ans=$ro['right_ans'];
////////////////////////Ajax Data Saved//////////////////////////////
$q1=mysqli_query($con,"SELECT * FROM student_ans where q_id='$que' AND stu_id='$stu_id'");
$ro1=mysqli_num_rows($q1);
if($ro1==''){
$sql = mysqli_query($con,"INSERT INTO student_ans(stu_ans,q_id,stu_id,date,right_ans) value('$gender','$que','$stu_id','$date','$right_ans')");
}else{
$sql1 = mysqli_query($con,"update student_ans set stu_ans='$gender' where q_id='$que' AND stu_id='$stu_id'");
}
?>
This code working like when i am click radio button so ajax fuction working and save the answer into database but i want that when inserting answer into database with answer insert Question ID

Shopping Cart only enters last item in Database not all of the data

I am having an issue with my shopping cart when I add three items only the last item enters into the database. I am not sure how to get all the items to insert into the database like 3 or 4. I have tried many different ways and still come up with nothing. I still have to also figure how to get subtotal and customer name to attach to the orders
Index.php
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["code"],array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["code"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
?>
<HTML>
<HEAD>
<TITLE>Simple PHP Shopping Cart</TITLE>
<link href="style.css" type="text/css" rel="stylesheet" />
</HEAD>
<BODY>
<div id="product-grid">
<div class="txt-heading">Products</div>
<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
?>
<div class="product-item">
<form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
<div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div>
<div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
<div><input type="text" name="quantity" value="1" size="2" /><input type="submit" value="Add to cart" class="btnAddAction" /></div>
</form>
</div>
<?php
}
}
?>
</div>
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart <a id="btnEmpty" href="index.php?action=empty">Empty Cart</a></div>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<form method="post" action="process_insert.php">
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th style="text-align:left;"><strong>Name</strong></th>
<th style="text-align:left;"><strong>Code</strong></th>
<th style="text-align:right;"><strong>Quantity</strong></th>
<th style="text-align:right;"><strong>Price</strong></th>
<th style="text-align:center;"><strong>Action</strong></th>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td style="text-align:left;border-bottom:#F0F0F0 1px solid;" ><input type="text" name="name" value="<?php echo $item["name"]; ?>"></td>
<td style="text-align:left;border-bottom:#F0F0F0 1px solid;"><input type="text" name="code" value="<?php echo $item["code"]; ?>"></td>
<td style="text-align:right;border-bottom:#F0F0F0 1px solid;"><input type="text" name="quantity" value="<?php echo $item["quantity"]; ?>"></td>
<td style="text-align:right;border-bottom:#F0F0F0 1px solid;"><input type="text" name="price" value="<?php echo $item["price"]; ?>"></td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">Remove Item</td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td colspan="5" align=right><strong>Total:</strong> <?php echo "$".$item_total; ?></td>
</tr>
</tbody>
</table>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
</div>
</BODY>
</HTML>
process_insert.php
<html>
<head>
<title></title>
</head>
<body>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "blog_samples";
$conn = mysqli_connect($serverName,$userName,$userPassword,$dbName);
$sql = "INSERT INTO order_table (name, code, quantity, price)
VALUES ('".$_POST["name"]."','".$_POST["code"]."'
,'".$_POST["quantity"]."','".$_POST["price"]."')";
$query = mysqli_query($conn,$sql);
if($query) {
echo "Record add successfully";
}
mysqli_close($conn);
?>
</body>
</html>
That's because your submit form doesnt support multiple fields.
You have to add a index to each inputs' name.
<?php
$i = 0;
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td style="text-align:left;border-bottom:#F0F0F0 1px solid;" ><input type="text" name="name[<?php echo $i; ?>]" value="<?php echo $item["name"]; ?>"></td>
<td style="text-align:left;border-bottom:#F0F0F0 1px solid;"><input type="text" name="code[<?php echo $i; ?>]" value="<?php echo $item["code"]; ?>"></td>
<td style="text-align:right;border-bottom:#F0F0F0 1px solid;"><input type="text" name="quantity[<?php echo $i; ?>]" value="<?php echo $item["quantity"]; ?>"></td>
<td style="text-align:right;border-bottom:#F0F0F0 1px solid;"><input type="text" name="price[<?php echo $i; ?>]" value="<?php echo $item["price"]; ?>"></td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">Remove Item</td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
$i++;
}
?>
process_insert.php
<html>
<head>
<title></title>
</head>
<body>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "blog_samples";
$conn = mysqli_connect($serverName,$userName,$userPassword,$dbName);
$rows_count = count($_POST["name"]);
for($i=0;$i<$rows_count;$i++){
// PREVENTING SQL INJECTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$name = mysqli_real_escape_string($conn,$_POST["name"][$i]);
$code = mysqli_real_escape_string($conn,$_POST["code"][$i]);
$quantity = intval($_POST["quantity"][$i]);
$price = mysqli_real_escape_string($conn,$_POST["price"][$i]);
$sql = "INSERT INTO order_table (name, code, quantity, price)
VALUES ('$name','$code','$quantity','$price')";
$query = mysqli_query($conn,$sql);
}
if(mysqli_affected_rows($conn)>0) {
echo "Record add successfully";
}
mysqli_close($conn);
?>
</body>
</html>

Very heavy wordpress plugin and customization

i have a wordpress website and with customization (cache/minify/database), is really quick in frontend, and in backend, with one exception. I use a plugin where it stores and retrieves players stats, carreers, teams etc.
When saving the team's match player's statistics, it needs 5 minutes to show the page reloaded with the data.
Also when retrieving for example team's season data, it also needs a lot of time to show them.
From what i ve seen, it is related with two of my files that do all the work. tournament_match.php, and functions.php. From hosting they said that it gets all tha database and thats why it is so slow
Here is the tournament_match file
<?php
global $wpdb;
global $msg;
$page = $_GET['page'];
$tournament_id = $_GET['tid'];
$match_id = $_GET['mid'];
$league_type = leagueengine_fetch_data_from_id($tournament_id,'league_type');
if(isset($_POST['home_team_bonus']) or isset($_POST['away_team_bonus'])) {
if(isset($_POST['save_tournament_match'])) { leagueengine_save_tournament_match($tournament_id,$match_id,$_POST['date_alt'],$_POST['time_alt'],$_POST['home_team_id'],$_POST['away_team_id'],$_POST['home_team_score'],$_POST['away_team_score'],$_POST['home_team_bonus'],$_POST['away_team_bonus']); }
} else {
if(isset($_POST['save_tournament_match'])) { leagueengine_save_tournament_match($tournament_id,$match_id,$_POST['date_alt'],$_POST['time_alt'],$_POST['home_team_id'],$_POST['away_team_id'],$_POST['home_team_score'],$_POST['away_team_score']); }
}
if(isset($_POST['save_attributes'])) { leagueengine_save_attribute_values('tournament_match',NULL,NULL,$match_id,NULL,NULL,$tournament_id); }
if(isset($_POST['add_event_to_match'])) { error_reporting(0); leagueengine_add_event_to_tournament_match($tournament_id,$match_id,$_POST['new_event_id'],$_POST['new_event_time'],$_POST['timeline_text'],$_POST['new_event_count'],$_POST['new_event_player_id']); error_reporting(1); }
if(isset($_POST['save_events'])) { leagueengine_save_event_times('tournament_match',$_POST['event_time_id'],$_POST['event_time'],$_POST['event_text']); }
if(isset($_POST['add_home_event_to_match'])){
error_reporting(0);
foreach($_POST as $key=>$val){
$val=intval($val);
if(is_int($val)&&$val>0){
$data=explode('-',$key);
$playerid=$data[1];
$eventid=$data[2];
leagueengine_add_event_to_tournament_match2($tournament_id,$match_id,$eventid,$_POST['new_event_time'],$_POST['timeline_text'],$val,$playerid);
}
}
error_reporting(1);
}
if(isset($_POST['add_away_event_to_match'])){
error_reporting(0);
foreach($_POST as $key=>$val){
$val=intval($val);
if(is_int($val)&&$val>0){
$data=explode('-',$key);
$playerid=$data[1];
$eventid=$data[2];
leagueengine_add_event_to_tournament_match2($tournament_id,$match_id,$eventid,$_POST['new_event_time'],$_POST['timeline_text'],$val,$playerid);
}
}
error_reporting(1);
}
if(isset($_POST['save_tournament_match_lineups'])) {
if(isset($_POST['homeplayers'])) { $homeplayers = $_POST['homeplayers']; } else { $homeplayers = ''; }
if(isset($_POST['awayplayers'])) { $awayplayers = $_POST['awayplayers']; } else { $awayplayers = ''; }
if(isset($_POST['homesubs'])) { $homesubs = $_POST['homesubs']; } else { $homesubs = ''; }
if(isset($_POST['awaysubs'])) { $awaysubs = $_POST['awaysubs']; } else { $awaysubs = ''; }
leagueengine_save_tournament_match_lineups($tournament_id,$match_id,$homeplayers,$awayplayers,$homesubs,$awaysubs);
}
if(isset($_POST['delete_events'])) { leagueengine_delete_data('tournament_match_event',$_POST['delete_id'],'tournament',NULL,NULL,$tournament_id,$match_id); }
if(isset($_POST['save_match_statistics'])) { leagueengine_save_tournament_match_statistics($tournament_id,$match_id,$_POST['tournament_match_statistic'],$_POST['home_value'],$_POST['away_value'],$_POST['att_type']); }
if(isset($_POST['save_tournament_match_preview'])) { leagueengine_save_tournament_match_preview($tournament_id,$match_id,stripslashes_deep($_POST['match_preview'])); }
if(isset($_POST['save_tournament_match_report'])) { leagueengine_save_tournament_match_report($tournament_id,$match_id,stripslashes_deep($_POST['match_report'])); }
if(isset($_POST['tournament_match_swap'])) { leagueengine_tournament_match_swap($tournament_id,$match_id); }
$table = $wpdb->prefix . 'leagueengine_tournament_matches';
$match = $wpdb->get_row("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND id = '$match_id'");
$home_team_id = $match->home_team_id;
$away_team_id = $match->away_team_id;
$tournament = leagueengine_fetch_data_row('tournament',$tournament_id);
$table2 = $wpdb->prefix . 'leagueengine_tournaments';
$tournament_row = $wpdb->get_row("SELECT * FROM $table2 WHERE data_id = '$tournament_id'");
?>
<div id="leagueengine_admin" class="<?php echo $page; ?>">
<?php echo leagueengine_admin_header(); ?>
<div id="leagueengine_admin_content">
<?php if($msg) { echo $msg; } ?>
<ul class="breadcrumbs">
<li><?php _e('Competitions','leagueengine');?> <span class="divider">/</span></li>
<li><?php echo leagueengine_fetch_data_from_id($tournament_id,'data_value') ?> <span class="divider">/</span></li>
<?php if($match->round == 'GROUP') { ?>
<li><?php _e('Groups','leagueengine');?> <span class="divider">/</span></li>
<?php } else { ?>
<li><?php _e('Knockout','leagueengine');?> <span class="divider">/</span></li>
<?php } ?>
<li><?php _e('Match','leagueengine');?></li>
</ul>
<?php
if($league_type == 'players') {
$home_emblem = leagueengine_fetch_player_emblem($match->home_team_id,20);
$away_emblem = leagueengine_fetch_player_emblem($match->away_team_id,20,'right');
} else {
$home_emblem = leagueengine_fetch_team_emblem($match->home_team_id,20);
$away_emblem = leagueengine_fetch_team_emblem($match->away_team_id,20,'right');
}
?>
<div class="match_masthead">
<table>
<tr>
<td class="home_team" style="border-top: 5px solid <?php echo leagueengine_fetch_team_colour($match->home_team_id,'primary');?>; text-align:left;width:40%;"><?php echo $home_emblem . leagueengine_fetch_data_from_id($match->home_team_id,'data_value');?></td>
<td class="score" style="text-align:center;width:20%;"><span><?php echo $match->home_team_score;?> &dash; <?php echo $match->away_team_score;?></span></td>
<td class="away_team" style="border-top: 5px solid <?php echo leagueengine_fetch_team_colour($match->away_team_id,'primary');?>; text-align:right;width:40%;"><?php echo leagueengine_fetch_data_from_id($match->away_team_id,'data_value') . $away_emblem;?></td>
</tr>
<tr>
<td colspan="3" style="text-align:center;"><?php echo date(leagueengine_fetch_settings('date_format_php'),strtotime($match->match_date)) . ' ' . date(leagueengine_fetch_settings('time_format_php'),strtotime($match->match_time)); ?></td>
</tr>
<tr>
<td class="competition" colspan="3" style="text-align:center;"><?php echo '' . leagueengine_fetch_data_from_id($tournament_id,'data_value') . ''; ?></td>
</tr>
<tr><td colspan="100%" style="text-align:center;padding-bottom:20px;"><?php echo leagueengine_link('tournament_match&tid='.$tournament_id.'&mid='.$match->id,__('Go To Match','leagueengine'),'','','button-primary'); ?></td></tr>
</table>
</div>
<div id="leagueengine_tabs">
<ul>
<li><?php _e('Score','leagueengine');?></li>
<?php
$table = $wpdb->prefix . 'leagueengine_player_careers';
$homeplayers = $wpdb->get_results("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND team_id = '$home_team_id'");
$awayplayers = $wpdb->get_results("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND team_id = '$away_team_id'");
if($homeplayers or $awayplayers && $league_type != 'players') {
?>
<li><?php _e('Lineups','leagueengine');?></li>
<?php } ?>
<?php if(leagueengine_data_exists('event')) { echo '<li>' . __('Events','leagueengine') . '</li>'; } ?>
<?php if(leagueengine_statistics_exists('tournament_match')) { echo '<li>' . __('Statistics','leagueengine') . '</li>'; } ?>
<?php if(leagueengine_h2h_history($match->match_date,$home_team_id,$away_team_id)) { echo '<li>' . __('History','leagueengine') . '</li>'; } ?>
<li><?php _e('Report','leagueengine');?></li>
</ul>
<div id="score">
<form action="" method="POST">
<table class="form">
<tr>
<th style="width:20%;"><?php _e('Date/Time','leagueengine');?></th>
<th style="width:30%;text-align:center;"><?php _e('Home','leagueengine');?></th>
<th style="width:20%;text-align:center;"><?php _e('Score','leagueengine');?></th>
<th style="width:30%;text-align:center;"><?php _e('Away','leagueengine');?></th>
</tr>
<tr class="date">
<td><input type="text" class="leagueengine_datepicker" name="match_date" value="<?php echo date(leagueengine_fetch_settings('date_format_php'),strtotime($match->match_date));?>"></td>
<td colspan="3"></td>
</tr>
<input type="hidden" name="tournament_match_id" value="<?php echo $match->id;?>">
<input type="hidden" name="home_team_id" value="<?php echo $match->home_team_id;?>">
<input type="hidden" name="away_team_id" value="<?php echo $match->away_team_id;?>">
<input type="hidden" name="date_alt" class="leagueengine_datepicker_alt" value="<?php echo $match->match_date;?>">
<input type="hidden" name="time_alt" class="leagueengine_timepicker_alt" value="<?php echo $match->match_time;?>">
<tr>
<td><input type="text" class="leagueengine_timepicker" name="match_time" value="<?php echo date(leagueengine_fetch_settings('time_format_php'),strtotime($match->match_time));?>"></td>
<td style="text-align:center;"><?php echo leagueengine_fetch_data_from_id($match->home_team_id,'data_value') ;?></td>
<td style="text-align:center;">
<input style="width:48%;text-align:center;" type="text" name="home_team_score" value="<?php echo $match->home_team_score;?>">
<input style="width:48%;text-align:center;" type="text" name="away_team_score" value="<?php echo $match->away_team_score;?>">
</td>
<td style="text-align:center;"><?php echo leagueengine_fetch_data_from_id($match->away_team_id,'data_value') ;?></td>
</tr>
<?php if($tournament_row->pts_bonus == 'on') { ?>
<tr>
<td></td>
<td style="text-align:center;"><?php _e('Bonus Points','leagueengine');?></td>
<td style="text-align:center;">
<input style="width:48%;text-align:center;" type="text" name="home_team_bonus" value="<?php echo $match->home_team_bonus;?>">
<input style="width:48%;text-align:center;" type="text" name="away_team_bonus" value="<?php echo $match->away_team_bonus;?>">
</td>
<td style="text-align:center;"><?php _e('Bonus Points','leagueengine');?></td>
</tr>
<?php } ?>
</table>
<input style="margin-top:20px;" type="submit" name="save_tournament_match" class="button-primary" value="<?php _e('Save','leagueengine');?>" />
<input style="margin:20px 0 0 10px;" type="submit" name="tournament_match_swap" class="button" value="<?php _e('Swap Teams','leagueengine');?>" style="float:right;margin-right:10px;" />
</form>
</div>
<?php
$table = $wpdb->prefix . 'leagueengine_player_careers';
$homeplayers = $wpdb->get_results("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND team_id = '$home_team_id'");
$awayplayers = $wpdb->get_results("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND team_id = '$away_team_id'");
if($homeplayers or $awayplayers && $league_type != 'players') {
?>
<div id="lineups">
<?php echo leagueengine_tournament_match_lineups($tournament_id,$match_id);?>
</div>
<?php } ?>
<?php if(leagueengine_data_exists('event')) { ?>
<div id="events">
<?php echo leagueengine_tournament_match_events($tournament_id,$match_id);?>
</div>
<?php } ?>
<?php if(leagueengine_statistics_exists('tournament_match')) { ?>
<div id="statistics">
<?php echo leagueengine_fetch_statistics('tournament_match',NULL,NULL,$tournament_id,$match_id);?>
</div>
<?php } ?>
<?php if(leagueengine_h2h_history($match->match_date,$home_team_id,$away_team_id)) { ?>
<div id="history">
<?php echo leagueengine_fetch_h2h_history($match->match_date,$home_team_id,$away_team_id);?>
</div>
<?php } ?>
<div id="report">
<form action="" method="post">
<div class="setting">
<table class="form">
<tr><th><?php _e('Match Report','leagueengine');?></th></tr>
</table>
<?php wp_editor( stripslashes_deep($match->report), 'match_report', array( 'media_buttons' => true, 'tinymce' => true, 'quicktags' => true, 'textarea_rows' => 20 )); ?>
</div>
<input style="margin-top:20px;" type="submit" name="save_tournament_match_report" class="button-primary" value="<?php _e('Save','leagueengine'); ?>">
</form>
</div>
</div>
</div>
</div>
</div>

Multiple Checkboxes Columns Updating Multiple SQL Rows

I've never had issues programming PHP SQL updates when updating multiple rows of data with multiple columns, but for some reason this section of coding is killing me as it is nothing more than checkboxes for the end user to check and/or uncheck. I've include portions of the code below as the full code is over 50+ columns wide of checkboxes and can range from 1-200 rows.
Everything displays/runs the way its supposed to but the updating isnt functioning properly ... example: if there is 5 rows (each with a unique trackingid) and I check the checkbox for the 4th row on update it says that the 1st checkbox was checked and NOT the 4th row.
<?php if (!isset($_POST['trackingid'])) { ?>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post" enctype="multipart/form-data" class="form-horizontal" id="form"><input type="hidden" name="id" value="<?php echo $id; ?>">
<table class="table table-striped">
<thead>
<tr>
<td class="rotate-alt"></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt2"><div><span></span></div></td>
<td class="rotate-alt"><div><span>Glass</span></div></td>
<td class="rotate-alt"><div><span>Glass - SDL</span></div></td>
<td class="rotate-alt"><div><span>Mill - S&R</span></div></td>
</tr>
</thead>
<tbody>
<?php $result = sqlsrv_query($conn, "SELECT id, [Order Number], [Door Number], [Qty Display], [Interior or Exterior], [Style], Species_DD_Desc, [Mill Batch Nbr],
[Glass Completed], [Glass Completed By], [Glass STD Hrs], [SDL Completed], [SDL Completed By], [SDL STD Hrs],
[Mill Completed], [Mill Completed By], [Mill STD Hrs]
FROM PD_Tracking
WHERE [Order Number] = '$id'
ORDER BY [Door Number], [Qty Display], [Mill Batch Nbr]");
$i=0;
while ($list = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){ ?>
<tr>
<td class="center">
<input type="checkbox" onclick="$('input[id=\'selid<?php echo $i; ?>\']').attr('checked', this.checked);">
<input type="hidden" name="trackingid[]" value="<?php echo $list['id']; ?>">
</td>
<td class="center"><?php echo $list['Door Number']; ?></td>
<td class="center"><?php echo $list['Qty Display']; ?></td>
<td class="center"><?php echo $list['Interior or Exterior']; ?></td>
<td class="center"><?php echo $list['Style']; ?></td>
<td class="center"><?php echo $list['Species_DD_Desc']; ?></td>
<td class="center">
<?php if (($list['Glass STD Hrs']>0) && (!isset($list['Glass Completed']))){ ?>
<input type="checkbox" name="glass[]" id="selid<?php echo $i; ?>">
<?php } else if (($list['Glass STD Hrs']>0) && ($list['Glass Completed'] > ' ')){ ?>
<input type="checkbox" name="glass[]" checked="checked" id="selid<?php echo $i; ?>">
<?php } else { ?>
NR
<?php } ?>
</td>
<td class="center">
<?php if (($list['SDL STD Hrs']>0) && (!isset($list['SDL Completed']))){ ?>
<input type="checkbox" name="sdl[]" id="selid<?php echo $i; ?>">
<?php } else if (($list['SDL STD Hrs']>0) && ($list['SDL Completed'] > ' ')){ ?>
<input type="checkbox" name="sdl[]" checked="checked" id="selid<?php echo $i; ?>">
<?php } else { ?>
NR
<?php } ?>
</td>
<td class="center">
<?php if (($list['Mill STD Hrs']>0) && (!isset($list['Mill Completed']))){ ?>
<input type="checkbox" name="mill[]" id="selid<?php echo $i; ?>">
<?php } else if (($list['Mill STD Hrs']>0) && ($list['Mill Completed'] > ' ')){ ?>
<input type="checkbox" name="mill[]" checked="checked" id="selid<?php echo $i; ?>">
<?php } else { ?>
NR
<?php } ?>
</td>
</tr>
<?php ++$i;
} ?>
</tbody>
</table>
<?php } // END if (!isset($_POST['trackingid'])) {
if (isset($_POST['trackingid'])) {
$query = sqlsrv_query($conn, "SELECT * FROM users WHERE id=".$_SESSION['auid']."");
$row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC);
$employee_num = $row['Employee Number'];
$size = count($_POST['trackingid']);
for($i=0; $i < $size; $i++){
$trackingid = $_POST['trackingid'][$i];
$query = "UPDATE PD_Tracking SET ";
if(isset($_POST['glass'][$i])){
$query .= "[Glass Completed]='$date_time_entered', [Glass Completed By]='$employee_num', ";
} else {
$query .= "[Glass Completed]= NULL, [Glass Completed By]= NULL, ";
}
if(isset($_POST['sdl'][$i])){
$query .= "[SDL Completed]='$date_time_entered', [SDL Completed By]='$employee_num', ";
} else {
$query .= "[SDL Completed]= NULL, [SDL Completed By]= NULL, ";
}
if(isset($_POST['mill'][$i])){
$query .= "[Mill Completed]='$date_time_entered', [Mill Completed By]='$employee_num' ";
} else {
$query .= "[Mill Completed]= NULL, [Mill Completed By]= NULL ";
}
$query .= "WHERE id='$trackingid'";
$query = sqlsrv_query($conn, $query);
} // END for($i=0; $i < $size; $i++){?>
<SCRIPT LANGUAGE='JavaScript'>
<!-- Begin
window.location = '<?php echo $_SERVER['REQUEST_URI']; ?>&success=edit';
// End -->
</script>
<?php } // END if (isset($_POST['trackingid'])) { ?>

Ajax Mysql PHP How to show $_SESSION arrays result into DIV

My friends,
I´m facing some hard trouble with Ajax & PHP integration. I have a simple code as below that returns the data from database and shows into div class="item-list". When the user puts the quantity and clicks on submit button, the selected item is uploaded into div class="returned", like the "add item to cart" function. The code is working as well (add & remove from list), but only with refresh on page.
I saw many examples on web and I tried to adapt them to my code (today is my third day of fighting), but with no success. Could you please show to me a way to load the selected items into div class="returned" without refresh on page?
Best regards & thanks a lot!
<?php
session_start();
if(isset($_POST["add_to_table"])){
if(isset($_SESSION["dynamic_list"])){
$item_array_id = array_column($_SESSION["dynamic_list"], "item_id");
if(!in_array($_GET["idproduct"], $item_array_id)){
$count = count($_SESSION["dynamic_list"]);
$item_array = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["dynamic_list"][$count] = $item_array;
}else{
echo'<script>alert("Item added!")</script>';
echo'<script>window.location="intransit.php"</script>';
}
}else{
$item_array = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["dynamic_list"][0] = $item_array;
}
}
if(isset($_GET["action"])){
if($_GET["action"] == "delete"){
foreach($_SESSION["dynamic_list"] as $list => $values){
if($values["item_id"] == $_GET["idproduct"]){
unset($_SESSION["dynamic_list"][$list]);
echo'<script>alert("Item removed!")</script>';
echo'<script>window.location="intransit.php"</script>';
}
}
}
}
?>
<?php include"header.php" ?>
<div id="main_box">
<div id="moviment">
<div class="item_list">
<?php
$query = "SELECT * FROM products ORDER BY model ASC LIMIT 3";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<div id="product_table">
<form method="post" action="intransit.php?action=add&idproduct=<?php echo $row["idproduct"]; ?>">
<span><img src="images/<?php echo $row["image"]; ?>" alt="motor" width="80" height="80" /></span>
<span>Model:&nbsp<?php echo $row["model"]; ?></span>
<span>Price:&nbsp<?php echo $row["unitprice"]; ?></span>
<input type="text" name="quantity" value="1" class="qty" />
<input type="hidden" name="got_model" value="<?php echo $row["model"]; ?>" />
<input type="hidden" name="got_price" value="<?php echo $row["unitprice"]; ?>" />
<input type="submit" name="add_to_table" value="Add Item" />
</form>
</div><!--end "product_table"-->
<?php
}
}
?>
</div><!--end "item_list"-->
<div class="returned">
<table>
<tr>
<th>Model</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
<th>Action</th>
</tr>
<?php
if(!empty($_SESSION["dynamic_list"])){
$total = 0;
foreach($_SESSION["dynamic_list"] as $list => $values){
?>
<tr>
<td><?php echo $values["model"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td>$<?php echo $values["price"]; ?></td>
<td><?php echo number_format($values["item_quantity"] * $values["price"], 2); ?></td>
<td>Remove</td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2);?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
<?php include"footer.php" ?>
I tried to make example less complicated and to make it work with code you already created.
if (isset($_POST['got_model'])) {
$_SESSION["dynamic_list"][$_GET["idproduct"]] = array(
'item_id' => $_GET["idproduct"],
'model' => $_POST["got_model"],
'price' => $_POST["got_price"],
'item_quantity' => $_POST["quantity"]
);
return show_dynamic_list();
}
if (isset($_POST["action"]) && $_POST["action"] == "delete") {
unset($_SESSION["dynamic_list"][$_POST["idproduct"]]);
return show_dynamic_list();
}
function show_dynamic_list(){
?>
<table>
<tr><th>Model</th><th>Qty</th><th>Price</th><th>Total</th><th>Action</th></tr>
<?php
$total = 0;
foreach ($_SESSION["dynamic_list"] as $list => $values) {
?>
<tr>
<td><?php echo $values["model"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td>$<?php echo $values["price"]; ?></td>
<td><?php echo number_format($values["item_quantity"] * $values["price"], 2); ?></td>
<td>
<form action="" method="post" class="delete_form">
<input type="hidden" name="idproduct" value="<?php echo $values["item_id"]; ?>"/>
<input type="hidden" name="action" value="delete"/>
<input type="submit" value="Remove">
</form>
</td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
</table>
<?php
}
include"header.php" ?>
<div id="main_box">
<div id="moviment">
<div class="item_list">
<?php
$query = "SELECT * FROM products ORDER BY model ASC LIMIT 3";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<div id="product_table_<?php echo $row["idproduct"]; ?>">
<form method="post" action="?action=add&idproduct=<?php echo $row["idproduct"]; ?>">
<span>Model:&nbsp<?php echo $row["model"]; ?></span>
<span>Price:&nbsp<?php echo $row["unitprice"]; ?></span>
<input type="text" name="quantity" value="1" class="qty"/>
<input type="hidden" name="got_model" value="<?php echo $row["model"]; ?>"/>
<input type="hidden" name="got_price" value="<?php echo $row["unitprice"]; ?>"/>
<input type="submit" name="add_to_table" value="Add Item"/>
</form>
</div><<!--end "product_table"-->
<?php
}
}
?>
</div><!--end "item_list"-->
<div class="returned">
<?php show_dynamic_list(); ?>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
$('body').on('submit','#moviment form,.delete_form',function (event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type:'post',
url: form.attr('action'),
data: form.serialize(),
dataType:'html'
}).done(function (data) {
$('.returned').html(data);
}).fail(function (data) {
// error
});
});
});
</script>
<?php include"footer.php";

Categories