Passing value from one field to another field - php

I'm new to programming language. I want to know can i get value from other field and pass to other field in same form without using javascript ? Can someone explain to me ? Thank u.
This my form page
<form id="leave_form">
<table><tr>
<td width="70"><b>*</b> Date From:</td>
<td width="120"><span id="lv_date_from_btn"><input readonly class="field_required control" onchange="validateLeave('from')" id="lv_date_from" name="date_from" value="<?php echo $start_date?>" size="10" maxlength="10"/> <img src="images/calendar.gif"/></span></td>
</tr>
<tr>
<td width="70"><b>*</b> Date To:</td>
<td width="120"><span id="lv_date_to_btn"><input readonly class="field_required control" onchange="validateLeave('to')" id="lv_date_to" name="date_to" value="<?php echo $end_date?>" size="10" maxlength="10"/> <img src="images/calendar.gif"/></span></td>
</tr>
<?php if ($userid == '609'):?>
<tr>
<td><b>*</b> Relief Staff: </td>
<td>
<select name="userid" id="frm_userid2" class="field_required control" onchange="validateLeave('relief')" >
<?php
$leavefrom = $_REQUEST['from'];
$leaveto = $_REQUEST['to'];
if (empty($leavefrom))
{
echo '<option value="" selected disabled>Select...</option>';
}
else{
echo '<option value="" selected disabled>Select...</option>';
$sql = "
SELECT distinct fullname FROM core_user LEFT JOIN lms_tran ON lms_tran.userid = core_user.userid where core_user.userid NOT IN (SELECT userid FROM lms_tran WHERE date_from BETWEEN '$leavefrom' AND '$leaveto' AND app_status = 'Approved') AND core_user.userid != 609 AND core_user.status = 'Y' ORDER by fullname ASC
";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="'.$row["userid"].'">'.$row["fullname"].'</option>';
}
}?>
</select>
</td>
</tr>
<?php endif; ?>
</table>
</form>
and this is javascript
function validateLeave(type)
{
var days= jQuery('#frm_days').val();
var from = jQuery('#lv_date_from').val();
var to = jQuery('#lv_date_to').val();
var relief = jQuery('#frm_userid2').val();
if (type != 'check')
{
days_incorrect = true;
}
if (type == 'days' || type == 'from')
{
to = '';
relief = '';
}
if (type == 'to')
{
days = '';
}
if (
(
(days == '' ? 0 : 1) +
(to == '' ? 0 : 1) +
(from == '' ? 0 : 1)
) < 2
)
{
days_correct = false;
return;
}
days = parseFloat(days);
jQuery('#frm_days').val(days);
jQuery('.control').attr('disabled', true);
jQuery('#lv_loading').show();
jQuery.post('index.php?_m=lms&_a=leave_validate&from='+from+'&to='+to, {from:from,to:to,days:days}, function(res){
eval('var r = '+res+';');
if (r.status == 'OK')
{
days_incorrect = false;
if (r.to)
{
jQuery('#lv_date_to').val(r.to);
}
if (r.from)
{
jQuery('#lv_date_from').val(r.from);
}
if (r.days)
{
jQuery('#frm_days').val(r.days);
}
}
else if (r.status == 'HOLIDAYERROR')
{
alert('Incorrect leave start date. Leave start date can not fall into Weekend or Public Holidays');
days_incorrect = true;
}
else
{
alert('Incorrect leave period. Please check back Leave Start, Leave End and Leave Days')
days_incorrect = true;
}
jQuery('.control').attr('disabled', false);
jQuery('#lv_loading').hide();
});
}
and i could'nt get the value return in php code as i hv pass value via jQuery.

No, you can't. The only way to do something interactive is to do it with javascript if you the to see it. If it doesn't matter you can do this on the server by assigning the second variable with the value of the first.

Related

How do I make filters work together using AJAX, PHP and MySQL

I have this table that shows a list of users and I'm trying to create some filters with selectbox to filter with some parameters. I'm building this table with a PHP script that I call with AJAX. This AJAX is activated when the user click on one of this selectbox.
This are the filters:
<div class="col-lg-6">
<select class="form-control filter" name="category" id="category">
<option>All</option>
<option>Abraham</option>
<option>Kevin</option>
<option>Eric</option>
</select>
</div>
<div class="col-lg-6">
<select class="form-control filter" name="datePeriod" id="datePeriod">
<option>Today</option>
<option>Yesterday</option>
<option>Last 7 days</option>
<option>Last month</option>
<option>Last year</option>
</select>
</div>
<div class="col">
<div id="output"></div>
</div>
and this is the AJAX:
$(document).ready(function(){
$('.filter').each(function () {
$(this).change(function(){
var filters = $(this).val();
var dataString = "filters="+filters;
$.ajax({
type: "GET",
url: "processes/filters.php",
data: dataString,
success: function(result){
$("#output").html(result);
}
});
});
});
$("#datePeriod").trigger("change");
});
This is my PHP code:
<?php
//Getting $datePeriod value for query
if(isset($_GET['filters']) && $_GET['filters'] == "Today" && $_GET['filters'] == "All"){
$datePeriod = 'AND DATE(VISIT_DATE) = CURDATE()';
$category = "";
}
if(isset($_GET['filters']) && $_GET['filters'] == "Yesterday"){
$datePeriod = 'AND VISIT_DATE >= DATE(NOW()) - INTERVAL 1 DAY';
}
if(isset($_GET['filters']) && $_GET['filters'] == "Last 7 days"){
$datePeriod = 'AND VISIT_DATE >= DATE(NOW()) - INTERVAL 7 DAY';
}
if(isset($_GET['filters']) && $_GET['filters'] == "Last month"){
$datePeriod = 'AND VISIT_DATE >= DATE(NOW()) - INTERVAL 1 MONTH';
}
if(isset($_GET['filters']) && $_GET['filters'] == "Last year"){
$datePeriod = 'AND VISIT_DATE >= DATE(NOW()) - INTERVAL 1 YEAR';
}
//Getting $category value for query
if(isset($_GET['filters']) && $_GET['filters'] == "All"){
$category = "";
}
if(isset($_GET['filters']) && $_GET['filters'] == "Abraham"){
$category = "AND VISIT_REASON='Abraham'";
}
if(isset($_GET['filters']) && $_GET['filters'] == "Kevin"){
$category = "AND VISIT_REASON='Kevin'";
}
if(isset($_GET['filters']) && $_GET['filters'] == "Eric"){
$category = "AND VISIT_REASON='Eric'";
}
include('conn.php');
mysqli_set_charset($conn, 'utf8');
$orderBy = 'ORDER BY VISIT_DATE DESC';
$sql = "SELECT * FROM queue WHERE ATTENDED='1' ".$category." ".$datePeriod." ".$orderBy." ";
$result = mysqli_query($conn, $sql);
//$ID = 'ID';
$GUEST_NAME = 'GUEST_NAME';
$GUEST_PHONE = 'GUEST_PHONE';
$VISIT_REASON = 'VISIT_REASON';
$VISIT_DATE = 'VISIT_DATE';
echo '<table class="table table-striped">';
echo "<tr>";
//echo '<th scope="col">ID</th>';
echo '<th scope="col">Name</th>';
echo '<th scope="col">Phone</th>';
echo '<th scope="col">Attended by</th>';
echo '<th scope="col">Visit Date</th>';
echo "</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
//echo "<td>$row[$ID]</td>";
echo "<td>$row[$GUEST_NAME]</td>";
echo "<td>$row[$GUEST_PHONE]</td>";
echo "<td>$row[$VISIT_REASON]</td>";
echo "<td style='text-transform:uppercase;'>".date('M-d-Y g:i a', strtotime(str_replace('-','/', $row['VISIT_DATE'])))."</td>";
echo "</tr>";
}
} else {
echo "<td style='text-transform: none;'>No records to show.</td>";
}
echo '</table>';
mysqli_close($conn);
?>
My problem is that I can't figure out how to build the correct conditions so the two filters can work together. I need that when the user select one filter the query build it self considering the value of the other one.
When I select the category filter I get "Undefined variable: datePeriod".
When I select the datePeriod filter I get "Undefined variable: category".
I do not know if I'm doing it the wrong way. Maybe I'm not building the query in the correct way. I will appreciate any help or guidance.
You need to send both filters every time each of them changes:
JS:
$(document).ready(function(){
$('.filter').change(function(){
$.ajax({
type: "GET",
url: "processes/filters.php",
data: {
category: $('#category').val(),
datePeriod: $('#datePeriod').val(),
},
success: function(result){
$("#output").html(result);
}
});
});
$("#datePeriod").trigger("change");
});
PHP:
<?php
if($_GET['category'] == "All"){
$category = "";
} else if($_GET['category'] == "Abraham"){
$category = "AND VISIT_REASON='Abraham'";
} else if( $_GET['category'] == "Kevin"){
$category = "AND VISIT_REASON='Kevin'";
} else if($_GET['category'] == "Eric"){
$category = "AND VISIT_REASON='Eric'";
} else {
$category = '';
}
if($_GET['datePeriod'] == "Today"){
$datePeriod = 'AND DATE(VISIT_DATE) = CURDATE()';
} else if($_GET['datePeriod'] == "Yesterday"){
$datePeriod = 'AND VISIT_DATE >= DATE(NOW()) - INTERVAL 1 DAY';
} else if($_GET['datePeriod'] == "Last 7 days"){
$datePeriod = 'AND VISIT_DATE >= DATE(NOW()) - INTERVAL 7 DAY';
} else if($_GET['datePeriod'] == "Last month"){
$datePeriod = 'AND VISIT_DATE >= DATE(NOW()) - INTERVAL 1 MONTH';
} else if($_GET['datePeriod'] == "Last year"){
$datePeriod = 'AND VISIT_DATE >= DATE(NOW()) - INTERVAL 1 YEAR';
} else {
$datePeriod = '';
}
// the rest of the file
Whilst not a complete solution to your question the following ought to give you a good idea about how to complete the solution. I do not use jQuery so below have opted to use a simple ajax function. the bit I think you might be most interested in is the states variable which stores the name/value of any select menu used on the page ~ found by querying the DOM. The values stored in that variable are then used in the ajax request so you are always going to have all values available in the PHP code and not suffer from the errors you mentioned above.
You could copy this and run it "As-is" to see how it works and then adopt, adapt and improve to suit your needs.
<?php
/* Process ajax request */
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && $_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest' ){
ob_clean();
$args=array(
'category' => FILTER_SANITIZE_STRING,
'datePeriod' => FILTER_SANITIZE_STRING
);
$_GET = filter_input_array( INPUT_GET, $args );
extract( $_GET );
echo $category . ' ' . $datePeriod;
/* process these variables to construct your sql query */
exit();
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>ajax filtering idea</title>
<script>
document.addEventListener('DOMContentLoaded',function(){
/* Create a nodelist collection of select menus according to class "filter" */
var col=document.querySelectorAll( 'select.filter' );
/* Placeholder object to store the state of any menu that is changed */
var states={};
/* Iterate through nodelist collection and assign event listener to each */
Array.prototype.slice.call( col ).forEach( function( menu ){
/* store initial state of all menus */
states[ menu.name ]=menu.value;
menu.addEventListener('change',function(e){
/* store this menu name & value after change */
states[ e.target.name ]=e.target.value;
/* send ajax request */
ajax.call( this, location.href, states, callback )
},false );
});
},false);
/* basic ajax function */
function ajax( url, payload, callback ){
var xhr=new XMLHttpRequest();
var params=[];
for( var p in payload )params.push( p + '=' + payload[ p ] );
xhr.onreadystatechange=function(){if( this.readyState==4 && this.status==200 )callback.call( this, this.response );};
xhr.open( 'GET', url + '?' + params.join('&'), true );
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( null );
}
/* very simple callback */
var callback=function(r){
document.getElementById('output').innerHTML=r
};
</script>
</head>
<body>
<div class="col-lg-6">
<select class="form-control filter" name="category" id="category">
<option>All</option>
<option>Abraham</option>
<option>Kevin</option>
<option>Eric</option>
</select>
</div>
<div class="col-lg-6">
<select class="form-control filter" name="datePeriod" id="datePeriod">
<option>Today</option>
<option>Yesterday</option>
<option>Last 7 days</option>
<option>Last month</option>
<option>Last year</option>
</select>
</div>
<div class="col">
<div id="output"></div>
</div>
</body>
</html>

PHP Quotation Calculator

newbie here...
Im trying to create a simple php quote calculator, I've got a quantity field and 2 lest menus.
What I'm trying to do is multiply the quantity by a assigned value of the one list item added to quantity multiplied by an assigned value of the other list item, no combination of the two list items will be the same.
I've got this to work fine except once one of the list items is the same the calculation is thrown off...
if( isset( $_REQUEST['calculate'] ))
{
$type=$_REQUEST['type'] && $lam=$_REQUEST['lam'];
if($type=="One Side Colour" && $lam=="None")
{
$add1 = $_REQUEST['quantity'];
$res= $add1*.70+$add1*0;
}
if($type=="One Side Colour" && $lam=="One Side")
{
$add1 = $_REQUEST['quantity'];
$res= $add1*.70+$add1*.15;
}
if($type=="Two Sides Colour" && $lam=="None")
{
$add1 = $_REQUEST['quantity'];
$res= $add1*1.4+$add1*0;
}
the last "if" confuses the calculation
Any ideas to get around this?
Some code fix ups:
if( isset( $_REQUEST['calculate'] )){
$type = $_REQUEST['type'];
$lam = $_REQUEST['lam'];
$add1 = (int)$_REQUEST['quantity']; // Casts the value to Integer
if($type=="One Side Colour" && $lam=="None"){
$res = ($add1 * .70) + ($add1 * 0); // Unclear 0 * anything = 0
}
if($type=="One Side Colour" && $lam=="One Side"){
$res = ($add1 * .70) + ($add1 * .15);
}
if($type=="Two Sides Colour" && $lam=="None"){
$res = ($add1 * 1.4) + ($add1 * 0); // Another 0 issue?
}
}
Added a few ( ) to outline the order or operations. Also don't get why you multiply by 0...
Edit
After some of your comments, this would be condensed some:
if( isset( $_REQUEST['calculate'] )){
$type = $_REQUEST['type'];
$lam = $_REQUEST['lam'];
$add1 = (int)$_REQUEST['quantity'];
if($type == "One Side Colour") {
$res = ($add1 * .70) + ($add1 * ($lam == "One Side" ? .15 : 0));
} elseif($type == "Two Sides Colour") {
$res = ($add1 * 1.4);
}
}
Edit 2
Looked at your HTML and have a few suggestions:
<table width="450" cellpadding="5" border="0" align="center">
<tbody><tr>
<td>Quantity</td>
<td>
<input type="text" size="5" name="quantity" value="<?php echo (isset($_REQUEST['quantity'])?$_REQUEST['quantity']:''); ?>"> Business Cards</td>
</tr>
<tr>
<td>Number of Sides</td>
<td>
<select name="type">
<?php
$type = array(
"One Side Colour",
"Two Sides Colour",
"One Side Black/White",
"One Side Colour/Other Side Black/White"
);
foreach($type as $o){
if(isset($_REQUEST['type']) && $_REQUEST['type'] == $o){
echo " <option selected='selected'>$o</option\r\n";
} else {
echo " <option>$o</option>\r\n";
}
}
?>
</select></td>
</tr>
<tr>
<td>Lamination</td>
<td>
<select name="lam">
<?php
$lam = array(
"None",
"One Side",
"Both Sides"
);
foreach($lam as $l){
if(isset($_REQUEST['lam']) && $_REQUEST['lam'] == $l){
echo " <option selected='selected'>$l</option\r\n";
} else {
echo " <option>$l</option>\r\n";
}
?>
</select></td>
</tr>
<tr>
<td> </td>
<td><input type="Submit" value="calculate" name="calculate"></td>
</tr>
<tr><td>Price</td>
<td style="font-weight:bolder;font-size: 20px;"><?php echo (isset($res)?"P$res":""); ?></td>
</tr>
<tr>
</tr></tbody></table>
This will allow your form to retain the selections each time the price is calculated.
Hope this will help you...
if( isset( $_REQUEST['calculate'] )){
$type = $_REQUEST['type'];
$lam = $_REQUEST['lam'];
$add1 = (int)$_REQUEST['quantity'];
if($type == "One Side Colour") {
$res = ($add1 * .70) + ($add1 * ($lam == "One Side" ? .15 : 0));
} elseif($type == "Two Sides Colour") {
$res = ($add1 * 1.4);
}}
Also, I've created a calculator, regarding auto transport quote
If you need any help and code of that calculator than contact me.

PHP : Variable does not show value in Function while shows directely

I have a problem in my code. I post some field data for addsms.php file.
<form id="signup" Name="signup" method="post" action="addsms.php?act=add"> <h1>SMS Detail Here!</h1>
User Refrence Code:<input name="rfcd" type ="text" class="a" id="rfcd" placeholder="Enter Refrence Code" /><br>
Total SMS Count: &nbsp &nbsp <input name="smsc" type ="text" class="a" id="smsc" placeholder="Enter SMS Count" /><br>
Total SMS Amount: <input name="amnt" type ="text" class="a" id="amnt" placeholder="Enter SMS Amount" /><br>
<input type ="submit" Name="submit" value="Submit" class="outset" />
</form>
addsms.php
<?php
require_once("./include/connect.php");
require_once("./include/fg_membersite.php");
if($_GET['act'] == 'add')
{
$rf_cd = $_POST['rfcd'];
$sms_c = $_POST['smsc'];
$am_nt = $_POST['amnt'];
// echo $rf_cd;
// exit;
//I can Get value of variable "$rf_cd" at above line. while not able to get value in any function,
if ($rf_cd == NULL || $sms_c == NULL || $am_nt == NULL )
{
header("Location:sms.php?field=miss");
}
else
if(checkref_id_from_user() == true && checkref_id_from_user_data() == true )
{
$get_detail = "select total_sms, total_sms_amount from user_data where ref_id = '$rf_cd'";
$res1 = Run($get_detail);
if(mysql_num_rows($res1) > 0){
while ($rows = mysql_fetch_object($res1)) {
$srn++;
$sms_oldcont = $rows->total_sms;
$sms_amnt_oldcont = $rows->total_sms_amount;
}
}
$inqry = "UPDATE user_data SET total_sms = '$sms_c' + '$sms_oldcont', total_sms_amount ='$am_nt'+ '$sms_amnt_oldcont' where ref_id = '$rf_cd' ";
$resinqry = Run($inqry);
if(!$resinqry)
{
echo $resinqry;
}
else
{
header("Location:sms.php?add=done");
}
}
else
if(checkref_id_from_user() == true && checkref_id_from_user_data() == false)
{
$inqry = "Insert into user_data (ref_id,total_sms,total_sms_amount) VALUES('$rf_cd','$sms_c','$am_nt')";
$resinqry = Run($inqry);
if(!$resinqry)
{
echo $resinqry;
}
else
{
header("Location:sms.php?add=done");
}
}
// if($result && mysql_num_rows($result) > 0 && )
else
{
header("Location:sms.php?refid=notavailable");
}
}
else
{
echo 'oh';
//header("Location:sms.php?refid=notavailable");
}
function checkref_id_from_user(){
$qry = "select ref_id from user where ref_id='".$rf_cd."'";
echo $qry;
$result = Run($qry);
echo $result;
exit;
if($result && mysql_num_rows($result) > 0)
{
return true;
}
return false;
}
function checkref_id_from_user_data()
{
$checkrefid = "select ref_id from user_data where ref_id = '$rf_cd'";
$res = Run($checkrefid);
if(mysql_num_rows($res) > 0)
{
return true;
}
return false;
}
?>
I can Get value of variable "$rf_cd" at any where in if condition. while not able to get value in any function, "$rf_cd" I wanna use this value in my functions to get info from database.
$checkrefid = "select ref_id from user_data where ref_id = '$rf_cd'";
echo $checkrefid;
exit
Above query shows the result that "Select ref_id from user_data where ref_id = '' ".
while this should show the value of variable $rf_cd.
Close your if statement } before your functions are read. And for good form, I always list functions at the top of my scripts.
You can just declare $rf_cd as argument of those functions and pass it when calling them (best solution).
Also you can use "global" keyword to get an access to a $rf_cd variable from global scope.
function checkref_id_from_user(){
global $rf_cd;
...
}
function checkref_id_from_user_data() {
global $rf_cd;
...
}
Have you tried using global in the function?
If you wish for a function to have access to passive variables, you need to define them.
fx
myFunction() {
global $LoggedUser, $OtherGlobalVars
}

If-statement while loop stopping after first row

I have the following PHP script that takes the selected $empfullname from the user and prints 'timecard_html' based on the selection. I am trying to make it capable that if they select 'All' then the script prints out all of the employees in the list each in a separate timecard_html. Here is the php script:
if ($empfullname == 'All') {
$query = "select empfullname from ".$db_prefix."employees";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result)) {
$empfullname = ("".$row['empfullname']."");
print timecard_html($empfullname, $local_timestamp_in_week);
unset($empfullname);
}
} else {
print timecard_html($empfullname, $local_timestamp_in_week);
}
Also, here is timecard_html in case you need to see it:
function timecard_html($empfullname, $local_timestamp_in_week) {
// Return html of employee's timecard.
global $show_display_name, $one_week;
// SQL search parameters for one work week.
$begin_local_timestamp = work_week_begin($local_timestamp_in_week);
$end_local_timestamp = $begin_local_timestamp + $one_week;
// Define helper functions for printing timecard header, footer, and for printing every row.
function print_header($tc) {
// Print timecard html header.
global $overtime_week_limit, $timecard_display_running_total;
$overtime_col = $overtime_week_limit > 0 ? "\n <th align=\"center\" class=\"ovt\" title=\"Overtime hours\">OT</th>" : '';
$total_col = $timecard_display_running_total == "yes" ? "\n <th align=\"center\" class=\"total\" title=\"Running total of regular work hours and overtime to date.\">Total</th>" : '';
print <<<End_Of_HTML
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
<thead>
<tr>
<th align="left">In/Out</th>
<th align="center">Time</th>
<th align="center">Date</th>
<th align="center" class="hrs" title="Regular work hours.">Hrs</th>$overtime_col$total_col
<th align="left" class="notes">Notes</th>
</tr>
</thead>
<tbody>
End_Of_HTML;
}
function print_row($tc) {
// Configuration variables.
global $timefmt, $datefmt;
global $overtime_week_limit, $timecard_list_punch_outs, $timecard_display_hours_minutes;
global $timecard_hours_include_overtime, $timecard_display_running_total;
static $print_count = 0;
if (($tc->in_or_out == 1) || $timecard_list_punch_outs == 'yes') {
$h_color = htmlentities($tc->row['color']);
$h_inout = htmlentities($tc->row['inout']);
$h_time = date($timefmt, $tc->start_time);
$h_date = date($datefmt, $tc->start_time);
if ($timecard_display_hours_minutes == "yes") {
$h_hours = hrs_min((($timecard_hours_include_overtime == "yes") ? ($tc->hours + $tc->overtime) : $tc->hours));
$h_overtime = hrs_min($tc->overtime);
$h_total = hrs_min(($tc->week_hours + $tc->overtime_hours));
}
else {
$h_hours = sprintf("%01.02f",(($timecard_hours_include_overtime == "yes") ? ($tc->hours + $tc->overtime) : $tc->hours));
$h_overtime = sprintf("%01.02f",$tc->overtime);
$h_total = sprintf("%01.02f",($tc->week_hours + $tc->overtime_hours));
}
$h_notes = htmlentities($tc->row['notes']);
if ($tc->in_or_out != 1) {
// Don't display hours on "out" records.
$h_hours = $h_overtime = $h_total = '';
}
$row_class = (++$print_count % 2) ? 'odd' : 'even';
$overtime_col = $overtime_week_limit > 0 ? "\n <td align=\"right\" class=\"ovt\">$h_overtime</td>" : '';
$total_col = $timecard_display_running_total == "yes" ? "\n <td align=\"right\" class=\"total\">$h_total</td>" : '';
print <<<End_Of_HTML
<tr class="display_row $row_class">
<td align="left" class="job_code" style="color:$h_color">$h_inout</td>
<td align="right">$h_time</td>
<td align="right">$h_date</td>
<td align="right" class="hrs">$h_hours</td>$overtime_col$total_col
<td align="left" class="notes">$h_notes</td>
</tr>
End_Of_HTML;
}
}
function print_footer($tc) {
global $timecard_display_running_total, $timecard_hours_include_overtime;
global $timecard_display_hours_minutes, $overtime_week_limit;
// Set flag to print paragraph of totals if they're not already obvious.
$print_totals = ($timecard_display_running_total == "yes" || $timecard_hours_include_overtime != "yes") ? true : false;
$h_total_hours = sprintf("%01.02f",($tc->week_hours+$tc->overtime_hours));
$h_totals = ($print_totals) ? "\n<p>Total for week: ".hrs_min($tc->week_hours + $tc->overtime_hours)." ($h_total_hours hours)</p>" : '';
$h_ovt_total_hours = sprintf("%01.02f",$tc->overtime_hours);
$h_overtime_totals = ($print_totals && $tc->overtime_hours > 0) ? "\n<p>Total overtime: ".hrs_min($tc->overtime_hours)." ($h_ovt_total_hours hours)</p>" : '';
$h_day_total_hours = sprintf("%01.02f",$tc->today_hours);
$h_today_hours = ($tc->today_hours !== null) ? "<p>Total today: ".hrs_min($tc->today_hours)." ($h_day_total_hours hours)</p>" : '';
if ($timecard_display_running_total != "yes") {
// Print row of totals
$total_hours = $timecard_hours_include_overtime == "yes" ? ($tc->week_hours+$tc->overtime_hours) : $tc->week_hours;
$h_hours = $timecard_display_hours_minutes == "yes" ? hrs_min($total_hours) : $h_total_hours;
$overtime_col = $overtime_week_limit > 0 ? "\n <td align=\"right\" class=\"ovt\">".($timecard_display_hours_minutes == "yes" ? hrs_min($tc->overtime_hours) : $h_ovt_total_hours)."</td>" : '';
$total_col = $timecard_display_running_total == "yes" ? "\n <td align=\"right\" class=\"total\">".($timecard_display_hours_minutes == "yes" ? hrs_min($tc->week_hours+$tc->overtime_hours) : $h_total_hours)."</td>" : '';
print <<<End_Of_HTML
<tr class="total_row">
<td align="left"></td>
<td align="right"></td>
<td align="right"></td>
<td align="right" class="hrs">$h_hours</td>$overtime_col$total_col
<td align="left" class="notes"></td>
</tr>
End_Of_HTML;
}
print <<<End_Of_HTML
</tbody>
</table>
End_Of_HTML;
if ($timecard_display_running_total == "yes" || $timecard_hours_include_overtime != "yes" || $h_today_hours) {
// Add totals text if totals are not already displayed or if summing the hours column is confusing.
print <<<End_Of_HTML
<div class="totals">
$h_today_hours$h_totals$h_overtime_totals
</div>
End_Of_HTML;
}
}
// End of helper function definitions.
// Print timecard page header.
$h_name_header = htmlentities( ($show_display_name == 'yes' ? get_employee_name($empfullname) : $empfullname) );
$begin_date = date('l F j, Y',$begin_local_timestamp);
print <<<End_Of_HTML
<div id="punchclock" class="timecard">
<h2>Timecard</h2>
<h3>$h_name_header</h3>
<h4>Week beginning $begin_date</h4>
End_Of_HTML;
// Print timecard.
$tc = new Timecard($empfullname,$begin_local_timestamp, $end_local_timestamp);
list($row_count, $total_hours, $overtime_hours, $today_hours) = $tc->walk(print_header, print_row, print_footer);
if ($row_count <= 0) print error_msg("No records were found.");
// Print timecard page footer.
print <<<End_Of_HTML
</div> <!-- timecard -->
End_Of_HTML;
}
?>
As of right now if 'All' is selected it prints the results for the first employee in the table, but not any of the other ones. Also, if I just print ("".$row['empfullname']."") it prints out all the employees. Do I maybe need to use a for each loop instead of a while loop?
Thanks in advance.
Your problem is that your are defining functions in your function. That will work the first time when you call your function, but the second time it will cause a fatal error as the function is already defined.
See a simple example here.
Moving the inner function declarations out of the main function should solve this specific problem.
You should also always enable error handling and displaying while developing. In this case you would have caught the problem inmediately.
Just put this at the top of the main script:
ini_set('display_errors',1);
error_reporting(E_ALL | E_STRICT);

append checkbox options to textarea that is load from database php

a user checks the type of zones and choose the type of change; this script will load the change description details from a database into a textarea field in html.
Then what I want to happend next is:
the descriptions text gets appended with the different zones the changes will take place within the html description textarea. I do not want the zones to be appended to my description data in my database. The issue is the appending of the different zones to the description field is not working..
I am using javascript to append the text. Can someone advice me why I need to correct my code?
<html>
<head>
<script language="JavaScript" type="text/javascript">
// who says we found anything? Maybe this id does not even exist.
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?change_type='+value;
data_center = [],
data_centers = "";
inputs = document.getElementsByTagName('input');
for (var x = 0, len = inputs.length; x < len; x++) {
{
if (inputs[x].type == "checkbox" && inputs[x].name == 'data_center[]') {
if (inputs[x].checked === true) {
data_center.push(inputs[x].value);
}
}
}
data_centers = (data_center.length > 0 ? ': ' + data_center.join(', ') : '') + '.';
document.getElementById('description').value += data_centers;
document.getElementById('impact').value += data_centers;
}
}
</script>
</head>
<?php
require_once("db_handler.php");
// $_REQUEST is both _GET and _POST
if (isset($_REQUEST['change_type'])) {
$change_type = mysql_real_escape_string($_REQUEST['change_type']);
} else {
$change_type = False;
}
$query = "SELECT `changeID` , `changeName` FROM `change`;";
$exec = mysql_query($query); // You need to be already connected to a DB
if (!$exec) {
trigger_error("Cannot fetch data from change table: " . mysql_error(), E_USER_ERROR);
}
if (0 == mysql_num_rows($exec)) {
trigger_error("There are no changes in the 'change' table. Cannot continue: it would not work. Insert some changeids and retry.", E_USER_ERROR);
}
$options = '';
while($row = mysql_fetch_array($exec))
{
// if the current pageid matches the one requested, we set SELECTED
if ($row['changeID'] === $change_type)
// who says we found anything? Maybe this id does not even exist.
$sel = 'selected="selected"';
else
{
// If there is no selection, we use the first combo value as default
if (False === $change_type)
$change_type = $row['changeID'];
$sel = '';
}
$options .= "<option value=\"{$row['changeID']}\" $sel>{$row['changeName']}</option>";
}
mysql_free_result($exec);
if (isset($_POST['description']))
{
$change_data = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO change ( changeID, description ) VALUE '{$change_type}', '{$change_data}' ) ON DUPLICATE KEY UPDATE description=VALUES(description);";
if (!mysql_query($query))
trigger_error("An error occurred: " . mysql_error(), E_USER_ERROR);
}
$query = "SELECT `changeID` , `changeName` FROM `change`;";
$exec = mysql_query($query); // You need to be already connected to a DB
// abbreviated unchanged code.
$query = "SELECT `description`, `impact` FROM `change` WHERE `changeID`='{$change_type}';";
$exec = mysql_query($query);
if (mysql_num_rows($exec) > 0)
{
// if it does, we're inside a textarea and we directly output the text
$row = mysql_fetch_array($exec);
$textareaDescription = $row['description'];
$textareaImpact = $row['impact'];
} else {
$textareaDescription = '';
$textareaImpact = '';
}
mysql_free_result($exec);
?>
<body bgcolor="white">
<form name="changeform" method="post" action="email_form.php">
<table>
<tr valign="top">
<td><b>Data Center</b></td>
<td><input name="data_center[]" type="checkbox" value="[Zone10]"/>[Zone10]
<input name="data_center[]" type="checkbox" value="[Zone11]"/>[Zone11]
</td>
</tr>
<tr valign="top">
<td><b>Change Type</b></td>
<td><select id="change_type" name="change_type" onChange="getData(this)""><?php print $options; ?></select></td>
</tr>
<tr valign="top">
<td><b>Description</b></td>
<td><textarea name="description" id="description" cols="50" rows="10"><?php print $textareaDescription; ?></textarea></td>
</tr>
<tr valign="top">
<td><b>Service Impact</b></td>
<td><textarea name="impact" id="impact" cols="50" rows="10"><?php print $textareaImpact; ?></textarea></td>
</tr>
<tr valign="top">
<td align="center" colspan="2"><input type="submit" value="submit change" /></td>
</tr>
</table>
</form>
</body>
</html>
The following lines look like there might be something wrong:
for (var x = 0, len = inputs.length; x < len; x++)
{
{
Unless that is syntax that I'm just not familiar with.
Is there any way you could show us the actual code, running? Looking at something like this is a bit hard to digest without being able to see it in action.

Categories