why multiple data doesn't insert in this code - php

I have a tbl_employee table and tbl_time table, I want to insert multiple data insert for attendance but when I click submit button it's insert only single data . but where is the problem ,help me to find out this..this is insert code
require './db_connect.php';
class Time extends Db_connect {
protected $link;
public function __construct() {
$this->link = $this->database_connection();
}
public function attendance_insert($data) {
extract($data);
$cur_date = date('Y-m-d');
foreach ($time_attendance as $attn_key => $attn_value) {
if ($attn_value == 'P') {
$SQL = "INSERT INTO tbl_time(employee_id,time_date,time_attendance)VALUES('$attn_key','$cur_date','P')";
$atten_date=mysqli_query($this->link, $SQL);
} else if ($attn_value == 'A') {
$SQL = "INSERT INTO tbl_time(employee_id,time_date,time_attendance)VALUES('$attn_key','$cur_date','A')";
$atten_date=mysqli_query($this->link, $SQL);
}
if ($atten_date) {
$massage = "<div class='alert alert-success text-center'><h5>Attendance insert successfully</h5></div>";
return $massage;
} else {
die('Attendance insert query problem' . mysqli_error($this->link));
}
}
}
}
this is html code
<?php
require_once './time.php';
$obj_time = new Time()
$massage = '';
if (isset($_POST['btn'])) {
$massage = $obj_time->attendance_insert($_POST);
}
$employee_view = $obj_employee->employee_all_view();
?>
<div class="container-fluid">
<div class="row">
<center>
<span style="font-size:1.8em;">Attendance form</span>
</center>
</div>
</div>
<hr/>
<?php echo $massage; ?>
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-body panel-default">
<div class="well text-center" style="font-size:15px;">
<strong>Date :</strong>
<?php $current_date = date('Y-M-d');
echo $current_date; ?>
</div>
<form class="form-horizontal" method="post">
<table class="table table-striped table-responsive text-center">
<tr>
<td><b>Serial</b></td>
<td><b>Name</b></td>
<td><b>ID</b></td>
<td><b>Attendance</b></td>
</tr>
<?php
$i = 0;
while ($employee_info = mysqli_fetch_assoc($employee_view)) {
extract($employee_info);
$i++;
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $employee_first_name . ' ' . $employee_last_name; ?></td>
<td><?php echo $employee_id; ?></td>
<td>
<input type="radio" name="time_attendance[<?php echo $employee_id; ?>]" value="P">P
<input type="radio" name="time_attendance[<?php echo $employee_id; ?>]" value="A">A
</td>
</tr>
<?php } ?>
<tr>
<td colspan="4">
<input type="submit" class="btn btn-primary btn-block" name="btn" value="submit"/>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>

This :
foreach($time_attendance as $attn_key => $attn_value){
$SQL = "INSERT INTO tbl_time(employee_id,time_date,time_attendance)
VALUES('$attn_key','$cur_date','A')";
$atten_date = mysqli_query($this->link, $SQL);
if ($atten_date) {
$massage = "<div class=''><h5>Attendance insert successfully</h5></div>";
return $massage;
}
}
Literally ask to break the foreach with return $massage; if you query succeed... So yes, you'll only have one record.
Put your return outside the foreach.

Related

PHP MySQL update multiple row with check box

I want to update checked values in MySQL with PHP
<?php
require "../../../../config.php";
if (isset($_POST['btn-upload'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$status = $_POST['status'];
$ck_id = $_POST['ck_id'];
for ($i = 0; $i < sizeof($ck_id); $i++) {
$sql = "UPDATE form_eg208 SET status=:status where ck_id IN (:ck_id)";
$statement = $connection->prepare($sql);
$statement->bindParam(':status', $status[$i]);
$statement->bindParam(':ck_id', $ck_id[$i]);
$statement->execute();
}
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
if ($statement->rowcount() >= 0) {
echo '<div class="alert alert-success alert-dismissible" id="flash-
msg">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×
</a>
<h4> <strong>Success!</strong> Insert Record
Successfully</h4>
</div>';
} else {
echo '<div class="alert alert-danger alert-dismissible" id="flash-
msg">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×
</a>
<h4> <strong>Failed!</strong> Duplicate BGLPARTNO</h4>
</div>';
}
}
?>
my html code is
<?php
$id = $_REQUEST['cid'];
try {
$connection = new PDO($dsn, $username, $password, $options);
$j = 1;
$sql = "CALL view_eg208 (:bglpartno)";
$statement = $connection->prepare($sql);
$statement->bindParam(':bglpartno', $id);
$statement->execute();
$result = $statement->fetchAll();
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
foreach ($result as $row1)
?>
<div class="container-fluid">
<div class="row">
<div class="col-md-12" style="margin-top:40px;">
<div class="card">
<div class="card-body">
<form method="post" action="" enctype='multipart/form-data' class="needs-validation" novalidate>
<div class="table-responsive m-t-40">
<table id="myTable" class="table table-hover table-bordered">
<thead class="thead-dark">
<tr>
<th>No.</th>
<th>Activity</th>
<th style="text-align:center;">Status</th>
</tr>
</thead>
<tbody>
<?php
if ($result && $statement->rowCount() > 0) {
foreach ($result as $row) { ?>
<tr>
<td>
<input type="checkbox" id="ck_id[]" class="filled-in chk-col-blue"
name="ck_id[]" value="<?php echo escape($row["ck_id"]); ?>"/>
</td>
<td style="color:black"><?php echo escape
($row["activity_name"]); ?></td>
<td>
<div class="form-group has-danger"
style="margin-bottom: 0;">
<input type="text" id="status[]" name="status[]" maxlength="100" class="form-control" value="<?php echo escape($row["status"]);?>" autocomplete="off" required="required">
<div class="invalid-feedback">
Please provide a Inputs.
</div>
</div>
</td>
</tr>
<?php }
}
$connection = null;
?>
</tbody>
</table>
When I update all the values then it works correctly but when single value then it updates the value of first box into that box which I selected. Please help me to solve this
Please make your checkbox input like this so you get the right status for the right ck_id index :
if ($result && $statement->rowCount() > 0) {
foreach ($result as $i => $row) { ?>
<tr>
<td>
<input type="checkbox" id="ck_id[]"class="filled-in chk-col-blue"
name="ck_id[<?php echo $i ?>]" value="<?php echo escape ($row["ck_id"]);?>"/>
</td>
<td style="color:black"><?php echo escape
($row["activity_name"]);?></td>
<td>
<div class="form-group has-danger"
style="margin-bottom: 0;">
<input type="text" id="status[]" name="status[<?php echo $i ?>]"
maxlength="100" class="form-control" value="<?
php echo escape ($row["status"]);?>" autocomplete="off"
required="required" >
<div class="invalid-feedback">
Please provide a Inputs.
</div>
</div>
</td>
</tr>
<?php
}
}
Also try to use foreach instead of for loops :
try {
$connection = new PDO($dsn, $username, $password, $options);
$status = $_POST['status'];
$ck_id = $_POST['ck_id'];
// for ($i = 0; $i < sizeof($ck_id); $i++) {
foreach ($ck_id as $i => $value) {
$sql = "UPDATE form_eg208 SET status=:status where ck_id IN (:ck_id)";
$statement = $connection->prepare($sql);
$statement->bindParam(':status', $status[$i]);
$statement->bindParam(':ck_id', $ck_id[$i]);
$statement->execute();
}
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}

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>

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

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

Fix Table Output for PHP

I am trying to make a table in PHP.
There is form where I am taking in Value - Market, Production Date, Sales Date and sending it in POST to Table to get it populated.
At the POST I am calling a set of data from production table from MySQL and populating in the same table.
I am able to populate the table from SQL and Form POST Action but I am not able to align them as per the required output format.
Please help in finding fix for the below Code:
<?php
if(isset($_POST['for_post']))
{
try
{
?>
<div class="card-box" style="padding-left:5px;padding:10px;padding-bottom:50px">
<div class="row">
<div class="col-sm-12">
<?php
if(isset($_POST['for_post_market'])){ $pname = $_POST['for_post_market']; }
if(isset($_POST['for_post_prod_date'])){ $pcat = $_POST['for_post_prod_date']; }
if(isset($_POST['for_post_sale_date'])){ $pprice = $_POST['for_post_sale_date']; }
$query = 'SELECT * FROM product';
$stmt = $DB_con->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['prod_cat_name']][] = $row['prod_name'];
}
?>
<table id="invoices" border="1">
<thead>
<th>Category</th>
<th>Product</th>
<th>Production Date</th>
<th>Sales Date</th>
<th>Market</th>
</thead>
<tbody>
<?php
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices) . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
echo "<td>$invoice</td>";
echo "<td>".$pcat."</td>";
echo "<td>".$pprice."</td>";
$count++;
}
}
$a=count($pname);
for($i=0;$i<$a;$i++)
{
echo "<td>".$pname[$i]."</td></tr>";
}
echo "</tbody>";
echo "</table>";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{ ?>
</div>
</div>
</div>
<div class="card-box" style="padding-left:5px;padding:10px;padding-bottom:50px">
<div class="row">
<div class="col-sm-12">
<form class="form-inline" method="post">
<div class="form-group m-r-10">
<label for="exampleInputName2">Market : </label>
<div class="input-group">
<select class="selectpicker" multiple data-selected-text-format="count" data-style="btn-white" name="for_post_market[]">
<?php
$stmt = $DB_con->prepare('Select * from location');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['location_name'].'</option>';
}
?>
</select>
<div>
&nbsp
<div class="form-group m-r-10">
<label for="exampleInputEmail2">Production Date : </label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclose" name="for_post_prod_date">
<span class="input-group-addon bg-custom b-0 text-white"><i class="icon-calender"></i></span>
</div>
</div>
<div class="form-group m-r-10">
<label for="exampleInputEmail2">Sales Date : </label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker2-autoclose" name="for_post_sale_date">
<span class="input-group-addon bg-custom b-0 text-white"><i class="icon-calender"></i></span>
</div>
</div>
<button type="submit" class="btn btn-default waves-effect waves-light btn-md" id="for_post" name="for_post">
Submit
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
The Current Output that I am able to get from this code is :
What I am trying to get is :
Updated Changes Suggested and worked:
<table id="invoices" border="1">
<thead>
<th>Category</th>
<th>Product</th>
<th>Production Date</th>
<th>Sales Date</th>
<th>Market</th>
<th>Input</th>
</thead>
<tbody>
<?php
$a=count($pname);
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices)*$a . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
echo '<td rowspan='. count($pname) . '>' . $invoice . '</td>';
echo '<td rowspan='. count($pname) . '>' . $pcat . '</td>';
echo '<td rowspan='. count($pname) . '>' . $pprice . '</td>';
for($i=0;$i<$a;$i++)
{
echo '<td>'. $pname[$i] . '</td>';
echo '<td><input type="text" class="form-control"></td></tr>';
}
$count++;
}
}
echo '</tbody>';
echo '</table>';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{ ?>
You have to set Category column rowspan to count($invoices)*count($pname) and set rowspan to Product, Production date and Sales date columns to count($pname)

PHP Beginner Column not found 1054 Unknown column

The goal is to code php files so I have the ability to perform CRUD functions on categories.
I don't know what I'm doing wrong and why I'm getting an this error . Check the image below!
But after changing it i get Column not found: 1054 Unknown column 'category_category_id' in 'field list' on line 43?
Line 43
$q->execute(array($category_category_id,$category_name,$id));
updateCategory.php
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$category_nameError = null;
$category_category_idError = null;
// keep track post values
$category_category_id = $_POST['id'];
$category_name = $_POST['category_name'];
// validate input
$valid = true;
if (empty($category_category_id)) {
$category_idError = 'Please enter Category id';
$valid = false;
}
if (empty($category_name)) {
$category_nameError = 'Please enter Category name';
$valid = false;
}
// update data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE category set category_category_id = ?, category_name = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($category_category_id,$category_name,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM category where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$category_category_id = $data['id'];
$category_name = $data['category_name'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update a Category</h3>
</div>
<form class="form-horizontal" action="updateCategory.php?id=<?php echo $id?>" method="post">
<div class="control-group <?php echo !empty($$category_category_idError)?'error':'';?>">
<label class="control-label">Category Id</label>
<div class="controls">
<input name="id" type="text" placeholder="Category Id" value="<?php echo !empty($category_category_id)?$category_category_id:'';?>">
<?php if (!empty($$category_category_id)): ?>
<span class="help-inline"><?php echo $$category_category_id;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($category_nameError)?'error':'';?>">
<label class="control-label">Category Name</label>
<div class="controls">
<input name="category_name" type="text" placeholder="Category Name" value="<?php echo !empty($category_name)?$category_name:'';?>">
<?php if (!empty($category_nameError)): ?>
<span class="help-inline"><?php echo $category_nameError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<h3>Product Menu</h3>
</div>
<div class="row">
<p>
Create
</p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>CategoryId</th>
<th>Brand</th>
<th>Name</th>
<th>Barcode</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
include_once 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM product ORDER BY id ASC';
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo '<td>'. $row['category_id'] . '</td>';
echo '<td>'. $row['brand'] . '</td>';
echo '<td>'. $row['name'] . '</td>';
echo '<td>'. $row['barcode'] . '</td>';
echo '<td>'. $row['price'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="read.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="update.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="delete.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
<div class="container">
<div class="row">
<h3>Category Menu</h3>
</div>
<div class="row">
<p>
Create
</p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Category Id</th>
<th>Category Name</th>
</tr>
</thead>
<?php
include_once 'database.php';
$pdo = Database::disconnect();
$pdo = Database::connect();
$sql = 'SELECT * FROM category ORDER BY id ASC';
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo '<td>'. $row['category_name'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="readCategory.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="updateCategory.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="deleteCategory.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div>
</body>
</html>
<!-- <div class="container">
<div class="row">
<h3>PHP CRUD Grid</h3>
</div>
<div class="row">
<p>
Create
</p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>CategoryId</th>
<th>Catengory Name</th>
</tr>
</thead>
$sql2 = 'SELECT * FROM category ORDER BY id DESC';
foreach ($pdo->query($sql2) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo '<td>'. $row['category_name'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="readCategory.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="updateCategory.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="deleteCategory.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
</div>
}
Database::disconnect();
?>
</tbody>
</table> -->
You need to initialize the variable in the code like this
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
$category_category_id = "";
$category_name = "";
if ( !empty($_POST)) {
// keep track validation errors
$category_nameError = null;
$category_category_idError = null;
// keep track post values
$category_category_id = $_POST['id'];
$category_name = $_POST['category_name'];
// validate input
$valid = true;
if (empty($category_name)) {
$category_nameError = 'Please enter Category name';
$valid = false;
}
if (empty($category_category_id)) {
$category_idError = 'Please enter Category id';
$valid = false;
}
// update data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE category set id = ?, category_name = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($category_category_id,$category_name,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM category where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$category_category_id = $data['id'];
$category_name = $data['category_name'];
Database::disconnect();
}
also change the input field name
<input name = "category_name" id="catogortId" type = "text" placeholder = "Category Name" value = "<?php echo !empty($category_name)?$category_name:'';?>">
You don't have put name attribute value in form so put it like :
<input name="category_name" type="text" placeholder="Category Name" name="category_name" value="<?php echo !empty($category_name)?$category_name:'';?>">
You do not have category_name field.
Change:
<input name="category_id" type="text" placeholder="Category Name" value="<?php echo !empty($category_name)?$category_name:'';?>">
To
<input name="category_name" type="text" placeholder="Category Name" value="<?php echo !empty($category_name)?$category_name:'';?>">
You need to change name = "category_id" to name = "category_name" in updateCategory.php file
Change
<input name = "category_id" type = "text" placeholder = "Category Name" value = "<?php echo !empty($category_name)?$category_name:'';?>">
TO
<input name = "category_name" type = "text" placeholder = "Category Name" value = "<?php echo !empty($category_name)?$category_name:'';?>">

Categories