How to update data from dynamically created table to database in php - javascript

I have create a table using php dynamically. But i need to update some of the cell value depending on user input. But i can't figure out how to do that. my codes are given below.
I have found a way to make names an array is to use [] in names attribute from stackoverflow. but it didn't work for me.If i echo $_POST['std_name'] in while loop or outside of loop only the last row of student name is counted. Please Someone help. I am stuck here for 3 days.
<form action="" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Student Name</th>
<th>Student Father Name</th>
<th>Student Mother Name</th>
<th>Student Parents Mobile Number</th>
<th>Student Mobile Number</th>
<th>Student Batch Name</th>
<th>Student College Name</th>
<th>Student Gender</th>
<th>Student Picture</th>
<th>Student Admit Date</th>
<th>January</th>
<th>February</th>
<th>March</th>
<th>April</th>
<th>May</th>
<th>June</th>
<th>July</th>
<th>August</th>
<th>September</th>
<th>October</th>
<th>November</th>
<th>December</th>
</tr>
<tr>
<?php
$host="localhost";
$username="root";
$password="";
$db="paragon_first_year";
$qry="select * from `student_info`";
$con=mysqli_connect($host,$username,$password);
mysqli_select_db($con,$db);
$res=mysqli_query($con,$qry);
if(mysqli_num_rows($res)>0){
while($dt=mysqli_fetch_array($res)){?>
<td><input type="text" name="std_id[]" value="<?php echo $dt['std_id']?>"></td>
<td><input type="text" name="std_name[]" value="<?php echo $dt['std_name']?>"></td>
<td><input type="text" name="std_father_name[]" value="<?php echo $dt['std_father_name']?>"></td>
<td><input type="text" name="std_mother_name[]" value="<?php echo $dt['std_mother_name']?>"></td>
<td><input type="text" name="std_parent_mob[]" value="<?php echo $dt['std_parents_mob_no']?>"></td>
<td><input type="text" name="std_mob[]" value="<?php echo $dt['std_mob_no']?>"></td>
<td><?php echo $dt['std_batch_name'] ?></td>
<td><?php echo $dt['std_college_name'] ?></td>
<td><?php echo $dt['std_gender'] ?></td>
<td><img style="height:100px;width:100px;" src="uploadImage/<?php echo $dt['std_name']."_".$dt['std_pic'] ?>" alt=""></td>
<td><?php echo $dt['std_admit_date'] ?></td>
<td><input type="text" name="jan[]" value="<?php echo $dt['january']?>"></td>
<td><input type="text" name="feb[]" value="<?php echo $dt['february']?>"></td>
<td><input type="text" name="mar[]" value="<?php echo $dt['march']?>"></td>
<td><input type="text" name="apr[]" value="<?php echo $dt['april']?>"></td>
<td><input type="text" name="may[]" value="<?php echo $dt['may']?>"></td>
<td><input type="text" name="jun[]" value="<?php echo $dt['june']?>"></td>
<td><input type="text" name="jul[]" value="<?php echo $dt['july']?>"></td>
<td><input type="text" name="aug[]" value="<?php echo $dt['august']?>"></td>
<td><input type="text" name="sep[]" value="<?php echo $dt['september']?>"></td>
<td><input type="text" name="oct[]" value="<?php echo $dt['october']?>"></td>
<td><input type="text" name="nov[]" value="<?php echo $dt['november']?>"></td>
<td><input type="text" name="dec[]" value="<?php echo $dt['december']?>"></td>
</tr><?php
}
}
?>
</table>
<center>
<input type="submit" name="submit" value="Update Data">
</center>
</form>
</body>
my table is showing nicely
hope someone help. Thanks in advance.

You can use array keys to pass information. In this example, the first key is the database primary key, and the second key is the variable name.
The resulting array would look something like this:
$row[123][std_name] = 'joe';
$row[123][std_father_name] = 'bob';
... etc
$row[124][std_name] = 'sally';
$row[124][std_father_name] = 'john';
...etc
Then, as you iterate through the rows, you get the key (123) to use to update the database, as in where std_id=123.
Note: I have used prepared statements to show updating the database. This is essential. Never put variables in a query using concatenation ( i.e., "select * from table where id='$id'")
Lastly, note the structure. Start with PHP, no print or echo statements. This allows you to work with user input and then redirect. First initialize, then work with user input, then do page logic, and lastly get out of php and output the view (html)
This example is not copy and paste; it has things that need to be filled in, and probably debugged. It is merely intended to show the big picture.
<?php
// initialize
$host="localhost";
$username="root";
$password="";
$db="paragon_first_year";
$con=mysqli_connect($host,$username,$password);
// a simple wrapper to make the prepared query more manageable
// see https://phpdelusions.net/mysqli/mysqli_connect#helper
function prepared_query($mysqli, $sql, $params, $types = "")
{
$types = $types ?: str_repeat("s", count($params));
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
}
// work with user input
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$dataRows = (array)$_POST['data'];
foreach($dataRows as $id=>$data) {
$sql = "INSERT INTO student_info SET std_name=?, std_father_name=?, " .
// etc .
"WHERE std_id=?";
$params = array(
$data['std_name'],
$data['std_father_name'],
// etc...
$id
);
// this does the prepare, bind, and execute... Yes, I could just do the
// bind and execute here, but the time savings isn't worth the trouble.
$stmt = prepared_query($con, $sql, $params);
}
// always redirect after a POST
header('Location: /path/to/next/page/or/this/page');
die;
}
// no user input; ok to use plain old query.
$qry="select * from `student_info`";
mysqli_select_db($con,$db);
$res=mysqli_query($con,$qry);
?>
<html>
...
<form action="" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Student Name</th>
<th>Student Father Name</th>
<th>Student Mother Name</th>
<th>Student Parents Mobile Number</th>
<th>Student Mobile Number</th>
<th>Student Batch Name</th>
<th>Student College Name</th>
<th>Student Gender</th>
<th>Student Picture</th>
<th>Student Admit Date</th>
<th>January</th>
<th>February</th>
<th>March</th>
<th>April</th>
<th>May</th>
<th>June</th>
<th>July</th>
<th>August</th>
<th>September</th>
<th>October</th>
<th>November</th>
<th>December</th>
</tr>
<!-- don't need mysqli_num_rows; the while won't loop if no results -->
<?php while($dt=mysqli_fetch_array($res)): ?>
<tr>
<td><?= $dt['std_id'] ?></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_name']" value="<?= $dt['std_name'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_father_name']" value="<?= $dt['std_father_name'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_mother_name']" value="<?= $dt['std_mother_name'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_parent_mob']" value="<?= $dt['std_parents_mob_no'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_mob']" value="<?= $dt['std_mob_no'] ?>"></td>
<td><?= $dt['std_batch_name'] ?></td>
<td><?= $dt['std_college_name'] ?></td>
<td><?= $dt['std_gender'] ?></td>
<td><img style="height:100px;width:100px;" src="uploadImage/<?= $dt['std_name']."_".$dt['std_pic'] ?>" alt=""></td>
<td><?= $dt['std_admit_date'] ?></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['jan']" value="<?= $dt['january'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['feb']" value="<?= $dt['february'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['mar']" value="<?= $dt['march'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['apr']" value="<?= $dt['april'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['may']" value="<?= $dt['may'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['jun']" value="<?= $dt['june'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['jul']" value="<?= $dt['july'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['aug']" value="<?= $dt['august'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['sep']" value="<?= $dt['september'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['oct']" value="<?= $dt['october'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['nov']" value="<?= $dt['november'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['dec']" value="<?= $dt['december'] ?>"></td>
<?php endwhile; ?>
</tr>
</table>
<center>
<input type="submit" name="submit" value="Update Data">
</center>
</form>
</body>

Related

Assign id or class to fetched data to work with in JavaScript

i have fetched data from database with PHP in while loop.i want to assign id or class to this data to work with it in javaScript individually with every id or class which are in table td.
For example
$i = 0 ;
if($result->rowCount() > 0)
{
while($row_pro = $prod->fetch())
{
$type = $row->type;
$brand = $row->brand;
$qty = $row->qty;
$total = $row->total;
$i++ ;
?>
<tr>
<td><input type="text" value="<?php echo $type; ?>" ></td>
<td><input type="text" value="<?php echo $brand; ?>" ></td>
<td><input type="text" value="<?php echo $qty; ?>" ></td>
<td><input type="text" value="<?php echo $total; ?>" ></td>
</tr>
<?php }} ?>
One solution would be to simply echo out your loop's index ($i) as a class:
<tr>
<td><input type="text" value="<?php echo $type; ?>" class="<?php echo $i; ?>"></td>
<td><input type="text" value="<?php echo $brand; ?>" class="<?php echo $i; ?>"></td>
<td><input type="text" value="<?php echo $qty; ?>" class="<?php echo $i; ?>"></td>
<td><input type="text" value="<?php echo $total; ?>" class="<?php echo $i; ?>"></td>
</tr>
Keep in mind that you can't do this for IDs, as IDs must be unique. Also, you don't actually need to do this in the first place, as you can directly target elements with JavaScript that have neither IDs nor classes. This is most commonly with .getElementsByTagName(), which returns a NodeList collection of elements. Here's an example of that:
let three = document.getElementsByTagName('td')[2];
console.log(three.innerHTML);
<table>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
</tr>
</table>

Dynamic Rows Form Submit

I have a decent sized form on my website which has an insert row button at the bottom, this adds rows to the bottom of the form to which I can also click the corresponding delete button to delete that single row to.
Screenshot of the bottom of the form
Now, the issue arises when I click the "Send" button. If I have added a few rows to the form and then click the "Send" button, the rows disappear from the form and so do their values. I want it so once I've added the rows and click the send button, the form keeps its state properly and keeps the rows that I previously added.
HTML Code can be found here:
<form name="contact" action="request-a-quote.php" method="POST">
<table class="form">
<thead>
<?php if (isset($form_error_message)) { echo $form_error_message; } ?>
<tr>
<th colspan="3">Company Information</th>
</tr>
</thead>
<tbody>
<tr>
<th class="desktop_only">Company Name *</th>
<td colspan="2"><input name="company_name" type="text" <?php if ($error_company_name=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Company Name"'; } ?> maxlength="45" value="
<?php if (isset($company_name)) echo $company_name; ?>"></td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="3">Contact Information</th>
</tr>
</thead>
<tbody>
<tr>
<th class="desktop_only">Contact person name *</th>
<td colspan="2"><input name="contact_person_name" type="text" <?php if ($error_contact_person_name=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Contact Person Name"'; } ?> maxlength="45" value="
<?php if (isset($contact_person_name)) echo $contact_person_name; ?>"></td>
</tr>
<tr>
<th class="desktop_only">Contact person e-mail *</th>
<td colspan="2"><input name="contact_person_email" type="email" <?php if ($error_contact_person_email=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Contact Person Email"'; } ?> size="40" value="
<?php if (isset($contact_person_email)) echo $contact_person_email; ?>" /></td>
</tr>
<tr>
<th class="desktop_only">Contact address *</th>
<td colspan="2"><input name="contact_address" type="text" <?php if ($error_contact_address=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Contact Address"'; } ?> maxlength="45" value="
<?php if (isset($contact_address)) echo $contact_address; ?>"></td>
</tr>
<tr>
<th class="desktop_only">Contact person phone *</th>
<td colspan="2"><input name="contact_person_phone" type="text" <?php if ($error_contact_person_phone=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Contact Person Phone"'; } ?> maxlength="45" value="
<?php if (isset($contact_person_phone)) echo $contact_person_phone; ?>"></td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="3">Boiler Information</th>
</tr>
</thead>
<tbody>
<tr>
<th class="desktop_only">Boiler brand / manufacturer *</th>
<td colspan="2"><input name="boiler_brand_manufacturer" type="text" <?php if ($error_boiler_brand_manufacturer=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Boiler brand / Manufacturer"'; } ?> maxlength="45" value="
<?php if (isset($boiler_brand_manufacturer)) echo $boiler_brand_manufacturer; ?>"></td>
</tr>
<tr>
<th class="desktop_only">Average annual fuel consumption (kW or £)</th>
<td colspan="2"><input name="average_annual_fuel_consumption" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Average annual fuel consumption (kW or £)"'; } ?> size="60" value="
<?php if (isset($average_annual_fuel_consumption)) echo $average_annual_fuel_consumption; ?>" ></td>
</tr>
<tr>
<th class="desktop_only">Current cost per kW (Pence)</th>
<td colspan="2"><input name="current_cost_per_kw" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Current cost per kW (Pence)"'; } ?> size="60" value="
<?php if (isset($current_cost_per_kw)) echo $current_cost_per_kw; ?>" ></td>
</tr>
<tr>
<th>Type of fuel</th>
<td colspan="2">
<select name="type_of_fuel">
<option value="0">Please Select...</option>
<option <?php if ($type_of_fuel == "Gas") echo "selected=selected" ?>>Gas</option>
<option <?php if ($type_of_fuel == "Oil") echo "selected=selected" ?>>Oil</option>
<option <?php if ($type_of_fuel == "LPG") echo "selected=selected" ?>>LPG</option>
<option <?php if ($type_of_fuel == "Other") echo "selected=selected" ?>>Other</option>
</select>
</td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="3">Boiler Capacity</th>
</tr>
</thead>
<tbody>
<tr>
<th>Type of boiler</th>
<td colspan="2">
<select name="type_of_boiler">
<option value="0">Please Select...</option>
<option <?php if ($type_of_boiler == "Thermostatically Controlled") echo "selected=selected" ?>>Thermostatically Controlled</option>
<option <?php if ($type_of_boiler == "CHP") echo "selected=selected" ?>>CHP</option>
<option <?php if ($type_of_boiler == "Steam") echo "selected=selected" ?>>Steam</option>
</select>
</td>
</tr>
<tr>
<th class="desktop_only">Total capacity</th>
<td colspan="2"><input name="total_capacity" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Total Capacity"'; } ?> size="60" value="
<?php if (isset($total_capacity)) echo $total_capacity; ?>" ></td>
</tr>
<tr>
<th class="desktop_only">Boiler capacity</th>
<td colspan="2"><input name="boiler_capacity" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Boiler Capacity"'; } ?> size="60" value="
<?php if (isset($boiler_capacity)) echo $boiler_capacity; ?>" ></td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="3">Required Measurements (up to 4 meters)</th>
</tr>
</thead>
<tbody class="row">
<tr>
<td colspan="3" class="center">
<img src="images/required-measurements.jpg" alt="Required Measurements" />
</td>
</tr>
</tbody>
</table>
<table id="addrows">
<thead>
<tr>
<th></th>
<th>Circumference</th>
<th>Length</th>
<th></th>
</tr>
</thead>
<tbody class="row">
<tr>
<th>Measurement 1</th>
<td><input name="circumference_1" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Circumference 1"'; } ?> size="60" value="
<?php if (isset($circumference_1)) echo $circumference_1; ?>" ></td>
<td><input name="length_1" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Length 1"'; } ?> size="60" value="
<?php if (isset($length_1)) echo $length_1; ?>" ></td>
<td style="width:200px;"></td>
</tr>
</tbody>
</table>
<p><input type="button" id="insert_row" value="Insert row"></p>
<script>
$('#addrows').on('click', 'input[type="button"]', function() {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function() {
$('#addrows').append('<tr><th>Measurement 2</th><td><input type="text" class="fname" /></td><td><input type="text" class="fname" /></td><td><input type="button" value="Delete" /></td></tr>')
});
</script>
<table class="form">
<tr id="send_holder">
<td class="calculate" colspan="3">
<input type="submit" id="send" value="Send">
<input type="hidden" name="submitted" value="TRUE">
</td>
</tr>
</table>
</form>
PHP Code can be found here:
<?php
// Taken from http://php.net/manual/en/function.mail.php - Example #4 Sending HTML email
// PHP script triggers if SEND button has been clicked
if (isset($_POST['submitted'])) {
// Set up Fasthosts mandatory settings to enable email sending
$email_from = 'EMAIL'; // Must be an email set-up in Fasthosts, mailbox or forwarder
ini_set('SMTP','smtp.fasthosts.co.uk' );
ini_set('sendmail_from', $email_from);
$website_name = 'NAME'; // Change to the name of the website in which the form is
$form_name = 'Request a Quote'; // Change to the name of the form
// Populate PHP variables from $_POST array
$company_name = htmlentities(trim($_POST['company_name']),ENT_QUOTES,"ISO-8859-15");
$contact_person_name = htmlentities(trim($_POST['contact_person_name']),ENT_QUOTES,"ISO-8859-15");
$contact_person_email = htmlentities(trim($_POST['contact_person_email']),ENT_QUOTES,"ISO-8859-15");
$contact_address = htmlentities(trim($_POST['contact_address']),ENT_QUOTES,"ISO-8859-15");
$contact_person_phone = htmlentities(trim($_POST['contact_person_phone']),ENT_QUOTES,"ISO-8859-15");
$boiler_brand_manufacturer = htmlentities(trim($_POST['boiler_brand_manufacturer']),ENT_QUOTES,"ISO-8859-15");
$average_annual_fuel_consumption = htmlentities(trim($_POST['average_annual_fuel_consumption']),ENT_QUOTES,"ISO-8859-15");
$current_cost_per_kw = htmlentities(trim($_POST['current_cost_per_kw']),ENT_QUOTES,"ISO-8859-15");
$type_of_fuel = htmlentities(trim($_POST['type_of_fuel']),ENT_QUOTES,"ISO-8859-15");
$type_of_boiler = htmlentities(trim($_POST['type_of_boiler']),ENT_QUOTES,"ISO-8859-15");
$total_capacity = htmlentities(trim($_POST['total_capacity']),ENT_QUOTES,"ISO-8859-15");
$boiler_capacity = htmlentities(trim($_POST['boiler_capacity']),ENT_QUOTES,"ISO-8859-15");
$circumference_1 = htmlentities(trim($_POST['circumference_1']),ENT_QUOTES,"ISO-8859-15");
$length_1 = htmlentities(trim($_POST['length_1']),ENT_QUOTES,"ISO-8859-15");
// Check for errors and update error variables, e.g. $error_on_name, etc.
if (empty($company_name)) { $error_company_name = 'Y'; }
if (empty($contact_person_name)) { $error_contact_person_name = 'Y'; }
if (empty($contact_person_email)) { $error_contact_person_email = 'Y'; }
if (empty($contact_address)) { $error_contact_address = 'Y'; }
if (empty($contact_person_phone)) { $error_contact_person_phone = 'Y'; }
if (empty($boiler_brand_manufacturer)) { $error_boiler_brand_manufacturer = 'Y'; }
$errors_exist = $error_company_name.$error_contact_person_name.$error_contact_person_email.$error_contact_address.$error_contact_person_phone.$error_boiler_brand_manufacturer;
// No errors exist - Set up and send emails and redirect
if (!empty($errors_exist)) {
$form_error_message = '<tr><td colspan="2"><p id="form_error_message">There are a few pieces of information that we need from you before this form comes through to us. They are highlighted below in red, so please fill those in again and click the <strong>Submit</strong> button again.</p></td></tr>';
// Else, i.e. if $errors array is empty
} else {
// Set up email recipient(s)
$to1 = $contact_person_email; // First email is sent to the person who submitted the form; $email
$to2 = 'email_address'; // Second email is sent to the website owner; change this to the relevant email address
// Set up email subject(s)
$subject1 = 'Thanks for your submission - '.$website_name.' - '.$form_name.' form'; // Do not change
$subject2 = 'Website submission - '.$website_name.' - '.$form_name.' form'; // Do not change
// Set up email message(s)
$message1 = '
<div style="font-family: arial, tahoma, sans serif; font-size: small; color: #666;">
<p>Hi '.$contact_person_name.',</p>
<p>Thanks for completing our '.$form_name.' form on the '.$website_name.' website. We\'ll be in touch as soon as we can!</p>
<p>With kind regards<br />'.$website_name.'</p>
</div>';
$message2 = '
<div style="font-family: arial, tahoma, sans serif; font-size: small; color: #666;">
<p>The following submission has been made via the '.$form_name.' form:</p>
<h2>Company Information</h2>
<p>Company Name: '.$company_name.'</p>
<h2>Contact Information</h2>
<p>
Contact Person Name: '.$contact_person_name.'
<br />Contact Person Email: '.$contact_person_email.'
<br />Contact Address: '.$contact_address.'
<br />Contact Person Phone: '.$contact_person_phone.'
</p>
<h2>Boiler Information</h2>
<p>
Boiler Brand/Manufacturer: '.$boiler_brand_manufacturer.'
<br />Average Annual Fuel Consumption: '.$average_annual_fuel_consumption.'
<br />Current Cost per kW: '.$current_cost_per_kw.'
<br />Type of Fuel: '.$type_of_fuel.'
</p>
<h2>Boiler Capacity</h2>
<p>
Type of Boiler: '.$type_of_boiler.'
<br />Total Capacity: '.$total_capacity.'
<br />Boiler Capacity: '.$boiler_capacity.'
</p>
</div>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers can be set here; Change From to website owner
$headers .= 'From: NAME <' . $email_from . '>' . "\r\n";
// Send emails
mail($to1, $subject1, $message1, $headers);
mail($to2, $subject2, $message2, $headers);
// Errors exist - populate $form_error_message ready for output to browser
}
} // END-OF-IF (isset($_POST['submitted']))
// Stage M3. Add <p> to end of $form_error_message
$form_error_message = $form_error_message.'</p>';
?>
Once you're doing a form submit (instead of an Ajax call) it's pretty easy.
In your form:
<input type="text" name="measure[]" value="This input is fixed">
Each time you add a new input (from the group "measure") it should has the same name as an array: name="measure[]" like the input above.
Then in PHP you just need to run into this array to get all fields.
<?php
$total_elements = count($_POST['measure']);
for ( $i=0;$i<$total_elements;++$i ) {
echo $_POST['measure'][$i];
}
?>
Hope it helps.

Dynamic subtotal in php

In my project I need to make the subtotal of the line (quantite*montant) dynamicali.
For the moment I have there:
I want the montant total it is auto make 1*110 for example and it is directly displayed.
My code :
<div id="contenu">
<h2>Renseigner ma fiche de frais du mois <?php echo $numMois."-".$numAnnee ?></h2>
<form method="POST" action="index.php?uc=gererFrais&action=validerMajFraisForfait">
<div class="corpsForm">
<fieldset>
<legend>Eléments forfaitisés
</legend>
<table width=100%>
<tr>
<td>Libelle</td>
<td>Nombre</td>
<td>Montant unitaire</td>
<td>Montant total</td>
</tr>
<?php
foreach ($lesFraisForfait as $unFrais)
{
$idFrais = $unFrais['idfrais'];
$libelle = $unFrais['libelle'];
$quantite = $unFrais['quantite'];
$montant = $unFrais['montant'];
?>
<tr>
<td><?php echo $libelle ?></td>
<td><input type="number" id="idFrais" name="lesFrais[<?php echo $idFrais?>]" size="10" min="0" autocomplete="off" maxlength="5" value="<?php echo $quantite?>" onkeyup="calculer()">
<td><input type="text" id="montant" value="<?php echo $montant ?>" disabled></td>
</tr>
<?php
}
?>
</table>
</fieldset>
</div>
<div class="piedForm">
<p>
<input id="ok" type="submit" value="Valider" size="20" />
<input id="annuler" type="reset" value="Effacer" size="20" />
</p>
</div>
</form>
Here I added another Answer for you.
So basically in your FOREACH Loop you have to create INCREMENTAL VARIABLE
<?php
$incr = 1;
foreach ($lesFraisForfait as $unFrais)
{
$idFrais = $unFrais['idfrais'];
$libelle = $unFrais['libelle'];
$quantite = $unFrais['quantite'];
$montant = $unFrais['montant'];
?>
<tr>
<td><?php echo $libelle ?></td>
<td><input type="number" id="<?php echo 'idFrais'.$incr; ?>" size="10" min="0" autocomplete="off" maxlength="5" value="<?php echo $quantite?>" onkeyup="calculer(this)">
<td><input type="text" id="<?php echo 'montant'.$incr; ?>" value="<?php echo $montant ?>" disabled></td>
<td id='subtotal<?php echo $incr;?>'><?php echo $quantite*$montant; ?></td>
</tr>
<?php
$incr ++;
}
?>
Since you already have ONKEYUP='calculer' on your javascript code this below.
function calculer( e ){
var i = e.getAttribute('id').length;
var input_identifier = e.getAttribute('id').substring(i-1,i);
var subtotal = document.getElementById('subtotal'+input_identifier)
var quantity = e.value;
var montant = document.getElementById('montant'+input_identifier);
subtotal.textContent = parseInt(quantity) + parseInt(montant.value);
return;
}
This should work.
please add td for total :
<tr>
<td><?php echo $libelle ?></td>
<td><input type="number" id="idFrais" name="lesFrais[<?php echo $idFrais?>]" size="10" min="0" autocomplete="off" maxlength="5" value="<?php echo $quantite?>" onkeyup="calculer()">
<td><input type="text" id="montant" value="<?php echo $montant ?>" disabled></td>
<td><input type="text" value="<?php echo ($montant*$quantite) ?>" disabled></td>
</tr>
You just have to add the following 4th TD.
<td><?php echo $quantite*$montant; ?></td>
That should work.

how can i make print button that will print a report?

I'm doing on a project but my problem is that i don't have any idea on how to make a print button to print my report..the report is in a table..can somebody please help me with this one?my question is how can i add a button for printing?
here is my code for the viewing of specific record
<?php
include_once 'dbconfig.php';
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$province = isset($_GET['province']) ? $_GET['province'] : '';
if(isset($_GET['user_id']))
{
$user_id = $_GET['user_id'];
extract($crud->getID($user_id));
}
?>
<body>
<div id="Survey-view">
<div id="header">
</div>
<p><strong>INFORMATION</strong></p>
<hr />
<div id="main-frame">
<table id="information-content" cellspacing="0">
<thead>
<tr>
<th>Username</th>
<th>Password</th>
<th>Province</th>
</tr>
<tbody>
<tr>
<td><?php echo $username; ?></td>
<td><?php echo $password; ?></td>
<td><?php echo $province; ?></td>
</tr>
</tbody>
</thead>
</table>
</div>
<br />
<br />
<p><strong>ASP</strong></p>
<hr />
<div id="asp">
<table id="asp-content" cellspacing="0">
<thead>
<tr>
<th>Date Survey</th>
<th>Date Submitted</th>
<th>Date Approved</th>
<th>Date Recv'd by Region</th>
<th>Date Recv'd by DARPO</th>
</tr>
<tbody>
<tr>
<td><?php echo $username; ?></td>
<td><?php echo $username; ?></td>
<td><?php echo $username; ?></td>
<td><?php echo $username; ?></td>
<td><?php echo $username; ?></td>
</tr>
</tbody>
</thead>
</table>
</div><!-- End of asp-->
<br />
<br />
<p><strong>DENR/DARPO</strong></p>
<hr />
<div id="denrdarpo">
<table id="denrdarpo-content" cellspacing="0">
<thead>
<tr>
<th>Date Survey</th>
<th>Date Submitted</th>
<th>Date Approved</th>
<th>Date Recv'd by Region</th>
<th>Date Recv'd by DARPO</th>
</tr>
<tbody>
<tr>
<td><?php echo $username; ?></td>
<td><?php echo $username; ?></td>
<td><?php echo $username; ?></td>
<td><?php echo $username; ?></td>
<td><?php echo $username; ?></td>
</tr>
</tbody>
</thead>
</table>
</div><!--End of denrdarpo-->
<br />
<br />
<p><strong>OTHERS</strong></p>
<hr />
<div id="others">
<table id="others-content" cellspacing="0">
<tr>
<td>Project Number</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
<td>Module Number</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
</tr>
<tr>
<td>Fund Year</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
<td>LAD Target</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
</tr>
<tr>
<td>Land Category</td>
<td><select disabled>
<option><?php echo $username; ?></option>
</select></td>
<td>LAnd Type</td>
<td><select disabled>
<option><?php echo $username; ?></option>
</select></td>
</tr>
<tr>
<td>Date Reported</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
<td>Date Suspended</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
</tr>
<tr>
<td>Date Completed</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
<td>Number of Lots</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
</tr>
<tr>
<td>Station</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
<td>Contractor</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
</tr>
<tr>
<td>Agency</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
<td>Cert 40</td>
<td><input type="text" value="<?php echo $username; ?>" disabled></td>
</tr>
</table>
</div>
</div>
</body>
Every time I need to do this I go to my old Gmail account, print a page and then view the source code cus I'm too lazy to remember the functions..
This is how Google does it.
<script type="text/javascript">// <![CDATA[
document.body.onload=function(){document.body.offsetHeight;window.print()};
// ]]></script>
You could just as easily attach it to a button instead of doing it on load.
<button onclick="document.body.offsetHeight;window.print();">Print</button>
Here's a working example.
And this one will remove the button from the printed page:
<button onclick="this.style.display='none';document.body.offsetHeight;window.print();this.style.display='inline';">Print</button>
And another example.
<html>
<head>
<script type="text/javascript">
function openWin()
{
var myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.document.close();
myWindow.focus();
myWindow.print();
myWindow.close();
}
</script>
</head>
<body>
<input type="button" value="Open window" onclick="openWin()" />
</body>
</html>

Table Row Sum Within PHP loop

I want to sum table rows dynamically as the user inputs values. Since the number of rows can vary I want to use a php loop to accomplish this. I'm having problems getting the loop to work correctly. If, for example, there are two individual rows to sum only the bottom row will be summed.
<script type="text/javascript">
var sumScoreF = function(a) {
var rowtotal = 0;
n = new Array();
for (i = 1; i <= 3; i++) {
if (parseInt(document.getElementById(a + i).value) > 0) {
n[i] = parseInt(document.getElementById(a + i).value);
rowtotal += n[i];
}
}
document.getElementById(a + 'total').value = rowtotal;
};
</script>
The following is an example of a single row sum. The total column continues to be summed as values are entered. This is a nice effect but not necessary.
<table>
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
<td>total</td>
</tr>
<tr>
<td>
<input name="p1g1" id="p1g1" type="text" value="" onChange="sumScoreF('p1g')" />
</td>
<td>
<input name="p1g2" id="p1g2" type="text" value="" onChange="sumScoreF('p1g')" />
</td>
<td>
<input name="p1g3" id="p1g3" type="text" value="" onChange="sumScoreF('p1g')" />
</td>
<td>
<input name="p1gtotal" id="p1gtotal" type="text" value="" />
</td>
</tr>
</table>
Here is my attempt at looping additional rows using php and javascript. The first row will not sum but the second row will. I think the problem is with the javascript variable "m" in that it goes directly to the last row but I can't figure out how to fix it.
<table>
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
<td>total</td>
</tr>
<?php for($j=1;$j<=3;$j++) { ?>
<script type="text/javascript">
var k = <?php echo json_encode($j); ?>;
var m = 'p'+k+'g';
</script>
<tr>
<td>
<input name="<?php echo 'p'.$j.'g1'; ?>" id="<?php echo 'p'.$j.'g1'; ?>" type="text" onChange="sumScoreF('m')" />
</td>
<td>
<input name="<?php echo 'p'.$j.'g2'; ?>" id="<?php echo 'p'.$j.'g2'; ?>" type="text" onChange="sumScoreF('m')" />
</td>
<td>
<input name="<?php echo 'p'.$j.'g3'; ?>" id="<?php echo 'p'.$j.'g3'; ?>" type="text" onChange="sumScoreF('m')" />
</td>
<td>
<input name="<?php echo 'p'.$j.'gtotal'; ?>" id="<?php echo 'p'.$j.'gtotal'; ?>" type="text" />
</td>
</tr>
<?php } ?>
Any help is greatly appreciated. Thanks.
Used PHP to echo the loop variable within the onChange javascript function call:
<table>
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
<td>total</td>
</tr>
<?php for($j=1;$j<=3;$j++) { ?>
<tr>
<td>
<input name="<?php echo 'p'.$j.'g1'; ?>" id="<?php echo 'p'.$j.'g1'; ?>" type="text" onChange="sumScoreF('<?php echo 'p'.$j.'g'; ?>')" />
</td>
<td>
<input name="<?php echo 'p'.$j.'g2'; ?>" id="<?php echo 'p'.$j.'g2'; ?>" type="text" onChange="sumScoreF('<?php echo 'p'.$j.'g'; ?>')" />
</td>
<td>
<input name="<?php echo 'p'.$j.'g3'; ?>" id="<?php echo 'p'.$j.'g3'; ?>" type="text" onChange="sumScoreF('<?php echo 'p'.$j.'g'; ?>')" />
</td>
<td>
<input name="<?php echo 'p'.$j.'gtotal'; ?>" id="<?php echo 'p'.$j.'gtotal'; ?>" type="text" />
</td>
</tr>
<?php } ?>

Categories