array push replacing or erasing the existing values - php

I have a problem with my code here... Basically, I have a page (edit_patient.php) which is receiving (GET) a number from another page (new_patient.php)... On the edit_patient.php page I want to either edit or add new information to what's already posted from new_patient.php...
The problem is, that I have an array and I want to push the old array to add new values to this existing array...
When I post, the information gets either replaced or erased...
Here are my codes:
<?php
// Update the database with new information from form;
if (isset($_POST['dossier'])){
$pid = mysqli_real_escape_string($connect,$_POST['thisID']);
if (!empty($_POST['medication'])|| ($_POST['posology'])) {
$thisArraysql = mysqli_query($connect, "SELECT medication, posology FROM patient WHERE dossier='$thisID' LIMIT 1");
$medArray_count = mysqli_num_rows($thisArraysql);
if ($medArray_count > 0) {
while ($row = mysqli_fetch_array($thisArraysql)) {
$old_medication = $row["medication"];
$old_posology = $row["posology"];
}
$medication .= array_push($old_medication, implode('-', $_POST['medication']));
$posology .= array_push($old_posology, implode('-',$_POST['posology']));
} else {
$medication = implode('-', $_POST['medication']);
$posology = implode('-', $_POST['posology']);
}
}
$sql = "UPDATE patient SET medication = '$medication', posology = '$posology' WHERE dossier = '$pid'";
if (!mysqli_query($connect, $sql)) {
printf("Error: %s\n", mysqli_error($connect));
} else {
header("location: patients_list.php");
}
exit();
}
// Get pid from new_patient.php; Select the patient from database;
if (isset($_GET['pid'])){
$targetID = $_GET['pid'];
$sql = "SELECT * FROM patient WHERE dossier='$targetID' LIMIT 1";
$query = mysqli_query($connect, $sql);
$patientCount = mysqli_num_rows($query);
if ($patientCount > 0){
while($row = mysqli_fetch_array($query)){
$id = $row["id"];
$dossier = $row["dossier"];
$medication = explode('-',$row['medication']);
$medication_count = count($medication);
$medication_count_added = $medication_count+1;
$posology = explode('-',$row['posology']);
}
} else {
echo "This patient does not exist!";
exit();
}
}
?>
<html>
<head>
<!-- this scripts adds more fields to the array -->
<script type="text/javascript">
$(document).ready(function() {
var MaxInputs = 19-"<?php echo $medication_count; ?>"; //maximum input boxes allowed
var CurrentSituation = $("#CurrentSituation"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFieldBox"); //Add button ID
var x = CurrentSituation.length; //initlal text box count
var FieldCount="<?php echo $medication_count_added; ?>"+1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(CurrentSituation).append('<tr class="field_added"><td><input type="text" name="medication['+ FieldCount +']" id="medication['+ FieldCount +']" size="40" /></td><td><input type="number" name="posology['+ FieldCount +']" id="posology['+ FieldCount +']" min="1" max="100000" /></td><td>Effacer</td></tr>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).closest("tr").remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
</script>
</head>
<body>
<form action="edit_patient.php" enctype="multipart/form-data" method="post">
Dossier Number: <input type="number" id="dossier" name="dossier" readonly value="<?php echo $dossier; ?>" />
<table border="0" cellpadding="1" cellspacing="1">
<tr>
<td>Medication(s)</td>
<td colspan="2">Posology(ies)</td>
</tr>
<?php
echo "<tr><td><table border=\"0\" cellpadding=\"1\" cellspacing=\"1\">";
foreach ($medication as $key => $value) {
echo "<tr><td>$value</td></tr>";
}
echo "</table></td><td><table border=\"0\" cellpadding=\"1\" cellspacing=\"1\">";
foreach ($posology as $key => $value) {
echo "<tr><td>$value</td></tr>";
}
echo "</table></td></tr>";
?>
<tr>
<td><input type="text" name="medication[<?php echo $medication_count_added; ?>]" id="medication[<?php echo $medication_count_added; ?>]" size="40" /></td>
<td><input type="number" name="posology[<?php echo $medication_count_added; ?>]" id="posology[<?php echo $medication_count_added; ?>]" min="1" max="100000" /></td>
</tr>
</table>
</form>
</body>
</html>
Thank you so much for your help, time, comprehension and dedication!!
EDIT:
I replaced the code for the array as such:
<?php
if (mysqli_num_rows($thisArraysql) < 0) {
$medication = implode('-', $_POST['medication']);
$posology = implode('-', $_POST['posology']);
} else {
$medication = array();
$posology = array();
while ($row = mysqli_fetch_array($thisArraysql)) {
$medication[] = $row["medication"];
$posology[] = $row["posology"];
}
foreach ($_POST['medication'] as $key => $value) {
$medication[$key] = $value;
}
foreach ($_POST['posology'] as $key => $value) {
$posology[$key] = $value;
}
}
?>
But I am still getting the same error... the array gets replaced by the word Array...
EDIT 2
I created a new patient (new_patient.php) and added some info in the array. Once in the edit_patient.php (this page that I have problems with), I did a var_dump and this is what I get:
array (size=1)
0 => string 'Med 1-Med 2-Med 3-Med 4-' (length=24)
array (size=1)
0 => string '25-30-50-5-' (length=11)
Now, if I update the array I get this:
array (size=1)
0 => string 'Array' (length=5)
array (size=1)
0 => string 'Array' (length=5)

Related

Give name to a function in a form

I would like to name the function devtest() in the form as developer so when a user selects the developer it is submitted with the form.
The function I have is this and it is working, it returns the results when you select an item from the dropdown:
function devtest()
{
$db = db();
$stmt = $db->prepare('SELECT developer FROM developers');
$result = $stmt->execute();
?>
<select name="Developer">
<?php
while ($row = $result->fetchArray()) {
$dev = $row['developer'];
echo "<option value='" . $row['developer'] ."'>" . $row['developer'] ."</option>";
}
echo "</select>";
}
on the page itself where I call function and have the form I have
<form method="POST">
Enter game name:
<input type="text" name="name">
<br>
Enter Price
<input type="text" name="price">
<br>
Enter Platform
<input type="text" name="platform">
<br>
Select Developer
<!--<input type="text" name="developer">-->
<?php
devtest();
?>
<br>
Enter quantity
<input type="text" name="quantity">
<br>
Enter shipping
<input type="text" name="shipping">
<br>
<input type="submit" value="save">
</form>
That form goes to this function
function addgame()
{
#$devtest = devtest();
$db = db();
#function to add the form data from the add game page to the database
if(!empty($_POST['name']) && !empty($_POST['price']) && !empty($_POST['platform']) && !empty($_POST['quantity'])&& !empty($_POST['shipping'])){
$name = SQLite3::escapeString($_POST['name']);
$price = SQLite3::escapeString($_POST['price']);
$platform = SQLite3::escapeString($_POST['platform']);
$developer = SQLite3::escapeString($_POST['Developer']);
#$developer = devtest();
$quantity = SQLite3::escapeString($_POST['quantity']);
$shipping = SQLite3::escapeString($_POST['shipping']);
if (strlen($name) < 2)
{
echo("name be 2 char or longer");
}
if (!is_numeric($price))
{
echo("price must be numbers only");
}
if (strlen($platform) < 2)
{
echo("Platform must be 2 char or longer");
}
if (strlen($quantity) < 1)
{
echo("quantity must be more than 1");
}
/*if (strlen($shipping) < 9)
{
echo("shipping must be more than $9");
}*/
else
{
$stmt = $db->prepare("INSERT INTO game (name , price , platform , Developer, quantity, shipping) VALUES ('$name' , '$price' , '$platform' , '$developer', '$quantity' , '$shipping')");
$result = $stmt->execute();
}
}
else
{
echo "Fill in all form fields";
}
}
Without using the devtest() function in the form, and using the everything works fine, I am trying to change it so those on the list can be selected but I am not sure how to pass their select through the form.
you can send data to javascript and write your function in js to add a dropdown every where you need:
...
<script>
var developer = []
</script>
.
.
.
<php>
while ($row = $result->fetchArray()) {
?>
<script>
var developer[]=<?php echo $row['developer']; ?>
</script>
<?php
}
?>
js funtion:
<script>
function devtest(elementID){
developer.forEach(index,item){
$('#'+elementID).append('<select value="'+item+'">'+item+'</select>');
}
}
</script>
}

Datalist only displaying and serving 1st word

OK, Let's start again. The purpose of this code is to update a database table (db.aotm) comprising the club members who will be featured during the coming year as "The Artist of the Month". The first (html)table shows a list of members who gualify as Features Artists. Their names are hald in the $featuredArtist array.
Next, the $aotm array is populated with the current list of "month" and "member" held in the db.aotm table these are used as the default values of the form.
Then the datalist is populated with names from the $featuredArtist array.
The problem is that when the Form Input box is clicked the datalist box only shows the first name of each artist and any selection only enters the first name.
I have tried using a simple variable instead ogf th array in the datalist but the same happens if $name = "John Smith"; then only "John" is displayed and entered into the input box. If I replace the soft datalist a hard coded datalist then it functions normally. So it seems tha any variable in the datalist only serves the first word.
My code is :
<?php
echo '<div class="dbrd">
$query = " SELECT id, status, fullname FROM members ";
$result = mysqli_query($db, $query);
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
if (bitN($row[status],2) == 1 && $row[id] > 20){
$featuredArtist[$i]['id'] = $row['id'];
$featuredArtist[$i]['artist'] = $row['fullname'];
$i++;
}
}
?>
<div style="text-align:center;width:100%;">
<table style="width:100%;">
<thead>
<tr><th colspan="3">Featured Artists</th></tr>
</thead>
<tbody>
<?php
$j = 0;
while ($j < $i){
echo " <tr><td>".$featuredArtist[$j]['artist']."</td>";
$j++;
echo " <td>".$featuredArtist[$j]['artist']."</td>";
$j++;
echo " <td>".$featuredArtist[$j]['artist']."</td></tr>";
$j++;
}
?>
</tbody>
</table>
<br />
</div>
<?php
$query = "SELECT id, artist FROM aotm";
$result = mysqli_query($db, $query);
$k = 0;
while ($row = mysqli_fetch_assoc($result)) {
$aotm[$k]['id'] = $row['id'];
$aotm[$k]['artist'] = $row['artist'];
$k++;
}
$l = 0;
echo '<datalist id = "artist">';
while ($l < $i) {
$artist = $featuredArtist[$l]['artist'];
echo " <option value = ".$artist.">";
$l++;
}
?>
</datalist>
<form action = "" method = "POST">
<table style="width:100%;">
<tbody>
<tr><td>Jan</td><td><input type = "text" list = "artist" name="1" size = "45" ></td></tr>
<tr><td>Sept</td><td><input list = "artist" type = "text" name="2" value = "<?php echo $aotm[1]['artist'];?>" size = "45" /></td></tr>
<tr><td colspan="2"><input type = "submit" name = "aotm" value = "Save" /></td></tr>
</tbody>
</table>
</form>
</div>

PHP Checkbox ordered by click and send thru post form to a news sql query on the clicked order

I have a code on page1.php where I have an array of checkbox populated with mysql data through a query. I can successfully submit the value of the checked checkbox to the page2.php. But I want to submit it according to the sequence the checkbox was checked by the user. I´ve seen that jQuery can do this, but i don´t know how and where to place the jQuery code.
My intention is to show on page2.php what the user selected, on a specific order, from the page1.php form
MODIFIED: Well , I managed to create the list and send via form . The problem now is to put a comma between the numbers . I know this must be the easiest problem to solve , but I can not yet.
The SQL Query is looking like this, for example:
SELECT * FROM emp WHERE id IN (7,9,30) ORDER BY FIELD (id,
30 9 7)
page1.php
<script type="text/javascript">
var listCheckedOptions = [];
function addToList(checkObj, outputObjID) {
//Remove from array if the element already in.
if (listCheckedOptions.indexOf(checkObj) >= 0) {
listCheckedOptions.splice(listCheckedOptions.indexOf(checkObj), 1);
}
listCheckedOptions.push(checkObj);
document.getElementById(outputObjID).value = ""; //Clean textarea
document.getElementById(outputObjID).value = listCheckedOptions.map(function (o) {
return o.value;
}).join('\r\n'); //Add to textarea
if (!checkObj.checked) checkObj.nextSibling.querySelector('span').innerHTML = '';
listCheckedOptions.forEach(function (el, i) {
var span = el.nextSibling.querySelector('span').innerHTML = i + 1;
});
return;
}
</script>
<?php
$query = "SELECT * FROM imoveis";
$result = mysql_query($query,$conn);
?>
<form action="page2.php" method="post">
<input type="submit" value="Create" id="enviarButton"/></td>
<br><br>
<table border="1">
<?
$i = 0;
echo "<tr>";
while($imovel = mysql_fetch_array($result)){
$name = $imovel['emp'];
$id = $imovel['id'];
?>
<td>
<?=$name;?><br>
<input type="checkbox" name="op_imovel[]" value="<?=$id;?>" onClick="addToList(this, 'txt1')">
</td>
<?
$i++;
if(($i % 3) == 0){
echo "</tr><tr>";
}
}
mysql_close();
?>
</table>
<br>
<input type="hidden" name="txt1" id="txt1">
</form>
page2.php
<?php
$checkbox = $_POST['op_imovel'];
$lista = $_POST['txt1'];
if (is_array($checkbox) && count($checkbox) > 0){
$res = '';
$tot = count($checkbox) - 1;
for ($y = 0; $y <= $tot; $y++) {
$res .=$checkbox[$y];
if ($y < $tot)
$res .= ",";
}
}
$query = "SELECT * FROM emp WHERE id IN ($res) ORDER BY FIELD (id, $lista)";
$result = mysql_query($query,$conn);
?>
<br>
<div align="center">
<table border="1">
<?
$i = 0;
echo "<tr>";
if (is_array($checkbox) && count($checkbox) > 0){
while($imovel = mysql_fetch_array($result)){
$name = ($imovel['emp']);
?>
<td>
<p>
<?= $name;?>
</p>
</td>
<?
$i++;
if(($i % 3) == 0){
echo "</tr><tr>";
}
}
}
?>
</div>
<? mysql_close(); ?>

Insert and Update data in database at the same time

What i want- i want to insert data into database if no existing data, and update if the data already exist in database.
Problem - If i click submit button without enter new data, the data still insert into database.
This is my code so far:
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<?php
mysql_connect("localhost","root","");
mysql_select_db("cuba");
if(isset($_POST['hantar']))
{
for($a=1; $a<=count($_POST['name']); $a++)
{
/*$sqlQuery = "REPLACE INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."')"; */
$sqlQuery = "INSERT INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' ) on DUPLICATE KEY UPDATE name='".$_POST['name'][$a]."', ic ='".$_POST['ic'][$a]."'";
mysql_query($sqlQuery)or die(mysql_error());
}
}
?>
<form action="" method="post">
<div class="b">
<?php
$a = 1;
$share = mysql_query("select *from a")or die(mysql_error());
while($share_papar = mysql_fetch_array($share))
{
?>
<table class="bb" style="border:1px solid #003;">
<tr>
<td width="200">Name</td>
<td> : <input type="text" class="input_teks" name="name[]" value="<? php echo $share_papar['name'];?>" />
</td>
</tr>
<tr>
<td>ic</td>
<td> : <input type="text" class="input_teks" name="ic[]" value="<?php echo $share_papar['ic'];?>" /></td>
</tr>
<tr>
<td>id</td>
<td> : <input type="text" class="input_teks" name="id[]" value="<?php echo $share_papar['id'];?>" id="akhir"/></td>
</tr>
<tr>
<td colspan="2" align="right" class="b_buang">Remove</td>
</tr>
</table>
<?php
}?>
</div>
<input type="submit" value="ss" name="hantar">
</form>
<span class="b_tambah">Add new group</span>
<script type="text/javascript">
$(function()
{
//nk clone
$('.b_tambah').on('click',function(e)
{
$(".b").find(".bb").last().clone(true).appendTo(".b");
alert( $(".bb:last").find("input[id=akhir]").last().val());
var m = $(".bb:last").find("input[id=akhir]").last();
m.val("");
});
//nk buang
$(".b_buang").click(function () {
if($('.bb').length < 2)
{
alert("Remove operation can be done if GROUP more than one");
}
else
{
$(this).parents(".bb").remove();
}
});
});
</script>
<!-- close clone Shareholders -->
</td>
I'm using jquery to clone form same with update form, then reset value to blank for input type name (id), so i can have non match id with existing data. But if i submit form without cloning those form, the data will insert into database. What i want is, no need to insert data into database if i dont cloning the new data and just update the existing. How i can achieve that..
Use this code
if(isset($_POST['hantar']))
{
for($a=1; $a<=count($_POST['name']); $a++)
{
$name = $_POST['name'][$a];
$ic = $_POST['ic'][$a];
$name = $_POST['name'][$a];
$sel = mysql_query("select * from a where name = '$name' and ic = '$ic' ");
if(mysql_num_rows($sel) > 0){
//write update query
$fet =mysql_fetch_array($sel);
$auto_increment_id = $fet['id'];
$sqlQuery = " update a set name = '$name' , ic = '$ic' where id = '$auto_increment_id' ";
}
else {
// write insert query
$sqlQuery = "INSERT INTO a (id,name,ic) VALUES ('".$_POST['id'][$a]."','".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' ) ";
}
mysql_query($sqlQuery)or die(mysql_error());
}
}
first check the $_POST['name'] in SELECT query if it is exsits update in the query if not then insert into database
try replacing
for($a=1; $a<=count($_POST['name']); $a++)
to
for($a=0; $a < count($_POST['name']); $a++)
And also check validation
e.g.
if(isset($_POST['name'][$a]) && trim($_POST['name'][$a]) != "")
Finally.. This code save me..
if(isset($_POST['hantar']))
{
for($a=0; $a < count($_POST['name']); $a++)
{
if($_POST['name'][$a]=="")
{
}else
{
if($_POST['id'][$a]=="")
{
$sqlQuery = "INSERT INTO a (name,ic) VALUES ('".$_POST['name'][$a]."', '".$_POST['ic'][$a]."' )";
mysql_query($sqlQuery)or die(mysql_error());
}
else
{
$sqlQuery = " update a set name = '{$_POST['name'][$a]}' , ic = '{$_POST['ic'][$a]}' where id = '{$_POST['id'][$a]}' ";
mysql_query($sqlQuery)or die(mysql_error());
}
}
}
}

Keeping Dynamic Table Rows shown after form post errors

I have a dynamic HTML table that allows users to enter receipt items in, and they can add as many rows as necessary.
If they forget to fill out a field upon form POST, I want all those rows with the data to stay shown, instead what happens, is they dynamic rows disappear and no values are saved in the one row that shows on default.
How can I achieve having those dynamic table rows shown with the values they've entered to avoid them having to enter all the data again?
<?php
if(isset($saveAdd))
{
$expenseType = safeDataMySQL($_POST['expenseType']);
//Save page, redirect to same page but increment receipt number.
if(empty($_POST['expenseNumber']))
{
//New expense so no records have been created as of yet. Otherwise, this would be stored in hidden field.
$getRef = mysql_query("SELECT CAST(SUBSTRING(refNumber,4) AS UNSIGNED INTEGER) AS referenceNumber FROM expense_main ORDER BY referenceNumber DESC LIMIT 1") or die("Ref No: " . mysql_error());
if(mysql_num_rows($getRef) > 0)
{
while($refData = mysql_fetch_array($getRef))
{
//Expense Number!
$refNumber = $refData['referenceNumber'];
$refNumber = ($refNumber + 1);
}
$ins = mysql_query("INSERT INTO `expense_main` (`respid`, `refNumber`, `dateCreated`, `draftMode`, `expenseType`) VALUES ('".$respid."', 'USA".$refNumber."', NOW(), '1', '".$expenseType."')") or die("Expense Insert: " . mysql_error());
$expClaimNumber = 'USA'.$refNumber;
}
}
else
{
$expClaimNumber = safeDataMySQL($_POST['expenseNumber']);
}
//Get the next receipt in line as well
$getRec = mysql_query("SELECT receiptNumber FROM expense_details ORDER BY receiptNumber DESC LIMIT 1") or die("Get Receipt: " . mysql_error());
if(mysql_num_rows($getRec) > 0)
{
while($recData = mysql_fetch_array($getRec))
{
$receiptNumber = $recData['receiptNumber'];
$receiptNumber = ($receiptNumber + 1);
}
}
$fields = array('recLineDate_', 'recLineCategory_', 'recLineDescr_', 'recLineAmount_');
foreach ($fields as $field)
{
foreach ($_POST[$field] as $key=>$line)
{
$returnArray[$key][$field] = $line;
}
}
foreach ($returnArray as $lineItem)
{
if(empty($lineItem['recLineDate_']))
{
$Errors[] = 'You forgot to enter the receipt date.';
}
else
{
$recDate = safeDataMySQL($lineItem['recLineDate_']);
}
if(empty($lineItem['recLineCategory_']))
{
$Errors[] = 'You forgot to enter a category.';
}
else
{
$recCategory = safeDataMySQL($lineItem['recLineCategory_']);
}
if(empty($lineItem['recLineDescr_']))
{
$Errors[] = 'You forgot to enter a description.';
}
else
{
$recDescr = safeDataMySQL($lineItem['recLineDescr_']);
}
if(empty($lineItem['recLineAmount_']))
{
$Errors[] = 'You forgot to enter your receipt amount.';
}
else
{
$recAmount = safeDataMySQL($lineItem['recLineAmount_']);
}
if(empty($_POST['alternateBranch']))
{
$alternateBranch = '0';
}
else
{
$alternateBrach = $_POST['alternateBranch'];
}
if(!isset($Errors))
{
$recDate = date("Y-m-d", strtotime($recDate));
$ins = mysql_query("INSERT INTO `expense_details` (`receiptNumber`, `claimId`, `alternateBranch`, `dateAdded`, `expenseDate`, `expenseDescription`, `expenseAmount`, `categoryId`)
VALUES ('".$receiptNumber."', '".$expClaimNumber."', '".$alternateBranch."', NOW(), '".$recDate."', '".$recDescr."', '".$recAmount."', '".$recCategory."')") or die("Could not insert receipt: " . mysql_error());
$nextReceipt = ($receiptNumber + 1);
//Redirect to same page, incrementing the receipt number by 1.
header('Location: createExpense.php?expenseNumber='.$expClaimNumber.'&receiptNum='.$nextReceipt);
}
}
}
$expenseNumber = safeData($_GET['expenseNumber']);
$receiptNumber = safeData($_GET['receiptNum']);
if (isset($Errors))
{
echo "<div align='center'><span class='errormessagered'><ul class='errors'>";
foreach ($Errors as $Error)
{
echo "<li>".$Error."</li>";
echo '<br />';
}
echo "</ul></span></div>";
}
?>
<form name="createNew" method="POST" action="">
<div id="row">
<div id="left">
<strong>Receipt Items:</strong>
</div>
<div id="right">
<i>Only add another line to the receipt below IF you have multiple items on one receipt.</i>
<br /><br />
<table border="0" width="825px" cellspacing="0" cellpadding="5" name="receipts" id = "receipts">
<thead>
<tr>
<th class="colheader" width="120px">Date</th>
<th class="colheader" width="120px">Category</th>
<th class="colheader" width="120px">Description</th>
<th class="colheader" width="120px">Amount</th>
<th class="colheader" width="145px"><span class="boldblacklinks">[Add +]</span></th>
</tr>
</thead>
<tbody class="lineBdy">
<tr id="line_1" class="spacer">
<td><input type="text" class="date fieldclasssm" id="recLineDate[]" name="recLineDate_[]" size="10" value = "<?=date("m/d/Y", strtotime($today))?>"/></td>
<td><select name="recLineCategory_[]" class="fieldclasssm">
<option value = "">Select a Category...</option>
<?php //Get Categories
$getCats = mysql_query("SELECT id, nominalName FROM expense_nominalCodes ORDER BY id") or die("Get Cats: " . mysql_error());
if(mysql_num_rows($getCats) > 0)
{
while($catData = mysql_fetch_array($getCats))
{
echo '<option value = "'.$catData['id'].'"'; if($catData['id'] == $_POST['recLineCategory_']) { echo "Selected = 'SELECTED'"; } echo '>'.$catData['nominalName'] . '</option>';
}
}
?>
</select>
</td>
<td><input type="text" class="lineDescr fieldclasssm" name="recLineDescr_[]" id="recLineDescr[]" value = "<?=$_POST['recLineDescr']?>" size="40" /></td>
<td colspan = "2"><input type="text" class="sum lineAmount fieldclasssm" name="recLineAmount_[]" id="recLineAmount[]" value = "<?=$_POST['recLineAmount']?>" size="12" /></td>
</tr>
</tbody>
</table>
</div>
" />
" />
<script type="text/javascript">
$(document).ready(function () {
$('.date').change(function () {
$('.date').val($('.date:nth-of-type(1)').val());
});
});
//Add new table row & clone date field
$('#add').on('click', function(){
addReceiptItem();
$('.date').focus(function() {
$(this).select();
});
$('.receipt').focus(function() {
$(this).select();
});
});
function addReceiptItem(){
var lastID = $('tr[id*="line_"]').length,
newTds = $('tr[id="line_' + lastID + '"] td').clone(),
newRow = document.createElement('tr');
// add new id and class to row, append cloned tds
$(newRow)
.attr('id', 'line_' + (lastID + 1 ))
.attr('class', 'spacer')
.append(newTds);
$(newRow).find('input').not(':eq(0)').val('');
// $(newRow).find('class').not(':eq(0)').not(':eq(0)').val('');
//add the new row to the table body
$('tbody.lineBdy').append(newRow);
$('.receipt').attr('readonly', true);
$('.date').attr('readonly', true);
};
</script>
Just to get you started. You can add the rows from $_POST["rows"]
foreach ($_POST["rows"] as $rowstring) {
list($date, $cat, $desc, $amt) = explode(",", $rowstring)
?>
<td><?php echo $date; ?></td>
<td><?php echo $cat; ?></td>
<td><?php echo $desc; ?></td>
<td><?php echo $amt; ?></td>
<td> </td>
<?php
}
Assuming you add a hidden input with a comma delimited string each time a dynamic row is added.
FWIW, I would also recommend doing all of the database queries (ie $getCats = ...) prior to rendering anything to the screen so that in case the 'or die()' happens, you wont get a half rendered page.

Categories