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.
Related
I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.
I am working on an online shopping cart project, which requires me to be able to add a custom text input field to each item that is added to the shopping cart. However, when I attempt to insert the information for each item in the card into a database, I cannot figure out how to pass the itemtext value into my INSERT statement. How would I go about being able to pass the itemtext value from the initial item list into my database for Orderitems? The itemtext input is on line 170, and I want to pass it into the INSERT statement seen on line 83.
<?php
session_start();
$user = $_SESSION['user'];
if(!isset($user)) {
header("Location:userlogin.php");
}
$cart = $_COOKIE['WSC'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("WSC", $new_cart, $expire);
header("Location:order.php");
}
if(isset($_POST['PlaceOrder'])) {
$email = $user;
$orderdate = date('m/d/Y');
$ordercost = $_POST['ordercost'];
$ordertype = $_POST['ordertype'];
$downcost = $_POST['downcost'];
$cardtype = $_POST['cardtype'];
$cardnumber = $_POST['cardnumber'];
$cardsec = $_POST['cardsec'];
$cardexpdate = $_POST['cardexpdate'];
$orderstatus = "Pending";
if($ordertype=="") {
$ordertypeMsg = "<br><span style='color:red;'>You must enter an order type.</span>";
}
if($cardtype=="") {
$cardtypeMsg = "<br><span style='color:red;'>You must enter a card type.</span>";
}
if($cardnumber=="") {
$cardnumberMsg = "<br><span style='color:red;'>You must enter a card number.</span>";
}
if($cardsec=="") {
$cardsecMsg = "<br><span style='color:red;'>You must enter a security code.</span>";
}
if($cardexpdate=="") {
$cardexpdateMsg = "<br><span style='color:red;'>You must enter an expiration date.</span>";
}
else {
include ('includes/dbc_admin.php');
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
$sql = "SELECT orderid FROM Orders";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$myid = $row[orderid];
}
$itemnumber = 1;
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$itemtext = $_POST['itemtext'];
$sql= "INSERT INTO OrderItems (orderid, itemnumber, itemid, itemtype, media, itemtext, price)
VALUE ('$myid', '$itemnumber', '$row[itemid]', '$row[itemtype]', '$row[media]', '$itemtext[itemnumber]', '$row[price]')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
}
$itemnumber++;
}
$inserted = "<h2>Thank You!</h2> <h3>Your order has been placed.</h3>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Williams Specialty Company</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function validateForm() {
var ordercost = document.form1.ordercost.value;
var downcost = document.form1.downcost.value;
var ordertype = document.form1.ordertype.value;
var cardtype = document.form1.cardtype.value;
var cardnumber = document.form1.cardnumber.value;
var cardsec = document.form1.cardsec.value;
var cardexpdate = document.form1.cardexpdate.value;
var ordertypeMsg = document.getElementById('ordertypeMsg');
var cardtypeMsg = document.getElementById('cardtypeMsg');
var cardnumberMsg = document.getElementById('cardnumberMsg');
var cardsecMsg = document.getElementById('cardsecMsg');
var cardexpdateMsg = document.getElementById('cardexpdateMsg');
if(ordertype == ""){ordertypeMsg.innerHTML = "You must enter an order type."; return false;}
if(cardtype == ""){cardtypeMsg.innerHTML = "You must enter a card type."; return false;}
if(cardnumber == ""){cardnumberMsg.innerHTML = "You must enter a card number."; return false;}
if(cardsec == ""){cardsecMsg.innerHTML = "You must enter a security code."; return false;}
if(cardexpdate == ""){cardexpdateMsg.innerHTML = "You must enter an expiration date."; return false;}
}
</script>
</head>
<body>
<?php include('includes/header.inc'); ?>
<?php include('includes/nav.inc'); ?>
<div id="wrapper">
<?php include('includes/aside.inc'); ?>
<section>
<h2>My Cart</h2>
<table width="100%">
<tr>
<th>Catalog ID</th>
<th>Item Name</th>
<th>Price</th>
<th>Item Text</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['WSC'];
if ($cart) {
$i = 1;
$ordercost;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td align="left">';
echo $row['itemid'];
echo '</td>';
echo '<td align="left">';
echo $row['itemname'];
echo '</td>';
echo '<td align="left">';
echo $row['price'];
$ordercost+=$row['price'];
$downcost = $ordercost / 10;
echo '</td>';
echo '<td align="left">';
echo '<p><input type="text" id= "itemtext" name="itemtext"></p>';
echo '</td>';
echo '<td align="left">';
echo 'Remove From Cart';
echo '</td>';
echo '</tr>';
}
$i++;
}
}
?>
</table><br />
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="submit" name="clear" value="Empty Shopping Cart">
</form>
<?php if(isset($inserted)) {echo $inserted;} else{ ?>
<form method="post" action="<?php echo $SERVER['PHP_SELF'] ?>" name="form1" onSubmit="return validateForm()">
<p>Total Price: <?php echo $ordercost;?> <input type="hidden" id="ordercost" name="ordercost" value="<?php echo $ordercost;?>"> </p>
<p>Down Cost: <?php echo number_format((float)$downcost, 2, '.', '');?> <input type="hidden" id="downcost" name="downcost" value="<?php echo number_format((float)$downcost, 2, '.', '');?>"> </p>
<p><label>Order Type:</label><br> <input type="text" id="ordertype" name="ordertype">
<?php if(isset($ordertypeMsg)) {echo $ordertypeMsg;} ?>
<br /><span id="ordertypeMsg" style="color:red"></span>
</p>
<p><label>Card Type:</label><br> <input type="text" id="cardtype" name="cardtype">
<?php if(isset($cardtypeMsg)) {echo $cardtypeMsg;} ?>
<br /><span id="cardtypeMsg" style="color:red"></span>
</p>
<p><label>Card Number:</label><br> <input type="text" id="cardnumber" name="cardnumber">
<?php if(isset($cardnumberMsg)) {echo $cardnumberMsg;} ?>
<br /><span id="cardnumberMsg" style="color:red"></span>
</p>
<p><label>Card Security Code:</label><br> <input type="text" id="cardsec" name="cardsec">
<?php if(isset($cardsecMsg)) {echo $cardsecMsg;} ?>
<br /><span id="cardsecMsg" style="color:red"></span>
</p>
<p><label>Card Expiration Date:</label><br> <input type="text" id="cardexpdate" name="cardexpdate">
<?php if(isset($cardexpdateMsg)) {echo $cardexpdateMsg;} ?>
<br /><span id="cardexpdateMsg" style="color:red"></span>
</p>
<p><input type="submit" name="PlaceOrder" value="Place Order"></p>
</form><?php }?>
</section>
</div>
<?php include('includes/footer.inc'); ?>
</body>
</html>
Update: This is your answer: change '$itemtext[itemnumber]' into '$itemtext'
This is going wrong because of the way you use quotes. (not the answer but you might want to think about it ;-) )
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
You should not use '$email' but -for example- ...VALUES ('".$email."',...
Learn more about this here: What is the difference between single-quoted and double-quoted strings in PHP?
On another note, your code is not safe. Please use: http://php.net/manual/en/function.mysql-real-escape-string.php
Example:
...VALUES ('".mysql_real_escape_string($email)."',...
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)
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());
}
}
}
}
I've been working on a client's admin panel (A photography company uploading images to a client's gallery), when I took on the role as web developer, it only allowed him to upload 30 images, even though there was 100 file upload boxes. This was fixed simply by changing the for loop to run 100 times. This fixed this problem.
But recently, without even touching the code, my client can only upload 19 images.. I haven't changed this form, he has previously uploaded 40+ images, so I don't quite understand what could have happened.. I've checked the code over and over, and can't quite seem to pinpoint the issue. Could this be server side, as I've recently moved from his old developer's host to my hostgator account. Maybe something in the htaccess? I add this because the image label's update, but not the image itself (I can't find it uploaded either, after it has been posted, but my browser shows it uploading)
Here is the edit gallery code itself, if it gives any assistance to the problem:
<?php
require_once("../conn.php");
require_once("access.php");
require_once("GalleryNavigation.php");
require_once("dThumbMaker.inc.php");
/////////////common varilable
$__table = "devbg_gallery";
$__page = $_SERVER['PHP_SELF'];
$__page2 = "AddGallery.php";
$__id = "ItemID";
$__pagetitle = "GALLERY";
$__uploadfolder = "../myimages/";
$__thumbuploadfolder = "../myimages/thumbs/";
$__imageprefix = "Gallery";
$Thumb_Imgwidth = 200;
$Thumb_Imgheight = 77;
/////////////
if(isset($_POST[ds]))
{
if(count($_POST['DelItem']) > '0')
{
while(list(, $value) = each($_POST['DelItem']))
{
$DelInfo = $value;
$r2 = mysql_query("select * from ".$__table." where ".$__id." = '$DelInfo' ") or die(mysql_error());
$a2 = mysql_fetch_array($r2);
for($i=1;$i<=100;$i++)
{
if(file_exists($__uploadfolder.$a2['ItemImage'.$i]))
{
unlink($__uploadfolder.$a2['ItemImage'.$i]);
unlink($__thumbuploadfolder.$a2['ItemImage'.$i]);
}
}
//delete the product
mysql_query("delete from ".$__table." where ".$__id." = '".$DelInfo."' ") or die(mysql_error());
}
}
}
if(isset($_POST[s100]))
{
$MyProductName = mysql_escape_string(trim(stripslashes(strip_tags($_POST[ProductName]))));
$Description = mysql_escape_string(trim(strip_tags(stripslashes($_POST['Description']))));
$Link = trim(strip_tags(stripslashes($_POST['Link'])));
$TopLabel = cleaninput($_POST['TopLabel'],"mres|he|tr");
$status = $_POST['status'];
$NewTopLabelName = $TopLabel;
if(!empty($_FILES['TopImage']['name']))
{
$NewTopImageName = $__imageprefix.$t.$_FILES['TopImage']['name'];
if(is_uploaded_file($_FILES['TopImage']['tmp_name']))
{
move_uploaded_file($_FILES['TopImage']['tmp_name'], $__uploadfolder.$NewTopImageName);
$NewTopImageName = $NewTopImageName;
$NewTopLabelName = $TopLabel;
//lets make the thumb
$tm = new dThumbMaker;
$load = $tm->loadFile($__uploadfolder.$NewTopImageName);
if($load === true)
{ // Note three '='
$tm->cropCenter($Thumb_Imgwidth, $Thumb_Imgheight);
$tm->build($__thumbuploadfolder.$NewTopImageName);
}
else
{
// Error returned.
$error .= "Could not open the file '".$NewTopImageName."'.\n";
$error .= "The error returned was: ";
$error .= $load;
}
}
}
else
{
$NewTopImageName = $_POST['OldTopImage'];
$NewTopLabelName = $NewTopLabelName;
}
for($i=1;$i<=100;$i++) //This is where I believe the problem is --------------------------------------------------------------------
{
${'NewsItemLabel'.$i} = cleaninput($_POST['ItemLabel'.$i],"mres|he|tr");
$ItemLabels .= "ItemLabel".$i ." = '". cleaninput($_POST['ItemLabel'.$i],"mres|he|tr") ."',";
if(!empty($_FILES['ItemImage'.$i]['name']))
{
${'NewImageName'.$i} = $__imageprefix.$t.$_FILES['ItemImage'.$i]['name'];
if(is_uploaded_file($_FILES['ItemImage'.$i]['tmp_name']))
{
move_uploaded_file($_FILES['ItemImage'.$i]['tmp_name'], $__uploadfolder.${'NewImageName'.$i});
//lets make the thumb
$tm = new dThumbMaker;
$load = $tm->loadFile($__uploadfolder.${'NewImageName'.$i});
if($load === true)
{ // Note three '='
$tm->cropCenter($Thumb_Imgwidth, $Thumb_Imgheight);
$tm->build($__thumbuploadfolder.${'NewImageName'.$i});
$ItemImages .= "ItemImage".$i ." = '". ${'NewImageName'.$i} ."',";
}
else
{
// Error returned.
$error .= "Could not open the file '".${'NewImageName'.$i}."'.\n";
$error .= "The error returned was: ";
$error .= $load;
}
} else { }
}
else
{
${'NewImageName'.$i} = $_POST['OldItemImage'.$i];
}
}
if(empty($error))
{
//update the database
$q1 = "update ".$__table." set
ItemName = '".$MyProductName."',
Description = '".$Description."',
Link = '".$Link."',
TopImage = '$NewTopImageName',
Toplabel = '$NewTopLabelName',
".$ItemImages.$ItemLabels."
status = '".$status."'
where ".$__id." = '".$_POST[$__id]."' ";
mysql_query($q1) or die(mysql_error());
echo "<br><br><center>Gallery Updated</center>";
}
}
if(!empty($_GET[$__id]))
{
$_POST[$__id] = $_GET[$__id];
}
if(!empty($_POST[$__id]))
{
//get the product info
$r1 = mysql_query("select * from devbg_gallery where ".$__id." = '".$_POST[$__id]."' ") or die(mysql_error());
$a1 = mysql_fetch_array($r1);
echo $error;
?>
<form method=post action=EditGallery.php enctype="multipart/form-data">
<table align=center width=740>
<caption align=center><b>Gallery Name:</b></caption>
<tr>
<td align='right'>Event Name:</td>
<td><input type=text class=input name="ProductName" value="<?php echo $a1['ItemName'];?>"></td>
</tr>
<TR>
<td align='right'>Description:</td>
<td><textarea name="Description"cols=60 rows=10><?php echo $a1['Description'];?></textarea></td>
</TR>
<?php
if(!empty($a1['TopImage']))
{
$v = $a1['TopImage'];
echo "<tr>";
echo "<td></td><td><img src='".$__uploadfolder.$v."' width='72' border='0'><br><a href='DeleteImage.php?".$__id."=".$a1[$__id]."&Type=gallery&file=".$v."&img=top'>Delete Image</a></td>";
echo "</tr>";
}
?>
<tr>
<td align='right'>Top Image:</td>
<td><input type=file name=TopImage></td>
</tr>
<tr>
<td align='right'>Top Image Label:</td>
<td><input type=text name=TopLabel value="<?php echo $a1['TopLabel'];?>"></td>
</tr>
<?php
for($i = 1; $i <= 100; $i++)
{
if($a1['ItemImage'.$i] != "")
{
echo "<tr>";
echo "<td></td><td><img src='".$__uploadfolder.$a1['ItemImage'.$i]."' width='72' border='0'><br><a href='DeleteImage.php?".$__id."=".$a1[$__id]."&Type=gallery&file=".$a1['ItemImage'.$i]."&id=".$i."'>Delete Image</a></td>";
echo "</tr>";
}
echo "<TR><TD align='right'>Image $i: </TD><TD><input type=file name='ItemImage$i'></TD></TR>\n\t";
echo "<TR><TD align='right'>Label $i: </td><TD><input type=text name='ItemLabel".$i."' value='".cleaninput($a1['ItemLabel'.$i],"ss|hd|tr")."' size='79'></TD></TR>\n\t";
echo "<input type='hidden' name='OldImage$i' value='".$a1['ItemImage'.$i]."'>";
echo "<input type='hidden' name='OldLabel$i' value='".cleaninput($a1['ItemLabel'.$i],"ss|hd|tr")."'>";
}
?>
<tr>
<td></td>
<td>
<input type="hidden" name="OldTopImage" value="<?php echo $a1['TopImage'];?>">
<input type="hidden" name="OldTopLabel" value="<?php echo $a1['TopLabel'];?>">
<input type="hidden" name=<?php echo $__id;?> value="<?php echo $_POST[$__id];?>">
<input type="submit" name="s100" value="Edit Gallery">
</td>
</tr>
</form>
<?php
exit();
}
if(!empty($_GET[Start]))
{
$Start = $_GET[Start];
}
else
{
$Start = '0';
}
$ByPage = "10";
//get the products list
$r1 = mysql_query("select * from devbg_gallery order by ordering_id ASC limit $Start,$ByPage") or die(mysql_error());
if(mysql_num_rows($r1) == '0')
{
echo "<center>You have no items at the database!</center>";
exit();
}
?>
<form method=post>
<table align=center width=500 cellspacing="0" cellpadding="3">
<tr style="background-color:#b5c3ce; color:white; font-family:verdana; font-size:11; font-weight:bold">
<td>Title</td>
<td>User</td>
<td align='center'>Edit</td>
<td align='center'>Delete</td>
</tr>
<?php
$col = "white";
$i=0;
while($a1 = mysql_fetch_array($r1))
{
$r2 = mysql_query("select * from tbl_register where GID = '".$a1['ItemID']."'") or die(mysql_error());
$a2 = mysql_fetch_array($r2);
$name = $a2['firstname'] . " " . $a2['lastname'];
$i++;
if($col == "white" )
{
$col = "#f3f6f8";
}
else
{
$col = "white";
}
echo "<tr bgcolor=$col>
<td>".$a1['ItemName']."</td>
<td>".$name."</td>";
echo "<td align=center><input type=radio name='".$__id."' value='".$a1[$__id]."'></td>
<td align='center'><input type='checkbox' name='DelItem[]' value='".$a1[$__id]."'></td>
</tr>\n\n";
}
echo "<tr>
<td colspan=4 align=right><br>\n\t<input class=input type=submit name=ds value='Edit Selected'> <input type='submit' class='input' name='ds' value='Delete Selected'></td>
</tr>
</table>
</form>\n\n";
//build the "next" - "prev" navigatioin
$qnav = "select * from ".$__table." order by ItemName ";
$rnav = mysql_query($qnav) or die(mysql_error());
$rows = mysql_num_rows($rnav);
echo "<br><table align=center width=600>";
echo "<td align=center><font face=verdana size=2> | ";
$pages = ceil($rows/$ByPage);
for($i = 0; $i <= ($pages); $i++)
{
$PageStart = $ByPage*$i;
$i2 = $i + 1;
if($PageStart == $Start)
{
$links[] = " <span class=bodybold>$i2</span>\n\t ";
}
elseif($PageStart < $rows)
{
$links[] = " <a class=bodybold href=EditGallery.php?Start=$PageStart>$i2</a>\n\t ";
}
}
$links2 = implode(" | ", $links);
echo $links2;
echo "| </td>";
echo "</table><br>\n";
?>
<?php include("footer.php");?>
If there's any other information I could provide that would help find a solution, I can post it straight up. This problem has really messed with my head, and my client needs his gallery running! Makes me wish I could have coded this myself and got there before his previous developer. Thanks everybody!
A friend of mine figured out that when I moved host, my max_file_uploads setting in my php.ini was set to 20, and that the code you see above loops each image and tries to upload it, even if there is no image, which explains why even if I only tried to upload 1 by itself, it wouldn't upload any after 19. Just a simple setting overlooked.
Changed this to max_file_uploads = 100 in my ini, everything works fine now, client happy!