Separate out array based on array data - php

I want to create a table for documents and allow users to select whether the document is required or not in relation to a task. I need it to check the current status of the document to see if it is already required and if it is mark the tick box as checked. There are currently 4 documents in the database and only 2 associations to 2 of the documents for this particular task.
When there is no association of a document to a task there will be no entry in the database to say that it is not associated it just simple will not be in that table.
The code I have currently will show checkboxes against those 2 documents which have associations however do not show any tick boxes at all for the ones that have no association. I would like it to still show the 3 check boxes, so that the user can change its association, but as default it should check not required. Currently It just shows no tick boxes at all. Below is the PHP snip. Please advise if you would like a screenshot or the DB dumps.
Any help would be greatly appreciated. I'm hoping its just been a long day and I am forgetting something simple.
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result4 = mysql_query($order4);
while ($row4 = mysql_fetch_array($result4)) {
$requirement = $row4['requirement'];
echo '
<td><input type="checkbox" name="req" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="opt" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="not" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>';
So far I have just tried tweaking the requirement = with the final tick box. But as it is staying the same whether i use NULL ect - im guessing im missing something.
Kind Regards,
n00bstacker

You can use the following if statement to identify the situation and respond appropriately:
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result4 = mysql_query($order4);
$_results = mysql_fetch_array($result4);
if (!$_results) {
<<<< OUTPUT THE CHECKBOXES/INPUTS YOU NEED >>>>
} else {
foreach ($_results as $result) {
$requirement = $result['requirement'];
echo '
<td><input type="checkbox" name="req" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="opt" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="not" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
Hope this helps!

Related

Populating html table with database data through user selection in php

So, I have a checkbox that allows the user to select the columns they want to view. So, if the user wants for example to select only 2 columns (say, TicketID and Category) it will only show the data of the ID and the category of the ticket. Here's what I have so far:
form:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<ul>
<li><input type="checkbox" name="filter[]" value="TicketID" >Ticket ID</li>
<li><input type="checkbox" name="filter[]" value="Category" />Category</li>
<li><input type="checkbox" name="filter[]" value="Priority" />Priority</li>
<li><input type="checkbox" name="filter[]" value="Status" />Status</li>
<li><input type="checkbox" name="filter[]" value="InitialDescription" />Initial Description</li>
<li><input type="checkbox" name="filter[]" value="SubmittedDate" />Submitted Date</li>
<li><input type="checkbox" name="filter[]" value="Description" />Status Description</li>
<input type="submit" value="Refresh Filters">
</ul>
</form>
</td>
<td>
<?php
viewTicketTable($_SESSION['userID'],$_POST['filter']);
?>
viewticketTable function:
function viewTicketTable($userID,$columns) {
/* Accepts $userID which will identify the tickets related with the user and
$columns which will filter only the columns that are required and outputs the
table with the columns passed through. */
/*
$columns_array = explode(',', $columns);
foreach($array as $array){
echo $array;
} */
foreach($columns as $filter) {
$filter = $filter . ',' ;
}
$filter = substr($filter, 0, -1);
$query = mysql_query("
SELECT $filter
FROM Ticket
LEFT JOIN TicketHistory
ON Ticket.TicketID = TicketHistory.TicketID
WHERE CustomerID = $userID;
");
/* Creation of the table */
echo '
<table border="1">
<thead>
<tr>';
foreach($columns as $tableHeader) {
$tableHeader = '<th scope="col">' . $tableHeader . '</th>' ;
echo $tableHeader;
}
echo '
</tr>
</thead>
<tbody>
';
/*Looping through the script to print out all the information.*/
while ($row = mysql_fetch_array($query) or die(mysql_error())) {
echo '
<tr>';
foreach($columns as $field) {
echo '<td>' . $row[$field] . '</td>';
}
echo '</tr>
';
}
echo ' </tbody>
</table>';
}
The problem resides in the while loop. row[$field] is only populating the last column instead of populating all of them. Any help?
You have an error in your SQL syntax - you have an extra ; before the " closes
Also, you should use mysql_fetch_assoc in place of mysql_fetch_array as using mysql_fetch_array without specifying a method is going to return a double array.
I fixed it. I'll post the answer in case someone has the same issue.
The problem was fixed here:
$filter = "";
foreach($columns as $c) {
$filter = $filter . $c . ',' ;
}
$filter = substr($filter, 0, -1);
The loop was not assigning the values to the $filter variable so I had to create an external variable. There was also anther error in the foreach loop that I had to fix with an if statement (not the best way of doin it, but it works):
foreach($columns as $field) {
if ($field == 'Ticket.TicketID'){
$field = 'TicketID';
}
echo '<td>' . $row[$field] . '</td>';
}
Ticket.TicketID wasn't accepted in the $row array, so I had to change it to TicketID
Thanks everyone for the help anyway.

INSERT a row per array object

I am in the process of creating a document association tool whereby users can associate documents to a ticket from a pre-existing list of documents.
Thanks to the help of Alberto Ponte I was able to construct the initial radio box system (originally checkbox, changed for obvious reasons) from this question: Separate out array based on array data
Now that I have the radio buttons presenting correctly I am trying to get the data inserted into a MySQL with a row for each document. Following on from this I want to have it look up the table for each object and see if there is an existing entry and update that rather than inset a duplicate entry.
Apologies in advance for the soon to be depreciated code and I will be correcting the code going forward, however that is a much bigger task than I currently have time for.
Also apologies if the code is considered messy. I'm not fantastic at PHP and not too hot on best practices. Any quick pointers are always welcome.
Display code:
<?php
include "../includes/auth.php";
include "../includes/header.php";
## Security ########################################################
if ($company_id != 1 OR $gid < 7) {
echo' <div class="pageheader">
<div class="holder">
<br /><h1>Access Denied <small> Your attempt has been logged</small></h1>
</div>
</div>
';
exit();
}
// GET Values ###################################################
$jat_id = intval($_GET['id']);
$div_id = intval($_GET['div_id']);
## Page Start ########################################################
echo '
<div class="pageheader">
<div class="holder">
<br /><h1>Clovemead Job Management Platform<small> Welcome...</small></h1>
</div>
</div>
<div class="well5" style="width:1000px !important;">
<h3>Create Document Association</h3>
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>
<form method="post" action="create-doc-assoc-exec.php">
<input type="hidden" value="'.$doc_id.'" name="doc_id">
<input type="hidden" value="'.$jat_id.'" name="jat_id">
<input type="hidden" value="'.$div_id.'" name="div_id">';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result400 = mysql_query($order4);
$_results = mysql_fetch_array($result400);
if (!$_results) {
echo '
<td><input type="radio" name="req0" value="2"></td>
<td><input type="radio" name="req0" value="1"></td>
<td><input type="radio" name="req0" value="0" checked ></td>';
} else {
foreach ($_results as $result400) {
$requirement = $_results['requirement'];
}
$name = "req".$doc_id;
echo '
<input type="hidden" value ="'.$name.'" name="name">
<td><input type="radio" name="'.$name.'" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>
<input type="submit" name="submit value" value="Create Document Association" class="btn success Large"></form>';
$order2 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$dbname = $row2['division_dbname'];
$order3 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type = $row3['type'];
$type2 = strtolower($type);
echo '
<input type="button" value="Back" onclick="window.location='./view-'.$type2.'.php?id='.$jat_id.''" class="btn primary Large">
';
}}
echo '
</div>';
include "../includes/footer.php";
?>
Execute Code:
<?php
include "../includes/dbconnect.php";
$name = $_POST['name'];
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$doc_id = intval($_POST['doc_id']);
$jat_id = intval($_POST['jat_id']);
$div_id = intval($_POST['div_id']);
$req = intval($_POST[$name]);
$req_blank = intval($_POST['req0']);
if ($req_blank == 0) {
$requirement = 0;
} elseif ($req_blank == 1) {
$requirement = 1;
} elseif ($req_blank == 2) {
$requirement = 2;
} elseif ($req == 0) {
$requirement = 0;
} elseif ($req == 1) {
$requirement = 1;
} elseif ($req == 2) {
$requirement = 2;
}
foreach ($doc_id as $doc_id2) {
$order = "INSERT INTO document_assoc (jat_id, dept_id, doc_id, requirement) VALUES ('$jat_id', '$div_id', '$doc_id2', '$requirement')";
$result = mysql_query($order);
$order1 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result1 = mysql_query($order1);
while ($row1 = mysql_fetch_array($result1)) {
$dbname = $row1['division_dbname'];
$order2 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$type = $row2['type'];
$type2 = strtolower($type);
if($result){
header("location:view-$type2.php?id=$jat_id&creation=success");
} else {
header("location:view-$type2.php?id=$jat_id&creation=failed");
}
}}
}
?>
A few reference points:
$doc_id is the ID of each document which is to be passed over as an array for use in a (i believe) foreach insert
$jat_id is the ticket id documents are being associated to
$div_id is the department the ticket is associated
And the radio boxes are to decider the requirement of each document. To be passed over inline with $doc_id
What I have tried:
After a fair bit of searching - finding nothing - rechecking my terminology and searching again I managed to find the suggestion of using base64_encode(serialize()) on the arrays but I could not get this to work.

Form only processes values from the last list on the page (PHP/MySQL)

I have a form for users to create a daily mealplan using recipes from our database. The processes are as follows:
1) An admin selects 2 recipes for each meal (Lunch and/or Dinner), for the desired date. These selections are what will be used to populate the customer meal select lists.
2) A customer selects 1 recipe for each meal available, for the desired date.
The PROBLEM:
The form only seems to be processing the values selected from the last list displayed on the page and I am not sure why.
Here's the code sections I've been working with. (I can post more if necessary)
// Create a new Meal Plan object
$MPObj = new MealPlan($date);
$MPObj->load($dbDate,$dbDate); // Just want this one day
$minshow = 1;
$defaultServings = 1;
// Read in a list of Meals and Recipes
$rc = DBUtils::fetchColumn( $db_table_meals, 'meal_name', 'meal_id', 'meal_id' );
$mealList = DBUtils::createList($rc, 'meal_id', 'meal_name');
array_unshift_assoc($mealList, 0, ""); // add an empty element to the list
--
$sql = "SELECT mplan_date,
mplan_recipe,
recipe_name,
meal_name,
recipe_serving_size
FROM recipe_mealplans
LEFT JOIN $db_table_meals ON meal_id = mplan_meal
LEFT JOIN $db_table_recipes ON recipe_id = mplan_recipe
WHERE mplan_date = '".mysql_real_escape_string($dbDate)."'
AND mplan_owner = '".mysql_real_escape_string($user_SK)."'
ORDER BY recipe_name";
$rc = $DB_LINK->Execute($sql);
DBUtils::checkResult($rc, NULL, NULL, $sql);
--
while (!$rc->EOF) {
if ($rc->fields['meal_name'] === "Lunch") {
$recipeListLunch[($rc->fields['mplan_recipe'])] = $rc->fields['recipe_name'] . " (" . $rc->fields['recipe_serving_size'] . ")";
}
if ($rc->fields['meal_name'] === "Dinner") {
$recipeListDinner[($rc->fields['mplan_recipe'])] = $rc->fields['recipe_name'] . " (" . $rc->fields['recipe_serving_size'] . ")";
}
$rc->MoveNext();
}
--
<form action="index.php?m=meals&dosql=update&view=daily&date=<?php echo $date; ?>" method="post" enctype="multipart/form-data">
<table cellspacing="1" cellpadding="4" border="0" width="80%" class="data">
<tr>
<th align="center">Remove</th>
<th align="center">Meal</th>
<th align="center">Servings</th>
<th align="center"></th>
<th align="center">Menu Options</th>
</tr>
<?php
// Print out all the existing meals, and some new ones
for ($i = 0, $maxshow = 1; $i < (isset($MPObj->mealplanItems[$dbDate]) && ($i < $maxshow) ? count($MPObj->mealplanItems[$dbDate]) : 0) + $minshow; $i++) {
if ($i < (isset($MPObj->mealplanItems[$dbDate]) ? count($MPObj->mealplanItems[$dbDate]) : 0)) {
// If it is an existing meal item, then set it
$meal = $MPObj->mealplanItems[$dbDate][$i]['meal'];
$servings = $MPObj->mealplanItems[$dbDate][$i]['servings'];
$recipe = $MPObj->mealplanItems[$dbDate][$i]['id'];
} else {
// It is a new one, give it blank values
$meal = NULL;
$servings = $defaultServings;
$recipe = NULL;
}
/* Display Meal Lists to select from */
// Lunch
echo '<tr>';
echo '<td align="center">';
echo '<input type="checkbox" name="delete_'.$i.'" value="yes"></td>';
echo '<td align="center">';
echo DBUtils::arrayselect($mealList, 'meal_id_'.$i, 'size=1', $meal);
echo '</td><td align="center">';
echo '<input type="text" autocomplete="off" name="servings_'.$i.'" value="' . $servings . '" size="3">';
echo '</td><td align="center">';
echo '<input type="hidden" autocomplete="off" name="repeat_'.$i.'" value="1" size="3"> ';
echo '</td><td align="center">';
echo DBUtils::arrayselect($recipeListLunch, 'recipe_id_'.$i, 'size=1', $recipe);
echo '</td></tr>';
// Dinner
echo '<tr>';
echo '<td align="center">';
echo '<input type="checkbox" name="delete_'.$i.'" value="yes"></td>';
echo '<td align="center">';
echo DBUtils::arrayselect($mealList, 'meal_id_'.$i, 'size=1', $meal);
echo '</td><td align="center">';
echo '<input type="text" autocomplete="off" name="servings_'.$i.'" value="' . $servings . '" size="3">';
echo '</td><td align="center">';
echo '<input type="hidden" autocomplete="off" name="repeat_'.$i.'" value="1" size="3"> ';
echo '</td><td align="center">';
echo DBUtils::arrayselect($recipeListDinner, 'recipe_id_'.$i, 'size=1', $recipe);
echo '</td></tr>';
} // end for
?>
</table>
<?php
if isset($recipeListLunch) || isset($recipeListDinner)) {
echo '<input type="submit" value="Update Menu" class="button">';
}
?>
</form>
The lunch and dinner code sections are using the same values for the name attributes. You need to give them different names altogether or append [] to create an array.
EDIT: For example,
echo '<input type="checkbox" name="delete_'.$i.'[]" value="yes"></td>';
Notice the [] inside the double quotes for the value of the name attribute. You'd need to do this to all of them. I am not familiar with DBUtils::arrayselect so I am not if sure the following will work.
echo DBUtils::arrayselect($mealList, 'meal_id_'.$i.'[]', 'size=1', $meal);
But as long as you have more than one field with the same name, they will overwrite each other. With making these fields into arrays, you also need to change the code that processes the form so that it can process an array.
EDIT: You could also increment $i between the lunch and dinner sections instead of creating an array. Incrementing $i within the loop would require changing the for parameters, but at least you wouldn't have to change the code that processes the form.
The for line seems very convoluted to me (and inefficient). A single line of code is not more efficient if it runs unnecessary calculations on each iteration of a loop. If I understand the intention correctly, try replacing the for line with the following.
$maxshow = 1;
$num_items = isset($MPObj->mealplanItems[$dbDate]) ? count($MPObj->mealplanItems[$dbDate]) : 0;
if ($num_items + $minshow < $maxshow) $maxshow = $num_items + $minshow;
$maxshow = $maxshow * 2; //double it because we will be incrementing $i within the loop
for ($i = 0; $i < $maxshow; $i++) {
And then add the following line between your original lunch and dinner sections (the ones without []).
$i++;
That effectively assigns different names to each field without creating arrays.

PHP image upload in admin section only allowing client to upload 19 images

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!

PHP/HTML - Trouble with form inputs - Turning multiple post's into just one

I am busy creating an order system.
I am having issues trying to create a form that requires only one order button.
Currently the form is for each product result. The user has the ability to enter in a quantity desired of a certain product, then can order the product based on the quantity chosen. The item id and quantity chosen are then added to sessions.
The problem with this, is that if there are 5 items, there are 5 order buttons.
I am trying to simplify this, where for 5 products, there will be only one order button controlling the entire selection of products.
Here is the code relating to this:
//Now we search for our search term, in the field the user specified
$dataQuery = "SELECT * FROM `products` WHERE upper(`desc`) LIKE '%"
. implode("%' AND upper(`desc`) LIKE '%", $keywords_array)
. "%' ORDER BY `desc`";
$data = mysql_query($dataQuery) or die(mysql_error());
$tempVar = 0;
//And we display the results
while ($result = mysql_fetch_array($data)) {
$prId = $result['id'];
$prRefCode = $result['refCode'];
$prDesc = $result['desc'];
$prPack = $result['pack'];
$prMeasure = $result['measure'];
$prQuantity = $result['quantity'];
$prDeptCode = $result['deptCode'];
$prTaxable = $result['taxable'];
$prPrice1 = $result['price1'];
$prPrice2 = $result['price2'];
$prCrdCode = $result['crdCode'];
$prCost1 = $result['cost1'];
$prCost2 = $result['cost2'];
if ($tempVar == 0) {
$pageContent .= '
<p><u>All prices are inclusive of VAT</u></p>
<table class="searchResults" border="1" align="center" width="90%">
<thead>
<tr>
<th>Stock Code</th>
<th>Description</th>
<th>Packsize</th>
<th>Price</th>
<th>In-Stock?</th>
<th>Quantity</th>
<th>Submit</th>
</tr>
</thead>
<tbody>
';
}
$pageContent .= '
<tr>
<td>' . $prId . '</td>
<td>' . $prDesc . '</td>
<td>' . $prPack . 'x' . $prSize . ' ' . $prMeasure . '</td>
<td>R' . $prPrice1 . '</td>
';
if (empty($prQuantity)) {
$pageContent .= '
<td>No</td>
';
} else {
$pageContent .= '
<td>Yes</td>
';
}
$pageContent .= '
<form id="validated" action="" method="post">
<td>
<div>
<input type="text"
onkeydown="return ( event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"
name="quantity" size ="2"
value ="1"
style="background: #F4F4F4;
font-family: Monaco, monospace;" />
</div>
</td>
<td>
<div>
<input type="hidden" name="id" value="' . $prId . '" />
<input type="submit" name="action" value="Order" />
</div>
</td>
</form>
</tr>
';
$tempVar ++;
}
//This counts the number of results - and if there wasn't any it gives them a little message explaining that
$anymatches = mysql_num_rows($data);
if ($anymatches == 0) {
$pageContent .= '
<p>Sorry, but we can not find an entry to match your query</p>
<!-- end .aliLeft --></div>
';
}
if ($anymatches > 0 and count($tempVar) == count($anymatches)) {
$pageContent .= '
</tbody>
</table>
<!-- end .aliLeft --></div>
';
}
And here is the code controlling the instance of a user clicking on the order button:
if (!isset($_SESSION['order']))
{
$_SESSION['order'] = array();
}
if (!isset($_SESSION['quantity']))
{
$_SESSION['quantity'] = array();
}
if (isset($_POST['action']) and $_POST['action'] == 'Order' and $_POST['quantity'] > 0)
{
// Add item to the end of the $_SESSION['order'] array
$_SESSION['order'][$_POST['id']] = $_POST['id'];
$_SESSION['quantity'][$_POST['id']] = $_POST['quantity'];
header('Location: .');
exit();
}
And here is the code that configures the quantity value for totalling the order:
$total = 0;
if (count($order) > 0)
{
foreach ($order as $product)
{
mysql_data_seek( $totalsSql, 0); //<- this line, to reset the pointer for every EACH.
while($row = mysql_fetch_assoc($totalsSql))
{
$prodId = $row['id'];
$prodPrice1 = $row['price1'];
$prodQuantity = $quantity[$prodId];
if ($product == $prodId)
{
$total += ($prodPrice1*$prodQuantity);
break;
}
}
}
}
As you can see, when the user searches for a product, the mysql table is queried, if results are found, then they are returned.
In this process, the form is created for each result.
What I am trying to do, is extend this form to cover the entire set of results, then have only one input for "Order", so essentially, the user can enter quantities on various products, then have those products and quantities added to their order.
Does anyone have any advice on how i would go about this task?
I would appreciate any input what so ever, thank you!
I would change the name for each input to quantity[$id] where id is the id for each field. You would get that result back as an associative array in php where the key is the id you have provided between the [].
That way, you can iterate over the array and process multiple fields.
Encode the product identifier in the field name:
<input type="text" onkeydown="…" name="quantity<?php echo $prId; ?>" size ="2" value ="1" style="…" />
In your process script you then do something like:
foreach ($_POST as $sKey => $sQuantity) {
if (preg_match('/^quantity([1-9][0-9]*)$/DX', $sKey, $asMatch) === 1) {
// User added $sQuantity times product $asMatch[1]
}
}

Categories