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.
Related
Currently I am constructing a form where I'd like to include the following work list by date functionality:
User selects a date
All IDs and Names of active users are drawn from an established MySQL table, presented in rows
2 new fields for each ID/User are presented with multiple selections
The ID and the 2 new multiple selection fields are passed to another table with columns ID, date, and 2 columns (AM Work and PM Work) to add the results of the multiple selection fields.
I understand that one field holding results of the multiple selection fields will be held and that there will be multiple date and ID rows to store these values, that is not a problem for me.
I've created the form table with the ID and name retrieved from the established table, and included the two fields where my multiple selections are the same in both, retrieved from another table of work types.
I first tried multiple foreach loops to pass the ID and then each AM work type selected, and then each PM work type selected. I can do this for one record, however I'd like to be able to take multiple IDs and parse multiple AM and PM multi-select work types.
//This is part of a loop that covers the AM work entry that I've tried already:
// IF THE VALIDATION PASSES - SEND THE INFORMATION TO THE DB
if ($valid) {
// SET NEW VALUES FOR THE EXISTING RECORD
$pdo = Database::connect();
pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
//INSERT THE WORK DATA INTO THE DATABASE
$capture_id = "";
foreach($_POST["id"] as $key => $capture_id){
//REARRANGE DATE FOR INSERT
$work_date = date('Y-m-d', strtotime($work_date));
//CAPTURE EACH VALUE FROM THE ARRAYS AS VARIABLES
$id = $_POST["id"][$key];
// FOR EACH PIECE OF AM WORK ADD TO WORK HISTORY TABLE
$capture_am_work = "";
foreach($_POST["$am_work"] as $key => $capture_am_work){
$am_work = $_POST["am_work"][$key];
//INSERT THE AM DATA INTO work_history_table
$sql = "INSERT INTO work_history_table (date, id, am_activity_id)
values(?,?,?,?)";
$q = $pdo->prepare($sql);
$q->execute(array($work_date, $id, $am_work, $pm_work));
}
}
}
Form details are:
<form class="form-horizontal" action="work_scheduling.php" method="post" enctype="multipart/form-data">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>AM Work</th>
</tr>
</thead>
<tbody>
<?php
$pdo = Database::connect();
$sql = "SELECT * FROM user WHERE status = 'Active'";
$sth = $pdo->prepare($sql);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo '<tr>';
echo '<td style="text-align: center; vertical-align: middle;"><input name="id[]" type="text" placeholder="id" value="';
echo $row['id'];
echo '" readonly></td>';
echo '<td style="text-align: center; vertical-align: middle;"><input name="name[]" type="text" placeholder="id" value="';
echo $row['name'];
echo '" readonly></td>';
echo '<td style="text-align: center; vertical-align: middle;">';
echo '<select name="am_work[]" class="chosen-select" data-placeholder="Click To Select AM Work" multiple tabindex="10">';
echo '<option value=""></option>';
$am_work_query = mysqli_query($con, "SELECT id, diary_task_name FROM diary_task_category WHERE status='Active'");
while ($am_work_rows = $am_work_query->fetch_array(MYSQLI_ASSOC)) {
$am_work_value = $am_work_rows['id'];
echo '<option value="';
echo $am_work_value;
echo '">';
echo $am_work_rows['id'],": ",$am_work_rows['diary_task_name'];
echo '</option>';
}
echo '</select>';
echo '</td>';
echo '</tr>';
}
Database::disconnect();
}
?>
</tbody>
</table>
<div class="form-actions">
<button type="submit" class="btn btn-success btn-sm">Update</button>
</div>
</form>
******* ANSWER - CODE USED SUCCESSFULLY *******
//table setup
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
$id2 = $row['id'];
$name = $row['name'];
echo '<tr>';
echo '<td><input name="id2[]" type="number" placeholder="id2" value="';
echo $id2;
echo '"></td>';
echo '<td><input name="name[]" type="text" placeholder="name" value="';
echo $name;
echo '"></td>';
echo '<td>';
echo '<select name="id2[';
echo $id2;
echo '][am_work][]" class="chosen-select" data-placeholder="Click To Select AM Work" multiple tabindex="10">';
echo '<option value=""></option>';
$am_work_query = mysqli_query($con, "SELECT id, diary_task_name FROM diary_task_category WHERE status='Active'");
while ($am_work_rows = $am_work_query->fetch_array(MYSQLI_ASSOC)) {
$am_work_value = $am_work_rows['id'];
echo '<option value="';
echo $am_work_value;
echo '">';
echo $am_work_rows['id'],": ",$am_work_rows['diary_task_name'];
echo '</option>';
}
echo '</select>';
echo '</td>';
echo '</tr>';
}
//loop
foreach($_POST["id2"] as $record_id => $value){
$val1 = $record_id;
foreach($value["am_work"] as $key => $am_work_value){
$val2 = $value["am_work"][$key];
//INSERT THE AM DATA INTO work_history_table
$sql = "INSERT INTO work_history_table (date, horse_id, am_activity_id)
values(?,?,?)";
$q = $pdo->prepare($sql);
$q->execute(array($work_date, $val1, $val2));
}
}
ultimately the expected results would be entries into a table that iterates through each ID, and then for each id, iterate through each multi-selected items.
Please be gentle - I'm completely new to all of this!
I am doing attendance management system but I am unable to understand. please help me
<form method="post">
<div class="table-responsive py-4">
<table class="table table-flush" id="datatable-basic">
<thead class="thead-light">
<tr>
<th>Name</th>
<th>Father's Name</th>
<th>Hall Ticket</th>
<th>Department</th>
<th>Attendace</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_POST["search_students"])){
$department=$_POST['department'];
$sql = "SELECT * FROM student_info WHERE department='$department'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["father_name"]."</td>";
echo "<td>".$row["hall_ticket"]."</td>";
echo "<td>".$row["department"]."</td>";
echo "<td>
Present <input type='radio' name='attendance[".$row['hall_ticket']."][".$row['department']."]' value='Present'>
Absent <input type='radio' name='attendance[".$row['hall_ticket']."][".$row['department']."]' value='Absent'>
</td>";
echo "</tr>";
}
}
}
?>
</tbody>
</table>
</div>
<div class="col-lg-12 mb-3">
<button type="submit" name="mark_attendance" class="btn btn-success">Mark Attendance</button>
</div>
</form>
</div>
<?php
if(isset($_POST["mark_attendance"])){
$attendance=$_POST['attendance'];
foreach ($attendance as $key => $value) {
if($value=="Present") {
$query="Insert into attendance (hall_ticket,attendance) values ('$key','Present')";
$insertAttendance=$conn->query($query);
}
else {
$query="Insert into attendance (hall_ticket,attendance) values ('$key','Absent')";
$insertAttendance=$conn->query($query);
}
}
if($insertAttendance){
echo "Attendance Updated Sucessfully";
}
}
?>
</div>
Here i want 2 key to store into my database as hall ticket value and department value.
attendance[".$row['hall_ticket']."][".$row['department']."]
how to use both variables to store into my db. I want to store each table person attendance with their department and hallticket. i will get the hallticket if i remove department from name and simply use $key to store the values.
Try following code:
HTML Code (Created dummy data for reference):
<form action='new.php' method="POST" >
Presnt<input type="radio" name="attendance[111][555]" value="present"><br>
Absent<input type="radio" name="attendance[111][555]" value="absent"><br><br>
Presnt<input type="radio" name="attendance[222][555]" value="present"><br>
Absent<input type="radio" name="attendance[222][555]" value="absent"><br><br>
Presnt<input type="radio" name="attendance[333][555]" value="present"><br>
Absent<input type="radio" name="attendance[333][555]" value="absent"><br>
<input type="submit">
</form>
PHP Code:
<?php
$attendance=$_POST['attendance'];
$data = "";
foreach ($attendance as $key => $value) {
$department = array_keys($value)[0];
$data.="('". $key ."','". $department ."', '" . $value[$department] . "'),";
}
$query = "INSERT INTO attendance (hall_ticket,department,attendance) VALUES " .
rtrim($data, ",");
// Your Query will look like:
// Query = "INSERT INTO attendance (hall_ticket,department,attendance)
// VALUES ('111','555', 'present'),
// ('222','555', 'present'),
// ('333','555', 'absent')";
// Now execute your query
$conn->query($query);
echo $sql;
?>
Note :
Never hit the database in for loops
Even this code will work for you but this is open for SQL injection, you should use a prepared statement to build and execute you query.
so you $attendance is
$attendance=array(
$row['hall_ticket'] => array(
$row['departement']"=> [" present " OR "absence"]
);
this what i understand
my solution is
foreach ($attendance as $hall => $departements) {
foreach($departements as departement => $value){
$req="INSERT INTO attendance (hall_ticket,department,attendance)
values ('".$hall. "','". $departement ."' ,'". $value ."')";
$insertAttendance=mysqli_query($dataBaseConnect,$req);
}
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!
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.
while ($row= mysql_fetch_array($result, MYSQL_ASSOC))
{ $id=$row[id];
$html=<<<html
<tr><td>
<input style="float:left" type="checkbox" name="mycheckbox" value="$id">
<span style="float:left">$row[content]</span>
<span style="color:black;float:right">$row[submitter]</span></td></tr>
html;
echo $html;
}
Since the HTML code is generated dynamically, I don't know how long the array "mycheckbox" is and I don't know what checkboxes are ticked or unticked(This is determined by users). How to retrieve the values of ticked checkboxes using PHP?
The way you have it now, mycheckbox will get overwritten and act more like a radio button.
You probably want:
<input style="float:left" type="checkbox" name="mycheckbox[]" value="$id">
PHP will push the checked values into an array: $_GET['mycheckbox']
<?php
$values = $_GET['mycheckbox'];
$count = count($values);
echo 'Selected values are: <br/>';
foreach($values as $val) {
echo $val . '<br/>';
}
echo 'Total Length is: ' . $count . '<br/>';