How to insert data in php/mysql in one save click? - php

I have table player_points with player_name, runs, sixes, match_no, fiftys, hundreds, point_scored.
I make form with above fields where i insert runs and sixes and calculate fiftys, hundreds and point_scored using runs & sixes, give extra 10 points for every sixex after 3 six.
Its works properly but when i insert runs and sixes and save it only shows calculation in fiftys, hundred and point-scored textbox not saved into database table. After i saved it second time its save into database. My code is like below:
<tr><td colspan="9"><hr style="border:1px #999 dashed;"></td></tr>
<tr>
<th>Player</th>
<th>Status</th>
<th>Runs</th>
<th>6's</th>
<th>50's</th>
<th>100's</th>
<th>TP</th>
<th>Action</th>
</tr>
<tr><td colspan="9"><hr style="border:1px #999 dashed;"></td></tr>
<?php
$classObj->getPlayerPointTable();
//$matchid = $_GET['mid'];
$condpl = "player_name='".$player1."' AND match_no = '".$matchid."'";
$resultpl = $classObj->selectSql($condpl);
//$recordcount = $classObj->getAffectedRows($result);
$rowpl = $classObj->fetchData($resultpl);
foreach($rowpl as $rowspl)
{
$Status1 = $rowspl['status'];
$runs1 = $rowspl['run_scored'];
$sixes1 = $rowspl['sixs'];
$fifty1 = $rowspl['fifty'];
$hundred1 = $rowspl['hundred'];
$total_score1 = $rowspl['Total_Score'];
$total_points1 = $rowspl['point_scored'];
$firstPoint1 = $rowspl['FirstPoint'];
$allocation1 = $rowspl['allocation'];
}
?>
<?php
$bonus1 = 10;
$bonus2 = 20;
$bonus3 = 25;
$bonus4 = 50;
/*condition for fifty 0 & 1 start */
if ($runs1 >= 50 && $runs1 <= 99 || $runs1 >= 150 && $runs1 <= 199 || $runs1 >= 250 && $runs1 <= 299) {
$fifty1 = 1;
} else {
$fifty1 = 0;
}
if ($runs1 >= 50 && $runs1 <= 499) {
$tfif1 = $runs1 + $bonus3;
} else {
$tpor1 = $runs1;
}
/*condition for fifty 0 & 1 end */
/*condition for hundred 0 & 1 start */
if ($runs1 >= 100 && $runs1 <= 199) {
$hundred1 = 1;
}
else if ($runs1 >= 200 && $runs1 <= 299) {
$hundred1 = 2;
}
else {
$hundred1 = 0;
}
/*condition for hundred 0 & 1 end */
/*Condition start for Six excess to 3 sixes*/
$i1 = $sixes1 - 3;
if($i1 >= 1 && $i1 <= 500)
{
$tsix1 = $i1 * $bonus1;
}
else
{
$tsix1 == 0;
}
/*Condition start for Six excess to 3 sixes*/
if($fifty1 == 1 && $hundred1 >= 1)
{
$tsixhnrd1 += $bonus4;
}
/*condition for hundred 0 & 1 end */
if ($runs1 >= 100 && $runs1 <= 500) {
$trun1 += $bonus3;
}
$total_points1 = $tfif1+$tsix1+$tsixhnrd1+$trun1+$tpor1;
$total_score1 = $runs1;
/*veriable for Balling team database insertions end*/
?>
<form enctype="multipart/form-data" method="post" name="formA1">
<tr>
<td><div style="width:auto;padding-left:7px;font-size:17px;"><?php echo $player1;?></div>
<input type="hidden" name="player1" id="player1" value="<?php echo $player1;?>" />
<input type="hidden" name="matchid" id="matchid" value="<?php echo $matchid;?>" />
</td>
<?php
if($Status1=='P'){
?>
<td align="center">
<select id='status1' name='status1' onChange="dis_ableA1(this)">
<option value='NP'>NP</option>
<option value='P' selected>P</option>
<option value='O'>Out</option>
</select>
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:50px;height:25px;text-align:right;background:#f5c0c0;" name="runs1" id="runs1" value="<?php echo $runs1;?>" size="3" maxlength="3" />
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:30px;height:25px;text-align:right;background:#f5c0c0;" name="sixes1" id="sixes1" value="<?php echo $sixes1;?>" size="2" maxlength="2" />
</td>
<?php
} else if($Status1=='O'){
?>
<td align="center">
<select id='status1' style="width:50px;height:25px;" name='status1' onChange="dis_ableA1(this)">
<option value='NP'>NP</option>
<option value='P'>P</option>
<option value='O' selected>Out</option>
</select>
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:50px;height:25px;text-align:right;background:#ccc;" disabled name="runs1" id="runs1" value="<?php echo $runs1;?>" size="3" maxlength="3" />
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:30px;height:25px;text-align:right;background:#CCC;" disabled name="sixes1" id="sixes1" value="<?php echo $sixes1;?>" size="2" maxlength="2" />
</td>
<?php } else { ?>
<td align="center">
<select id='status1' style="width:50px;height:25px;" name='status1' onChange="dis_ableA1(this)" tabindex="1">
<option value='NP'>NP</option>
<option value='P'>P</option>
<option value='O'>Out</option>
</select>
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:50px;height:25px;text-align:right;" name="runs1" disabled id="runs1" value="<?php echo $runs1;?>" size="3" maxlength="3" />
</td>
<td align="center">
<input type="text" onkeypress="return blockNonNumbers(this, event, false, false);" style="width:30px;height:25px;text-align:right;" name="sixes1" disabled id="sixes1" value="<?php echo $sixes1;?>" size="2" maxlength="2" />
</td>
<?php }?>
<td align="center">
<label style="width:30px;height:25px;text-align:right;"><?php echo $fifty1;?></label>
<input style="width:30px;height:25px;text-align:right;" type="hidden" id="fifty1" name="fifty1" value="<?php echo $fifty1;?>" size='2' maxlength='2' />
</td>
<td align="center">
<label style="width:30px;height:25px;text-align:right;"><?php echo $hundred1;?></label>
<input style="width:30px;height:25px;text-align:right;" type="hidden" id="hundred1" name="hundred1" value="<?php echo $hundred1;?>" size='2' maxlength='2' />
</td>
<td align="center">
<label style="width:30px;height:25px;text-align:right;"><?php echo $total_points1;?></label>
<input style="width:30px;height:25px;text-align:right;" type="hidden" id="total_points1" name="total_points1" value="<?php echo $total_points1;?>" size='5' maxlength='5' />
<input type="hidden" name="allocation1" id="allocation1" value="pending" />
</td>
<?php
if($Status1=='P'){
?>
<td align="center">
<input type="submit" name="submitA1" id="submitA1" value="Save" />
</td>
<?php } else { ?>
<td align="center">
<input type="submit" disabled="disabled" name="submitA1" id="submitA1" value="Save" />
</td>
<?php } ?>
</tr>
</form>
<tr><td style="height:5px"></td></tr>
<!-- Insert Code Starts Submit1-->
<?php
if(isset($_POST['submitA1']))
{
$classObj->getPlayerPointTable();
$matchid = $_GET['mid'];
$cond = "player_name='".$player1."' AND match_no = '".$matchid."'";
$result = $classObj->selectSql($cond);
$count = $classObj->getAffectedRows($result);
//echo $count;
if($count > 0)
{
$player1up['status'] = $postedData['status1'];
//$player1up['player_name'] = $postedData['player1'];
$player1up['run_scored'] = $postedData['runs1'];
$player1up['sixs'] = $postedData['sixes1'];
$player1up['fifty'] = $postedData['fifty1'];
$player1up['hundred'] = $postedData['hundred1'];
$player1up['Total_Score'] = $postedData['total_score1'];
$player1up['point_scored'] = $postedData['total_points1'];
$player1up['allocation'] = $postedData['allocation1'];
$player1up['FirstPoint'] = $postedData['total_points1'];
$classObj->getPlayerPointTable();
$classObj->userPostedData = $player1up;
$cond = "match_no= '".$matchid."' AND player_name='".$player1."'";
$insert_query = $classObj->updateData($cond);
echo "<script> alert ('Player 1 update successfully.')</script>";
echo "<script>window.location='FirstIn.php?mid=$matchid'</script>";
}
else if($count <= 0)
{
$player['player_name'] = $postedData['player1'];
$player['match_no'] = $postedData['matchid'];
$player['status'] = $postedData['status1'];
$player['run_scored'] = $postedData['runs1'];
$player['sixs'] = $postedData['sixes1'];
$player['fifty'] = $postedData['fifty1'];
$player['hundred'] = $postedData['hundred1'];
$player['Total_Score'] = $postedData['total_score1'];
$player['point_scored'] = $postedData['total_points1'];
$player['FirstPoint'] = $postedData['total_points1'];
$classObj->userPostedData = $player;
$insert_query = $classObj->insertData();
if($insert_query == 'success')
{
echo "<script> alert('Player 1 score added.')</script>";
echo "<script>window.location='score.php?mid=$matchid'</script>";
}
}
else
{
echo "<script> alert ('Error Occured')</script>";
}
}
?>

Assuming that your class' getAffectedRows() method really fetches the affected rows from the last statement, it must be noted that a SELECT does not set this, it will be zero.
If you want to know how many lines were selected, use something like mysqli_num_rows.

Related

Lost PHP variable, last seen in Chrome, answers to the name $quote_date

I can't seem to find my PHP variable $quote_date. I have a form that grabs job records from the database and displays a job's current progress in the form ready to be edited, submitted and updated to the database. All of the job's other records are being collected and displayed correctly but the $quote_date is missing in action. Yet when I echo the $quote_date after the renderForm() function is executed it appears to really exist, at least at that point. Why is the $quote_date not being displayed in the form?
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Allow the user to both create new records and edit existing records.
// Connect to the database.
$connect = mysqli_connect('localhost', 'username', 'password', 'database');
if ( !$connect ) {
die( 'connect error: '.mysqli_connect_error() );
}
// creates the new/edit record form.
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($error = '', $id = '', $start_date = '', $company = '', $stock_code = '', $card_quantity = '', $fiske_print = '', $carrier_quantity = '', $quoted = '', $quote_details = '', $quoted_date = '', $quote_accepted = '', $quote_accepted_date = '', $proof_sent = '', $proof_sent_date = '', $proof_approved = '', $proof_approved_date = '', $printed = '', $print_date = '', $closed_loop_allocated = '', $invoiced = '', $invoiced_date = '', $posted = '', $tracking_number = '', $postal_date = '', $paid = '', $is_bulk_load = '', $bulk_funds_recieved = '', $cards_loaded = '', $notes = '', $completed = '')
{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<?php
$pageName = 'overview';
?>
<?php
include('header.php');
?>
<h1><?php
if ($id != '') {
echo "Edit Record";
} else {
echo "New Record";
}
?></h1>
<?php
if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error . "</div>";
}
?>
<form action="" method="post">
<div>
<table>
<tr>
<td colspan="2" style="text-align:center;"><strong>Job Details</strong></td>
<td colspan="2" style="text-align:center;"><strong>Job Progress</strong></td>
</tr>
<tr>
<td>ID: </td>
<td><input type="text" name="id" value="<?php echo $id; ?>" readonly></td>
<td>Quoted: </td>
<td><input type="checkbox" name="quoted" value="1" <?php if($quoted == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Start Date: </td>
<td><input type="date" name="start_date" value="<?php if($start_date !== ''){echo date('Y-m-d',strtotime($start_date));} ?>"></td>
<td>Quote Details: </td>
<td><input type="text" name="quote_details" size="40" value="<?php echo $quote_details; ?>"></td>
</tr>
<tr>
<td>Company: </td>
<td><input type="text" name="company" size="40" value="<?php echo $company; ?>"></td>
<td>Quote Date: </td>
// Here is where the mystery lies why is my $quote_date variable missing?
<td><input type="date" name="quote_date" value="<?php echo date('Y-m-d',strtotime($quote_date)); ?>"></td><?php echo '<script type="text/javascript">alert("'.$quote_date.'");</script>'; ?>
</tr>
<tr>
<td>Stock Code: </td>
<td>
<div id="billdesc">
<select id="test" name="stock_code">
<option class="non" value="GS01">GS01</option>
<option class="non" value="GS03">GS03</option>
<option class="non" value="SM01">SM01</option>
<option class="non" value="SM11">SM11</option>
<option class="non" value="CG01">CG01</option>
<option class="non" value="CG38">CG38</option>
<option class="editable" value="Other">Other</option>
</select>
<input class="editOption" style="display:none;" placeholder="Text juaj"></input>
</div>
</td>
<td>Quote Accepted: </td>
<td><input type="checkbox" name="quote_accepted" value="1" <?php if($quote_accepted == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Card Quantity: </td>
<td><input type="text" name="card_quantity" value="<?php echo $card_quantity; ?>"></td>
<td>Quote Accepted Date: </td>
<td><input type="date" name="quote_accepted_date" value="<?php if($quote_accepted_date !== ''){echo date('Y-m-d',strtotime($quote_accepted_date));} ?>"></td>
</tr>
<tr>
<td>Carrier Quantity: </td>
<td><input type="text" name="carrier_quantity" value="<?php echo $carrier_quantity; ?>"></td>
<td>Proof Sent: </td>
<td><input type="checkbox" name="proof_sent" value="1" <?php if($proof_sent == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Fiske Print: </td>
<td><input type="checkbox" name="fiske_print" value="1" <?php if($fiske_print == 1){echo 'checked';} ?>></td>
<td>Proof Sent Date: </td>
<td><input type="date" name="proof_sent_date" value="<?php if($proof_sent_date !== ''){echo date('Y-m-d',strtotime($proof_sent_date));} ?>"></td>
</tr>
<tr>
<td rowspan="6" colspan="2" style="text-align:center;">
Notes:<br>
<textarea name="notes" rows="8" cols="70"><?php echo $notes; ?></textarea>
</td>
<td style="text-align:right;">Proof Approved: </td>
<td style="text-align:left;"><input type="checkbox" name="proof_approved" value="1" <?php if($proof_approved == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Proof Approved Date: </td>
<td><input type="date" name="proof_approved_date" value="<?php if($proof_approved_date !== ''){echo date('Y-m-d',strtotime($proof_approved_date));} ?>"></td>
</tr>
<tr>
<td>Printed: </td>
<td><input type="checkbox" name="printed" value="1" <?php if($printed == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Print Date</td>
<td><input type="date" name="printed_date" value="<?php if($print_date !== ''){echo date('Y-m-d',strtotime($print_date));} ?>"></td>
</tr>
<tr>
<td>Closed Loop Allocated: </td>
<td><input type="checkbox" name="closed_loop_allocated" value="1" <?php if($closed_loop_allocated == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Invoiced: </td>
<td><input type="checkbox" name="invoiced" value="1" <?php if($invoiced == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Paid: </td>
<td><input type="checkbox" name="paid" value="1" <?php if($paid == 1){echo 'checked';} ?>></td>
<td>Invoice Date: </td>
<td><input type="date" name="invoice_date" value="<?php if($invoice_date !== ''){echo date('Y-m-d',strtotime($invoice_date));} ?>"></td>
</tr>
<tr>
<td>Is Bulk Load: </td>
<td><input type="checkbox" name="is_bulk_load" value="1" <?php if($is_bulk_load == 1){echo 'checked';} ?>></td>
<td>Posted: </td>
<td><input type="checkbox" name="posted" value="1" <?php if($posted == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Bulk Funds Recieved</td>
<td><input type="checkbox" name="bulk_funds_recieved" value="1" <?php if($bulk_funds_received == 1){echo 'checked';} ?> ></td>
<td>Postal Date: </td>
<td><input type="date" name="postal_date" value="<?php if($postal_date !== ''){echo date('Y-m-d',strtotime($postal_date));} ?>"></td>
</tr>
<tr>
<td>Cards Loaded: </td>
<td><input type="checkbox" name="cards_loaded" value="1" <?php if($cards_loaded == 1){echo 'checked';} ?>></td>
<td>Tracking Number: </td>
<td><input type="text" name="tracking_number" size="30" value="<?php echo $tracking_number; ?>"></td>
</tr>
<tr>
<td colspan="4" style="text-align:center;">
Completed: <input type="checkbox" name="completed" value="1" <?php if($completed == 1){echo 'checked';} ?>>
<input type="submit" name="submit" value="Save" style="width:90px" />
</td>
</tr>
</table>
<script type="text/javascript">
var initialText = $('.editable').val();
$('.editOption').val(initialText);
$('#test').change(function(){
var selected = $('option:selected', this).attr('class');
var optionText = $('.editable').text();
if(selected == "editable"){
$('.editOption').show();
$('.editOption').keyup(function(){
var editText = $('.editOption').val();
$('.editable').val(editText);
$('.editable').html(editText);
});
}else{
$('.editOption').hide();
}
});
</script>
</body>
</html>
<?php
}
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit an existing record
if (isset($_GET['id'])) {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id'])) {
// get the form data
// I'll get to this later... get form to display first...
echo 'We are saving a new edit of job ' . $id;
}
// if the 'id' variable is not valid, show an error message
else {
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else {
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0) {
// get 'id' from URL
$id = $_GET['id'];
// get the record from database
if ($stmt = $connect->prepare("SELECT id, start_date, company, stock_code, card_quantity, fiske_print, carrier_quantity, quoted, quote_details, quoted_date, quote_accepted, quote_accepted_date, proof_sent, proof_sent_date,proof_approved, proof_approved_date, printed, print_date, closed_loop_allocated, invoiced, invoiced_date, posted, tracking_number, postal_date, paid, is_bulk_load, bulk_funds_received, cards_loaded, notes, completed FROM jobs WHERE id = ?")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($id,$start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s\n", $id,$start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
}
// show the form by executing renderForm()
renderForm(NULL, $id,$start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
// check to see if we have a quote date..?
echo 'quote date: '.$quote_date;
$stmt->close();
}
// show an error if the query has an error
else {
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else {
header("Location: addJob.php");
}
}
}
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// get the form data
$start_date = date("Y-m-d", strtotime($_POST['start_date']));
$company = $_POST['company'];
$stock_code = $_POST['stock_code'];
$card_quantity = $_POST['card_quantity'];
$carrier_quantity = $_POST['carrier_quantity'];
$fiske_print = $_POST['fiske_print'];
$quoted = $_POST['quoted'];
$quote_details = $_POST['quote_details'];
$quote_date = date("Y-m-d", strtotime($_POST['quote_date']));
$quote_accepted = $_POST['quote_accepted'];
$quote_accepted_date = date("Y-m-d", strtotime($_POST['quote_accepted_date']));
$proof_sent = $_POST['proof_sent'];
$proof_sent_date = date("Y-m-d", strtotime($_POST['proof_sent_date']));
$proof_approved = $_POST['proof_approved'];
$proof_approved_date = date("Y-m-d", strtotime($_POST['proof_approved_date']));
$printed = $_POST['printed'];
$printed_date = date("Y-m-d", strtotime($_POST['printed_date']));
$closed_loop_allocated = $_POST['closed_loop_allocated'];
$invoiced = $_POST['invoiced'];
$invoice_date = date("Y-m-d", strtotime($_POST['invoice_date']));
$posted = $_POST['posted'];
$postal_date = date("Y-m-d", strtotime($_POST['postal_date']));
$tracking_number = $_POST['tracking_number'];
$paid = $_POST['paid'];
$is_bulk_load = $_POST['is_bulk_load'];
$bulk_funds_received = $_POST['bulk_funds_received'];
$cards_loaded = $_POST['cards_loaded'];
$completed = $_POST['completed'];
/* Prepare an insert statement */
$query = "INSERT INTO jobs (start_date,company,stock_code,card_quantity,fiske_print,carrier_quantity,quoted,quote_details,quoted_date,quote_accepted,quote_accepted_date,proof_sent,proof_sent_date,proof_approved,proof_approved_date,printed,print_date,closed_loop_allocated,invoiced,invoiced_date,posted,tracking_number,postal_date,paid,is_bulk_load,bulk_funds_received,cards_loaded,notes,completed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($connect, $query);
mysqli_stmt_bind_param($stmt, "sssssssssssssssssssssssssssss", $start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
/* Execute the statement */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
// redirect the user
header("Location: index.php");
}
// if the form hasn't been submitted yet, show the form
else {
error_log('SQL error ('.__FILE__.' line '.__LINE__.'): '. $connect->error);
renderForm();
}
}
// close the mysqli connection
$connect->close();
?>

Comparison and data extraction with PHP, MySQL, JS

I have a database, golf_add.php and ajax_price.php Files.
So I can not do this:
After I choose values from form like > From | To | Transfer Type | Golf Date option box fields, I want these fields' values are compared and select the appropriate data from database (for golf price value) into Golf Price textBox.
For example:
From: XXX Otel (id=15)To: YYY Place(id=25)Transfer Type: Shuttle (id=4)Golf Date: 2015/08/05
After I choose these values from form I want to click refresh button OR after I selected the Golf Date last step its automatically must get only price from correct row according to my selection as above..
You can preview my form here :
golf_add.php code:
<!-- OTHER CODES ... -->
<script>
function refreshforprice() {
jQuery.ajax({
type: 'GET',
url: 'ajax_price.php',
data: 'tid='+jQuery('#op_transfer_type_id').val()+'&p='+jQuery('#operation_pax').val()+'&p2='+jQuery('#operation_pax2').val()+'&v=1',
cache : false,
success: function(sonuc){
sonucx = sonuc.split(';');
jQuery('#sold_tour_price_auto').val(sonucx[0]+'.00');
jQuery('#xprice1').html('* '+sonucx[1]+'.00 €');
jQuery('#xprice2').html('* '+sonucx[2]+'.00 €');
}
});
}
</script>
<form method="POST" action="golf_add.php" name="adminForm" id="adminForm">
<table class="adminlist">
<thead>
<tr>
<th> GOLF DETAILS </th>
</tr>
</thead>
</table>
<table class="adminlist">
<tbody>
<?PHP $i = 0; ?>
<tr class="<?php $i++; $m=$i%2; if($m=='1') echo "row0"; else echo "row1";?>">
<td align="right"><b>From</b></td>
<td id="fromarea">
<select size="1" name="operation_pickup_from" id="operation_pickup_from">
<option value="-1" disabled selected> --- Select Pick Up Point --- </option>
<?php
$strSQL2 = "SELECT * FROM pickup_points_From WHERE region_id='".$regionidx."' soldtours='1' ORDER BY pickup_point_name ASC";
$resultSQL2 = mysql_query($strSQL2);
$ks = mysql_num_rows($resultSQL2);
for ($z=0; $z<$ks; $z++) {
$rowSQL2 = mysql_fetch_array($resultSQL2);
?><option value="<?=$rowSQL2['pickup_point_id']?>"><?=$rowSQL2['pickup_point_name']?></option><?
}
?>
</select>
</td>
</tr>
<tr class="<?php echo "row1";?>">
<td align="right"><b>To</b></td>
<td id="fromarea">
<select size="1" name="operation_pickup_to" id="operation_pickup_to">
<option value="-1" disabled selected> --- Select Drop Point --- </option>
<?php
$strSQL3 = "SELECT * FROM pickup_points_To WHERE region_id='".$regionidx."' AND soldtours='1' ORDER BY drop_point_name";
$resultSQL3 = mysql_query($strSQL3);
while($rowSQL3 = mysql_fetch_array($resultSQL3)) {
?>
<option value="<?=$rowSQL3['drop_point_id']?>"><?=$rowSQL3['drop_point_name']?></option>
<? } ?>
</select>
</td>
</tr>
<tr class="<?php $i++; $m=$i%2; if($m=='1') echo "row0"; else echo "row1";?>">
<td align="right"><b>Transfer Type</b></td>
<td id="tourtypes">
<select size="1" name="op_transfer_type_id" id="op_transfer_type_id">
<option value="-1" disabled selected> --- Select Transfer Type --- </option>
<?php
$strSQL2 = "SELECT * FROM operation_transfer_types WHERE op_transfer_type_id IN (4,10) ORDER BY op_transfer_type_name";
$resultSQL2 = mysql_query($strSQL2);
while($rowSQL2 = mysql_fetch_array($resultSQL2)) {
?><option value="<?=$rowSQL2['op_transfer_type_id']?>"><?=$rowSQL2['op_transfer_type_name']?></option><?
}
?>
</select>
</td>
</tr>
<tr class="<?php $i++; $m=$i%2; if($m=='1') echo "row0"; else echo "row1";?>">
<td width="45%" align="right"><b>Golf Date</b>»</td>
<td width="55%"><input type="text" name="operation_date" id="operation_date" value="<?=$_GET['selected_day']?>" size="10" class="datepicker" autocomplete="off"> <input type="text" name="operation_time" id="operation_time" size="5" class="timepicker" autocomplete="off">«<b>Golf Time</b></td>
</tr>
<tr class="<?php $i++; $m=$i%2; if($m=='1') echo "row0"; else echo "row1";?>">
<td align="right"><b>Adult</b></td>
<td><input type="text" name="operation_pax" id="operation_pax" size="5" value="1" onkeypress="return OnlyDigits(event);"
onblur="OnlyDigits(event,false)" autocomplete="off"> <span id="xprice1" style="color: green;">* 0.00 €. </span>
</tr>
<tr class="<?php $i++; $m=$i%2; if($m=='1') echo "row0"; else echo "row1";?>">
<td align="right" id="agex1"><b>06-12 Age</b></td>
<td><input type="text" name="operation_pax2" id="operation_pax2" size="5" value="0" onkeypress="return OnlyDigits(event);"
onblur="OnlyDigits(event,false)" autocomplete="off"> <span id="xprice2" style="color: green;">* 0.00 €. </span>
</td>
</tr>
<tr class="<?php $i++; $m=$i%2; if($m=='1') echo "row0"; else echo "row1";?>">
<td align="right"><b>Golf Price</b></td>
<td id="pricediv"><input type="text" name="sold_tour_price_auto" id="sold_tour_price_auto" size="8" class="bestupper"
value="0.00" onkeypress="return OnlyDigits(event,'.');" onblur="OnlyDigits(event,false)"> EUR
</td>
</tr>
</tbody>
</table>
</form>
<!-- OTHER CODES ... -->
ajax_price.php Code:
<?php
$tid = intval(#$_GET['tid']);
$p = intval(#$_GET['p']);
$p2 = intval(#$_GET['p2']);
$v = intval(#$_GET['v']);
$sql = "SELECT * FROM transfer_type WHERE transfer_id='".$tid."'";
$s = mysql_query($sql);
$ks = mysql_num_rows($s);
if ($ks > 0) {
$k = mysql_fetch_assoc($s);
$pprice = floatval($k['golf_price']);
if ($tid == 4) {
$price_pax = $p + $p2;
$price = ($price_pax * $pprice) + ($price_pax * 7);
}
else {
$price = ($pprice * $p) + ($pprice * $p2);
}
if ($v == 1) { echo $price.';'.$pprice.';'.$pprice; }
else { echo $price; }
?><?PHP
}
else {
if ($v == 1) { ?>0;0;0<?PHP }
else { ?>0<?PHP }
}
?>
I'm not too sure but I can't see where you are using the function refreshforprice() in your form, I have done similar using the function in a onchange in a <select> box.
eg <select id="something" name="something" onchange"function();">

PHP if isset($_POST doesn't work

I have a simple form on my page and I want to make sure every field is filled before inserting the values into the database. The problem is the condition never met, even if every field is filled I still get "Something is missing"...
Search:
<form method="post" action="<?php echo $_SERVER[" PHP_SELF "]?>">
<input placeholder="e-mail address" type="text" name="email_search">
<input type="submit" name="search" value="Go">
<?php if (isset($_POST[ "search"])) { $email_search=m ysql_real_escape_string($_POST[ "email_search"]); $check=m ysql_query( "SELECT * FROM torzsvendegek WHERE email = '$email_search'"); $s=m ysql_fetch_array($check); }?>
<form method="post" action="<?php echo $_SERVER[" PHP_SELF "]?>">
<table width="440" border="0" style="text-align:right;">
<tr>
<td>E-mail:</td>
<td>
<input type="text" name="email" value="<?php echo $email_search;?>" disabled>
</td>
</tr>
<tr>
<td>Név:</td>
<td>
<input type="text" name="nev" value="<?php echo $s['nev'];?>">
</td>
</tr>
<tr>
<td>Mikor:</td>
<td>
<input type="text" name="mikor">
</td>
</tr>
<tr>
<td>Éjszakák száma:</td>
<td>
<input type="text" name="ejszakak">
</td>
</tr>
<tr>
<td>Nemzetisége:</td>
<td align="left">
<select name="nyelv">
<option value="magyar" <?php if($s[ 'nyelv']=="magyar" ) echo "selected=\"selected\ ""; ?>>Magyar</option>
<option value="nemet" <?php if($s[ 'nyelv']=="nemet" ) echo "selected=\"selected\ ""; ?>>Német</option>
<option value="lengyel" <?php if($s[ 'nyelv']=="lengyel" ) echo "selected=\"selected\ ""; ?>>Lengyel</option>
<option value="roman" <?php if($s[ 'nyelv']=="roman" ) echo "selected=\"selected\ ""; ?>>Román</option>
<option value="szlovak" <?php if($s[ 'nyelv']=="szlovak" ) echo "selected=\"selected\ ""; ?>>Szlovák</option>
<option value="egyeb" <?php if($s[ 'nyelv']=="egyeb" ) echo "selected=\"selected\ ""; ?>>Egyéb</option>
</select>
</td>
</tr>
<tr>
<td>Megjegyzés:</td>
<td>
<textarea name="megjegyzes">
<?php echo htmlspecialchars($s[ 'megjegyzes']);?>
</textarea>
</td>
</tr>
</table>
<br>
<table width="440">
<tr>
<td>
<input type="submit" name="submit_add" value="Hozzáad">
</td>
</tr>
</table>
</form>
<?php if (isset($_POST[ "submit_add"]) && !empty($_POST[ "nev"]) && !empty($_POST[ "email"]) && !empty($_POST[ "mikor"]) && !empty($_POST[ "ejszakak"])){ $nev=m ysql_real_escape_string($_POST[ "nev"]); $email=m ysql_real_escape_string($_POST[ "email"]); $mikor=m ysql_real_escape_string($_POST[ "mikor"]); $ejszakak=m ysql_real_escape_string($_POST[ "ejszakak"]); $nyelv=m ysql_real_escape_string($_POST[ "nyelv"]); $megjegyzes=m ysql_real_escape_string($_POST[ "megjegyzes"]); $check2=m ysql_query( "SELECT * FROM torzsvendegek WHERE email = '$email'"); $br="<br>" ; if (mysql_num_rows($check2)> 0) { $adatok = mysql_fetch_array($check2); $osszesen = ($adatok['ejszakak'] + $ejszakak); mysql_query("UPDATE torzsvendegek SET nev = '".$nev."', mikor = '".$adatok['mikor']."".$mikor."".$br."', ejszakak = '".$osszesen."', nyelv = '".$nyelv."', megjegyzes = '".$adatok['megjegyzes']."".$megjegyzes."".$br."' WHERE email = '".$email."'"); echo "
<br>".$email." Updated"; } else { mysql_query("INSERT INTO torzsvendegek (id, nev, email, mikor, ejszakak, nyelv, megjegyzes) VALUES (NULL, '$nev', '$email', '".$mikor."".$br."', '$ejszakak', '$nyelv', '".$megjegyzes."')"); echo "
<br>".$email." Added"; } } else { echo "Something is missing"; } ?>
You made 2 mistakes in your code:
1) You didn't close the first form (missing </form>)
2) You disabled the E-mail input field which resulted in always empty
Here's the updated (though deprecated and insecure!!!) code:
<?php
if(isset($_POST["search"])){
$email_search = mysql_real_escape_string($_POST["email_search"]);
$check = mysql_query("SELECT * FROM torzsvendegek WHERE email = '$email_search'");
$s = mysql_fetch_array($check);
}
if(isset($_POST["submit_add"]) && !empty($_POST["nev"]) && !empty($_POST["email"]) && !empty($_POST["mikor"]) && !empty($_POST["ejszakak"])){
$nev = mysql_real_escape_string($_POST["nev"]);
$email = mysql_real_escape_string($_POST["email"]);
$mikor = mysql_real_escape_string($_POST["mikor"]);
$ejszakak = mysql_real_escape_string($_POST["ejszakak"]);
$nyelv = mysql_real_escape_string($_POST["nyelv"]);
$megjegyzes = mysql_real_escape_string($_POST["megjegyzes"]);
$check2 = mysql_query("SELECT * FROM torzsvendegek WHERE email = '$email'");
$br = "<br>";
if (mysql_num_rows($check2) > 0){
$adatok = mysql_fetch_array($check2);
$osszesen = ($adatok['ejszakak'] + $ejszakak);
mysql_query("UPDATE torzsvendegek SET nev = '".$nev."', mikor = '".$adatok['mikor']."".$mikor."".$br."', ejszakak = '".$osszesen."', nyelv = '".$nyelv."', megjegyzes = '".$adatok['megjegyzes']."".$megjegyzes."".$br."' WHERE email = '".$email."'");
echo "<br>".$email." Updated";
} else {
mysql_query("INSERT INTO torzsvendegek (id, nev, email, mikor, ejszakak, nyelv, megjegyzes) VALUES (NULL, '$nev', '$email', '".$mikor."".$br."', '$ejszakak', '$nyelv', '".$megjegyzes."')");
echo "<br>".$email." Added";
}
} else {
echo "Something is missing";
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>">
Search: <input placeholder="e-mail address" type="text" name="email_search">
<input type="submit" name="search" value="Go">
</form>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>">
<table width="440" border="0" style="text-align:right;">
<tr>
<td>E-mail:</td>
<td><input type="text" name="email" value="<?php echo $email_search;?>"></td>
</tr>
<tr>
<td>Név:</td>
<td><input type="text" name="nev" value="<?php echo $s['nev'];?>"></td>
</tr>
<tr>
<td>Mikor:</td>
<td><input type="text" name="mikor"></td>
</tr>
<tr>
<td>Éjszakák száma:</td>
<td><input type="text" name="ejszakak"></td>
</tr>
<tr>
<td>Nemzetisége:</td>
<td align="left">
<select name="nyelv">
<option value="magyar" <?php if($s['nyelv']=="magyar") echo "selected=\"selected\""; ?>>Magyar</option>
<option value="nemet" <?php if($s['nyelv']=="nemet") echo "selected=\"selected\""; ?>>Német</option>
<option value="lengyel" <?php if($s['nyelv']=="lengyel") echo "selected=\"selected\""; ?>>Lengyel</option>
<option value="roman" <?php if($s['nyelv']=="roman") echo "selected=\"selected\""; ?>>Román</option>
<option value="szlovak" <?php if($s['nyelv']=="szlovak") echo "selected=\"selected\""; ?>>Szlovák</option>
<option value="egyeb" <?php if($s['nyelv']=="egyeb") echo "selected=\"selected\""; ?>>Egyéb</option>
</select>
</td>
</tr>
<tr>
<td>Megjegyzés:</td>
<td><textarea name="megjegyzes"><?php echo htmlspecialchars($s['megjegyzes']);?></textarea></td>
</tr>
</table>
<br>
<table width="440">
<tr>
<td><input type="submit" name="submit_add" value="Hozzáad"></td>
</tr>
</table>
</form>
You need to close your search form tag to keep the two forms separated
Search:<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>"><input placeholder="e-mail address" type="text" name="email_search"><input type="submit" name="search" value="Go"></form>
and
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>">
<table width="440" border="0" style="text-align:right;">
<tr><td>E-mail:</td><td><input type="text" name="email" value="<?php echo $email_search;?>" disabled></td></tr>
<tr><td>Név:</td><td><input type="text" name="nev" value="<?php echo $s['nev'];?>"></td></tr>
<tr><td>Mikor:</td><td><input type="text" name="mikor"></td></tr>
<tr><td>Éjszakák száma:</td><td><input type="text" name="ejszakak"></td></tr>
<tr><td>Nemzetisége:</td><td align="left"> <select name="nyelv">
<option value="magyar" <?php if($s['nyelv']=="magyar") echo "selected=\"selected\""; ?>>Magyar</option>
<option value="nemet" <?php if($s['nyelv']=="nemet") echo "selected=\"selected\""; ?>>Német</option>
<option value="lengyel" <?php if($s['nyelv']=="lengyel") echo "selected=\"selected\""; ?>>Lengyel</option>
<option value="roman" <?php if($s['nyelv']=="roman") echo "selected=\"selected\""; ?>>Román</option>
<option value="szlovak" <?php if($s['nyelv']=="szlovak") echo "selected=\"selected\""; ?>>Szlovák</option>
<option value="egyeb" <?php if($s['nyelv']=="egyeb") echo "selected=\"selected\""; ?>>Egyéb</option>
</select></td></tr>
<tr><td>Megjegyzés:</td><td><textarea name="megjegyzes"><?php echo htmlspecialchars($s['megjegyzes']);?></textarea></td></tr>
</table><br>
<table width="440"><tr><td><input type="submit" name="submit_add" value="Hozzáad"></td></tr></table>
</form>
You did not close your search form and you need to remove the disabled attribute from your email input field.
I re-wrote your code to help you will debugging. I commented out all the stuff related to the database so you can focus on the form fields only. Here is the code I re-wrote. I left comments so you can see what I did.
<?php
/******JUST TO MAKE DEBBUGGING EASIER***/
echo "<pre>"; // Start of the pre> tags
/**ANYTHING TO DO WITH THE DATABASE I HAVE COMMENTED OUT**/
if(isset($_POST["search"])){
$email_search = mysql_real_escape_string($_POST["email_search"]);
/**PRINT_R FOR DEBUGGING PURPOSES, REMOVE!!*/
print_r($email_search);
//$check = mysql_query("SELECT * FROM torzsvendegek WHERE email = '$email_search'");
//$s = mysql_fetch_array($check);
}
/***CHECK THE POST DATA, REMOVE FROM APPLICATION ONCE YOU HAVE DEBUGGED THE DATA**/
print_r($_POST);
/***I WILL STORE THE POST DATA IN VARIABLES BEFORE CHECKING**/
$nev = isset($_POST["nev"]) ? mysql_real_escape_string($_POST["nev"]) : null;
$email = isset($_POST["email"]) ? mysql_real_escape_string($_POST["email"]) : null;
$mikor = isset($_POST["mikor"]) ? mysql_real_escape_string($_POST["mikor"]) : null;
$ejszakak = isset($_POST["ejszakak"]) ? mysql_real_escape_string($_POST["ejszakak"]) : null;
$nyelv = isset($_POST["nyelv"]) ? mysql_real_escape_string($_POST["nyelv"]) : null;
$megjegyzes = isset($_POST["megjegyzes"]) ? mysql_real_escape_string($_POST["megjegyzes"]) : null;
if(isset($_POST["submit_add"]) && !is_null($nev) && !is_null($email) && !is_null($mikor) && !is_null($ejszakak)){
/*******
SINCE I ALREADY HAVE THEM, YOU NEED TO REMOVE THEM FROM THE CODE
$nev = mysql_real_escape_string($_POST["nev"]);
$email = mysql_real_escape_string($_POST["email"]);
$mikor = mysql_real_escape_string($_POST["mikor"]);
$ejszakak = mysql_real_escape_string($_POST["ejszakak"]);
$nyelv = mysql_real_escape_string($_POST["nyelv"]);
$megjegyzes = mysql_real_escape_string($_POST["megjegyzes"]);
******/
//$check2 = mysql_query("SELECT * FROM torzsvendegek WHERE email = '$email'");
$br = "<br>";
/*********
if (mysql_num_rows($check2) > 0) {
$adatok = mysql_fetch_array($check2);
$osszesen = ($adatok['ejszakak'] + $ejszakak);
mysql_query("UPDATE torzsvendegek SET nev = '".$nev."', mikor = '".$adatok['mikor']."".$mikor."".$br."', ejszakak = '".$osszesen."', nyelv = '".$nyelv."', megjegyzes = '".$adatok['megjegyzes']."".$megjegyzes."".$br."' WHERE email = '".$email."'");
echo "<br>".$email." Updated";
}else {
mysql_query("INSERT INTO torzsvendegek (id, nev, email, mikor, ejszakak, nyelv, megjegyzes) VALUES (NULL, '$nev', '$email', '".$mikor."".$br."', '$ejszakak', '$nyelv', '".$megjegyzes."')");
echo "<br>".$email." Added";
}
****/
}elseif (isset($_POST["submit_add"])) {
echo "Something is missing";
}
echo '</pre>';//end of pre
?>
Search:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>">
<input placeholder="e-mail address" type="text" name="email_search">
<input type="submit" name="search" value="Go">
</form>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]?>">
<table width="440" border="0" style="text-align:right;">
<tr>
<td>E-mail:</td>
<td><input type="text" name="email" value="<?php echo $email;?>" ></td>
</tr>
<tr>
<td>Név:</td>
<td><input type="text" name="nev" value="<?php echo $nev;?>"></td>
</tr>
<tr>
<td>Mikor:</td>
<td><input type="text" name="mikor" value="<?php echo $mikor;?>"></td>
</tr>
<tr>
<td>Éjszakák száma:</td>
<td><input type="text" name="ejszakak" value="<?php echo $ejszakak;?>"></td>
</tr>
<tr>
<td>Nemzetisége:</td>
<td align="left">
<select name="nyelv">
<option value="magyar" <?php if($nyelv=="magyar") echo "selected=\"selected\""; ?>>Magyar</option>
<option value="nemet" <?php if($nyelv=="nemet") echo "selected=\"selected\""; ?>>Német</option>
<option value="lengyel" <?php if($nyelv=="lengyel") echo "selected=\"selected\""; ?>>Lengyel</option>
<option value="roman" <?php if($nyelv=="roman") echo "selected=\"selected\""; ?>>Román</option>
<option value="szlovak" <?php if($nyelv=="szlovak") echo "selected=\"selected\""; ?>>Szlovák</option>
<option value="egyeb" <?php if($nyelv=="egyeb") echo "selected=\"selected\""; ?>>Egyéb</option>
</select>
</td>
</tr>
<tr>
<td>Megjegyzés:</td>
<td><textarea name="megjegyzes"><?php echo htmlspecialchars($megjegyzes);?></textarea>
</td>
</tr>
</table><br>
<table width="440">
<tr><td><input type="submit" name="submit_add" value="Hozzáad"></td></tr>
</table>
</form>

data not inerted correctly when going through a loop

$answersql = "INSERT INTO Penalty_Marks (PenaltyAnswer, PenaltyMarks, QuestionId)
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
}
$c = count($_POST['incorrect']);
for($i = 0; $i < $c; $i++ )
{
$incorrect = $_POST['incorrect'][$i];
$answerMarks = $_POST['answerMarks'][$i];
$numQuestion = $_POST['numQuestion'][$i];
$insertanswer->bind_param('sii', $incorrect, $answerMarks, $numQuestion);
$insertanswer->execute();
}
The above insert is not inserting all the incorrect answers into the table, it is only inserting one incorrect answer per question. What am I doing wrong?
Below is the currect db table looks like:
PenaltyAnswerId PenaltyAnswer PenaltyMarks QuestionId
1 A 4 12
2 D 1 13
Below is what it should of been like:
PenaltyAnswerId PenaltyAnswer PenaltyMarks QuestionId
1 A 4 12
2 B 3 12
3 D 0 12
4 D 1 13
5 E 1 13
Below is form:
<form id="PenaltyMarks" action="insertpenaltymarks.php" method="post">
<table id='penaltytbl'>
<?php
foreach($ques_ans as $questionId => $inc_ans)
{
$q_row_span = count($inc_ans);
$row_count = 0;
$inc_ans = array_values($inc_ans);
?>
<tr class="questiontd">
<td>
<input type="hidden" name="numQuestion[]" value="<?php echo$questionId?>" />
</td>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[]" value="<?php echo$inc_ans[$row_count];?>">
</td>
<td>
<input name="answerMarks[]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
//remaining incorrect answers in separate row (if any) follows here
if($row_count < $q_row_span - 1)
{
for($i=($row_count + 1); $i<$q_row_span; $i++) { ?>
<tr>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[]" value="<?php echo$inc_ans[$i];?>">
</td>
<td class="answermarkstd">
<input name="answerMarks[]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
}
}
}
?>
</table>
<input id="submitBtn" name="submitPenalty" type="submit" value="Submit Marks" />
</form>
Below is jquery handling submit:
myClickHandler = function(e) {
if (confirm("Are you sure you want to Proceed?" + "\n")) {
$.ajax({
url: "insertpenaltymarks.php",
data: $("#PenaltyMarks").serialize(),
async: false,
type: "POST"
});
return true;
} else {
return false;
}
};
$('#PenaltyMarks').submit(myClickHandler);
});
UPDATE:
Question Table:
QuestionId (PK auto) (int 10)
QuestionNo (int 4)
QuestionContent (varchar 5000)
Penalty_Marks Table;
PenaltyAnswerId (PK auto) (int 10)
PenaltyAnswer (Varchar 5)
PenaltyMarks (int 3)
QuestionId (FK) (int 10) Reference to QuestionId in Question Table
Updated
With your current code, you can var_dump and found that the $_POST['numQuestion'] array may contains a fewer member than the $_POST['incorrect'][$i] array. I have updated my code too.
<form id="PenaltyMarks" action="insertpenaltymarks.php" method="post">
<table id='penaltytbl'>
<?php
foreach($ques_ans as $questionId => $inc_ans)
{
$q_row_span = count($inc_ans);
$row_count = 0;
$inc_ans = array_values($inc_ans);
?>
<tr class="questiontd">
<td>
<input type="hidden" name="numQuestion[<?php echo $questionId; ?>]" value="<?php echo$questionId?>" />
</td>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[<?php echo $questionId; ?>][]" value="<?php echo$inc_ans[$row_count];?>">
</td>
<td>
<input name="answerMarks[<?php echo $questionId; ?>][]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
//remaining incorrect answers in separate row (if any) follows here
if($row_count < $q_row_span - 1)
{
for($i=($row_count + 1); $i<$q_row_span; $i++) { ?>
<tr>
<td>
<input type="hidden" class="hiddenincorrect" name="incorrect[<?php echo $questionId; ?>][]" value="<?php echo $inc_ans[$i];?>">
</td>
<td class="answermarkstd">
<input name="answerMarks[<?php echo $questionId; ?>][]" type="text" data-type="qmark" value='0' />
</td>
</tr>
<?php
}
}
}
?>
</table>
<input id="submitBtn" name="submitPenalty" type="submit" value="Submit Marks" />
</form>
The insertion script should be changed too :)
foreach($_POST['incorrect'] as $questionId => $incorrectArray)
{
for($i = 0; $i < count($incorrectArray), $i++)
{
$incorrect = $_POST['incorrect'][$questionId][$i];
$answerMarks = $_POST['answerMarks'][$questionId][$i];
$numQuestion = $_POST['numQuestion'][$questionId];
$insertanswer->bind_param('sii', $incorrect, $answerMarks, $numQuestion);
$insertanswer->execute();
}
}

Validating between 2 drop down menus so only one can be selected php

I have a script below which the user logs a php form.
There is a section with 2 drop down menus next to each other, 'npc_battery_n_code' and 'npc_battery_other_code'.
What I am trying to do is to make it so one of these drop down menus has to have an option selected for the form to be submitted, but not both or none.
So for example, if an option gets selected in 'npc_battery_n_code' and then the user selects another option in 'npc_battery_other_code', then the value of the 'npc_battery_n_code' will revert to the 'None' option.
Any suggestions welcome
<?php //logsale.php
require_once ('./includes/config.inc.php');
$page_title = 'Log a sale';
include ('./includes/header.html');
if (!isset($_SESSION['sp_user_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
$users = $_SESSION['sp_user_id'];
?>
<h1>Heading</h1>
<?php
if (isset($_POST['submitted'])) {// Handle the form.
require_once ('mydatabase.php');
if (!empty($_POST['npc_quantity'])) {
$quantity = escape_data($_POST ['npc_quantity']);
} else {
$quantity = FALSE;
echo '<p><font color="red">You forgot to enter the Quantity</font></p>';
}
if (!empty($_POST['npc_customer_name'])) {
$customer = escape_data($_POST ['npc_customer_name']);
} else {
$customer = FALSE;
echo '<p><font color="red">You forgot to enter the Customer Name</font></p>';
}
if (!empty($_POST['npc_registration_no'])) {
$rego = escape_data($_POST ['npc_registration_no']);
} else {
$rego = FALSE;
echo '<p><font color="red">You forgot to enter the Customer Rego Number</font></p>';
}
if (!empty($_POST['npc_suo_no'])) {
$suo = escape_data($_POST ['npc_suo_no']);
} else {
$suo = FALSE;
echo '<p><font color="red">You forgot to enter the SUO Number</font></p>';
}
if (!empty($_POST['npc_amb_club_no'])) {
$repair_order = escape_data($_POST ['npc_amb_club_no']);
} else {
$repair_order = FALSE;
echo '<p><font color="red">You forgot to enter the A-Club number</font></p>';
}
if (!empty($_POST['npc_repair_order'])) {
$amb_club = escape_data($_POST ['npc_repair_order']);
} else {
$amb_club = FALSE;
echo '<p><font color="red">You forgot to enter the Repair Order</font></p>';
}
if (!empty($_POST['npc_invoice_no'])) {
$inv = escape_data($_POST ['npc_invoice_no']);
} else {
$inv = FALSE;
echo '<p><font color="red">You forgot to enter the Invoice Number </font></p>';
}
if (!empty($_POST['npc_entry_userdate'])) {
$inv_date = escape_data($_POST ['npc_entry_userdate']);
} else {
$inv_date = FALSE;
echo '<p><font color="red">You forgot to enter the Invoice Date</font></p>';
}
if ($quantity && $customer && $rego && $suo && $repair_order && $amb_club && $inv && $inv_date) {
$uid = #mysql_insert_id(); //Get the url ID.
$query = "INSERT INTO npc_sales_list
(npc_item_id , sp_user_id, npc_battery_n_code, npc_battery_other_code, npc_quantity,
npc_customer_name, npc_registration_no, npc_suo_no, npc_amb_club_no, npc_repair_order,
npc_entry_userdate, npc_usertype, npc_points, npc_bonus_points, npc_entry_date)
VALUES
('$uid', '$users', '$_POST[npc_battery_n_code]', '$_POST[npc_battery_other_code]', '$quantity',
$customer , $rego, $suo, $amb_club , $repair_order,
$inv , 'NPC', '5' , '0' , NOW())";
$result = mysql_query ($query) or trigger_error
("Query: $query\n<br />MySQL Error: " .mysql_error());
if ($result = #mysql_query($query)) {
//Finish the page.
echo '<p>The sale with invoice number: <strong>' . $inv . '</strong> <br />
is now registered into the system.</p>
<p>If you would like to log in further sales, please click here</p>
<p>If you would like to view your sales log, please click here</p>
';
include ('./includes/footer.html'); // Include the HTML footer.
exit();
} else { // If it did not run OK.
echo '<p><font color="red" size="+1">You could not be
registered due to a system error. We apologize for any
inconvenience.</font></p>';
}
}
} else { // If one of the data tests failed.
echo '<p><font color="red" size="+1">Please check all manatory fields are complete and try again.
</font></p>';
}
mysql_close(); // Close the database connection.
?>
<form enctype="multipart/form-data" action="logsale.php" method="post">
<table width="520" border="0" cellspacing="3" cellpadding="2">
<tr>
<td width="184"><div align="right">NPC Vehicle<span class="style2">*</span></div></td>
<td width="323"><select name="npc_battery_n_code" id="npc_battery_n_code">
<option value="None"
<?php if (isset($_POST['npc_battery_n_code']) && $_POST['npc_battery_n_code'] == 'None')
{echo 'selected="selected"';} ?>>None
</option>
<option value="55D23L"
<?php if (isset($_POST['npc_battery_n_code']) && $_POST['npc_battery_n_code'] == '55D23L')
{echo 'selected="selected"';} ?>>55D23L
</option>
<option value="55D23R"
<?php if (isset($_POST['npc_battery_n_code']) && $_POST['npc_battery_n_code'] == '55D23R')
{echo 'selected="selected"';} ?>>55D23R
</option>
<option value="75D23R"
<?php if (isset($_POST['npc_battery_n_code']) && $_POST['npc_battery_n_code'] == '75D23R')
{echo 'selected="selected"';} ?>>75D23R
</option>
</select></td>
</tr>
<tr>
<td width="184"><div align="right">Other <span class="style2">*</span></div></td>
<td width="323">
<select name="npc_battery_other_code" id="npc_battery_other_code">
<option value="50D20L"
<?php if (isset($_POST['npc_battery_other_code']) && $_POST['npc_battery_other_code'] == '50D20L')
{echo 'selected="selected"';} ?>>50D20L
</option>
<option value="50D20R"
<?php if (isset($_POST['npc_battery_other_code']) && $_POST['npc_battery_other_code'] == '50D20R')
{echo 'selected="selected"';} ?>>50D20R
</option>
<option value="55D23LMF"
<?php if (isset($_POST['npc_battery_other_code']) && $_POST['npc_battery_other_code'] == '55D23LMF')
{echo 'selected="selected"';} ?>>55D23LMF
</option>
<option value="55D23RMF"
<?php if (isset($_POST['npc_battery_other_code']) && $_POST['npc_battery_other_code'] == '55D23RMF')
{echo 'selected="selected"';} ?>>55D23RMF
</option>
</select></td>
</tr>
<tr>
<td><div align="right">Quantity <span class="style2">*</span></div></td>
<td><input type="text" name="npc_quantity" size="10" maxlength="10"
value="<?php if (isset($_POST['npc_quantity'])) echo $_POST['npc_quantity']; ?>" /></td>
</tr>
<tr>
<td><div align="right">Customer name<span class="style2">*</span></div></td>
<td><input type="text" name="npc_customer_name" size="30" maxlength="30"
value="<?php if (isset($_POST['npc_customer_name'])) echo $_POST['npc_customer_name']; ?>" /></td>
</tr>
<tr>
<td><div align="right">Rego number <span class="style2">*</span></div></td>
<td><input type="text" name="npc_registration_no" size="10" maxlength="7"
value="<?php if (isset($_POST['npc_registration_no'])) echo $_POST['npc_registration_no']; ?>" /></td>
</tr>
<tr>
<td><div align="right">SUO No.<span class="style2">*</span></div></td>
<td><input type="text" name="npc_suo_no" size="10" maxlength="7"
value="<?php if (isset($_POST['npc_suo_no'])) echo $_POST['npc_suo_no']; ?>"/></td>
</tr>
<tr>
<td><div align="right">A-Club ID<span class="style2">*</span></div></td>
<td><input type="text" name="npc_amb_club_no" size="15" maxlength="7"
value="<?php if (isset($_POST['npc_amb_club_no'])) echo $_POST['npc_amb_club_no']; ?>"/></td>
</tr>
<tr>
<td><div align="right">Repair Order <span class="style2">*</span></div></td>
<td><input type="text" name="npc_repair_order" size="15" maxlength="12"
value="<?php if (isset($_POST['npc_repair_order'])) echo $_POST['npc_repair_order']; ?>" /></td>
</tr>
<tr>
<td><div align="right">Invoice No. <span class="style2">*</span></div></td>
<td><input size="10" name="npc_invoice_no"
value="<?php if (isset($_POST['npc_invoice_no'])) echo $_POST['npc_invoice_no']; ?>" /></td>
</tr>
<tr>
<td><div align="right">Invoice Date <span class="style2">*</span></div></td>
<td><input size="12" name="npc_entry_userdate" maxlength="10"
value="<?php if (isset($_POST['npc_entry_userdate'])) echo $_POST['npc_entry_userdate']; ?>"/> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" /></p><input type="hidden" name="submitted" value="TRUE" />
</td>
</tr>
</table>
</form>
<p>Footer</p>
<?php
include ('./includes/footer.html');
?>
jquery: select and unselect items of listbox is what you are looking for.
How you want your script to work cannot be achieved with PHP or Mysql. You can only work with the data when the website is loaded. If you want to edit the data without refreshing the page you need to use JavaScript, or more advanced jQuery.

Categories