I have a dynamic form where input name='' value is from database, but how can I define it in function? Or you have any better suggestions how to write this code.
<?php
$query = "SELECT * FROM product_types";
$input_product_attribute = mysqli_query($connection,$query);
while($row = mysqli_fetch_array($input_product_attribute)) {
$product_type_ID = $row['Product_type_ID'];
$label_name = $row['Product_type_label_name'];
$product_type_attribute = $row['Product_type_attribute'];
$label_comment = $row['Product_type_label_comment'];
?>
<div id='div_<?php echo $product_type_ID ?>' class="divParameter" style="display: none;">
<div class="form-group">
<label for='<?php echo $label_name ?>'><?php echo $label_name ?></label>
<input id='<?php echo $label_name ?>' type="text" name='<?php echo $product_type_attribute ?>' class="form-control">
<label><?php echo $label_comment ?></label>
</div>
</div>
<?php } ?>
<?php
function createRows(){
if (isset($_POST['submit'])) {
global $connection;
file_put_contents('debug.txt', json_encode($_POST)."\n", FILE_APPEND );
$productType = $_POST['select_box'];
$productAttribute = $_POST['?']; //PROBLEM!!
$productType = mysqli_real_escape_string($connection, $productType );
$productAttribute = mysqli_real_escape_string($connection, $productAttribute );
$query = "INSERT INTO products(Product_type,Product_size) ";
$query .= "VALUES ('$productType', '$productAttribute') ";
}
?>
You can make your form and php code is below way
HTML
<label for='<?php echo $label_name ?>'><?php echo $label_name ?></label>
//solution to your problem, see name attribute
<input name='dynamic_values[<?php echo $product_type_attribute ?>]' id='<?php echo $label_name ?>' type="text" class="form-control">
PHP
<?php
function createRows(){
if (isset($_POST['submit'])) {
global $connection;
file_put_contents('debug.txt', json_encode($_POST)."\n", FILE_APPEND );
$productType = $_POST['select_box'];
//$productAttribute = $_POST['?']; //PROBLEM!! //problem solved below
$productType = mysqli_real_escape_string($connection, $productType );
//$productAttribute = mysqli_real_escape_string($connection, $productAttribute );
//solution to your problem
if( !empty($_POST['dynamic_values']) ) {
foreach( $_POST['dynamic_values'] as $val ) {
$query = "INSERT INTO products(Product_type,Product_size) ";
$val = mysqli_real_escape_string($connection, $val );
$query .= "VALUES ('$productType', '$val') ";
}
}
}
}
?>
If you face any problem, let me know in comments.
I do it this way:
function update_products($products), function insert_products($products), unction find_products_by_id($id, $options=[])....
EXAMPLE
function insert_products($products) {
global $db;
$errors = validate_products($products);
if(!empty($errors)) {
return $errors;
}
$sql = "INSERT INTO products ";
$sql .= "(cat_id, name, code, content) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $products['cat_id']) . "',";
$sql .= "'" . db_escape($db, $products['name']) . "',";
$sql .= "'" . db_escape($db, $products['code']) . "',";
$sql .= "'" . db_escape($db, $products['content']) . "'";
//echo $sql;
$sql .= ")";
$result = mysqli_query($db, $sql);
// For INSERT statements, $result is true/false
if($result) {
return true;
} else {
// INSERT failed
echo mysqli_error($db);
db_disconnect($db);
exit;
}
}
Related
Here is the error I get when I submit the updated form: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id='19' LIMIT 1' at line 1
Here is the PHP and HTML for the edit (update) page.
<?php
require_once('../../../private/initialize.php');
if(!isset($_GET['id'])) {
redirect_to(url_for('/staff/subjects/index.php'));
}
$id = $_GET['id'];
if(is_post_request()) {
// Handle form values sent by new.php
$subject = [];
$subject['id'] = $id;
$subject['menu_name'] = $_POST['menu_name'] ?? '';
$subject['description'] = $_POST['description'] ?? '';
$result = update_subject($subject);
if($result === true) {
redirect_to(url_for('/staff/subjects/show.php?id=' . $id));
} else {
$errors = $result;
}
} else {
$subject = find_subject_by_id($id);
}
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
mysqli_free_result($subject_set);
?>
<?php $page_title = 'Edit Subject'; ?>
<?php include(SHARED_PATH . '/staff_header.php'); ?>
<a class="back-link" href="<?php echo url_for('/staff/subjects/index.php'); ?>">« Back to List</a>
<div class="subject edit">
<h1>Edit Subject</h1>
<?php echo display_errors($errors); ?>
<form action="<?php echo url_for('/staff/subjects/edit.php?id=' . h(u($id))); ?>" method="post">
<dl>
<dt>Subject name</dt>
<dd><input type="text" name="menu_name" value="<?php echo h($subject['menu_name']); ?>"</dd>
</dl>
<dl>
<dt>Description</dt>
<dd>
<textarea name="description" cols="60" rows="10"><?php echo h($subject['description']); ?></textarea>
</dd>
</dl>
<div id="operations">
<input type="submit" value="Edit Subject" />
</div>
</form>
</div>
<?php include(SHARED_PATH . '/staff_footer.php'); ?>
This is my PHP update to update the record.
//UPDATE SUBJECTS
function update_subject($subject) {
global $db;
$errors = validate_subject($subject);
if(!empty($errors)) {
return $errors;
}
$sql = "UPDATE subjects SET ";
$sql .= "menu_name='" . db_escape($db, $subject['menu_name']) . "', ";
$sql .= "description='" . db_escape($db, $subject['description']) . "', ";
$sql .= "WHERE id='" . db_escape($db, $subject['id']) . "' ";
$sql .= "LIMIT 1";
$result = mysqli_query($db, $sql);
// For UPDATE statements, $result is true/false
if($result) {
return true;
} else {
// UPDATE failed
echo mysqli_error($db);
db_disconnect($db);
exit;
}}
You have a comma ( , ) right before the WHERE
$sql .= "description='" . db_escape($db, $subject['description']) . "', ";
$sql .= "WHERE id='" . db_escape($db, $subject['id']) . "' ";
change it to:
$sql .= "description='" . db_escape($db, $subject['description']) . "' ";
Remove the , at the last from this line :
$sql .= "description='" . db_escape($db, $subject['description']) . "', ";
Use this :
$sql .= "description='" . db_escape($db, $subject['description']) . "' ";
Can anyone help me with the pagination? I am trying this code on pagination and the pages are showing but when clicked on the pages like Next or the number with links it gives a syntax error.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?page=2' at line 1"
My tables data is around 250 and I wanted to limit it to 50 data per page.
Here is my code: (pagination section - is the problem)
<link rel="stylesheet" type="text/css" href="css/navbar.css">
<?php include 'navbar.php';?>
<br>
<?php
if(!isset($_GET['table'])){
echo 'You must assign a table to view.';
exit;
}
session_start();
//Connect here
$conn = mysqli_connect("localhost", "root", "", "dkusers");
$table = mysqli_real_escape_string($conn, $_GET['table']);
$fields = array();
$q = mysqli_query($conn, "SHOW COLUMNS FROM " . $table) or die(mysqli_error($conn));
while($r = mysqli_fetch_assoc($q)) $fields[count($fields)] = $r['Field'];
echo '<b><font size="4">Table: </b>', $table, '</font><br>';
// -----------------INSERT-----------------
if(isset($_POST['action']) && $_POST['action'] == "Insert"){
if(!isset($_POST['insert'])){
echo '<h3>Insert Row</h3>';
echo '<form method="post"><input type="hidden" name="action" value="' . $_POST['action'] . '" />';
echo '<table border="1" cellpadding="7"><tr><th>Field</th><th>Value</th><th>MD5</th></tr>';
foreach($fields as $key => $value){
echo '<tr><td>' . $value . ':</td><td><input type="text" name="field_' . $value . '" /></td><td><input type="checkbox" name="md5_' . $value . '" /></td></tr>';
}
echo '<tr><td><input type="submit" name="insert" value="Submit" /></td><td colspan="2">Back</td></tr></table></form>';
exit;
}else{
$first = true;
$query = "INSERT INTO " . $table;
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = substr($key, 6);
$query .= sprintf("%s%s", ($first) ? " (" : ",", $key);
$first = false;
}
}
$query .= ") VALUES";
$first = true;
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = substr($key, 6);
$query .= sprintf("%s'%s'", ($first) ? " (" : ",", (isset($_POST['md5_' . $key])) ? md5($value) : $value);
$first = false;
}
}
$q = mysqli_query($conn, $query . ")");
if($q) echo 'Successfully inserted row into table!<br/><br/>'; else echo mysqli_error($conn) . '<br/><br/>';
}
}
// -----------------DELETE-----------------
if(isset($_POST['action']) && $_POST['action'] == "Delete"){
if(!isset($_POST['rows'])){
echo 'You didn\'t send any rows to delete.<br/><br/>';
}else{
$count = 0;
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
$query = "DELETE FROM " . $table . "";
$row = $_SESSION['store'][$_POST['rows'][$i]];
$first = true;
foreach($row as $key => $value){
$query .= sprintf(" %s %s = '%s'", ($first) ? "WHERE" : "AND", $key, $value);
$first = false;
}
$q = mysqli_query($conn, $query . " LIMIT 1");
if(!$q) echo mysqli_error($conn) . '<br/>';
$count += mysqli_affected_rows($conn);
}
echo 'Successfully deleted ' . $count . ' row(s)!<br/><br/>';
}
}
// -----------------MODIFY-----------------
if(isset($_POST['action']) && $_POST['action'] == "Modify"){
if(!isset($_POST['rows'])){
echo 'You didn\'t send any rows to modify.<br/><br/>';
}else if(isset($_POST['modify'])){
$count = 0;
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
$first = true;
$query = "UPDATE " . $table . " SET";
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = explode("_", $key, 3);
if($key[1] == $i){
$query .= sprintf(((!$first) ? "," : "") . " %s = '%s'", $key[2], (isset($_POST['md5_' . $key[1] . '_' . $key[2]])) ? md5($value) : $value);
$first = false;
}
}
}
$row = $_SESSION['store'][$_POST['rows'][$i]];
$first = true;
foreach($row as $key => $value){
$query .= sprintf(" %s %s = '%s'", ($first) ? "WHERE" : "AND", $key, $value);
$first = false;
}
$q = mysqli_query($conn, $query . " LIMIT 1");
if(!$q) echo mysqli_error($conn) . '<br/>';
$count += mysqli_affected_rows($conn);
}
echo 'Successfully updated ' . $count . ' row(s)!<br/><br/>';
}else{
echo '<h3>Modify Row</h3>';
echo '<form method="post"><input type="hidden" name="action" value="' . $_POST['action'] . '" />';
for($i = 0;$i < count($_POST['rows']);$i++) if($_POST['rows'][$i] < count($_SESSION['store'])) echo '<input type="hidden" name="rows[]" value="' . $_POST['rows'][$i] . '" />';
echo '<table border="1" cellpadding="7"><tr><th>Field</th><th>Value</th><th>MD5</th></tr>';
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
if($i != 0) echo '<tr><td colspan="3"><hr/></td></tr>';
$row = $_SESSION['store'][$_POST['rows'][$i]];
foreach($row as $key => $value){
echo '<tr><td>' . $key . ':</td><td><input type="text" name="field_' . $i . '_' . $key . '" value="' . $value . '" /></td><td><input type="checkbox" name="md5_' . $i . '_' . $key . '" /></td></tr>';
}
}
echo '<tr><td><input type="submit" name="modify" value="Submit" /></td><td colspan="2">Back</td></tr></table></form>';
exit;
}
}
// -----------------SEARCH-----------------
echo '<br><form method="post">Search: <input type="text" name="filter" value="' . ((isset($_POST['filter'])) ? $_POST['filter'] : '') . '"/><br/>Filter by: <br/>';
for($i = 0;$i < count($fields);$i++) echo '<input type="checkbox" name="' . $fields[$i] . '"' . ((isset($_POST['filter']) && isset($_POST[$fields[$i]])) ? ' checked' : '') . '/>' . $fields[$i] . ' ';
echo '</form><form method="post"><table border="1" cellpadding="7"><tr>';
for($i = 0;$i < count($fields);$i++) echo '<th>' . $fields[$i] . '</th>';
echo '<th>-</th></tr>';
$sql = "SELECT * FROM " . $table;
if(isset($_POST['filter'])){
$filter = mysqli_real_escape_string($conn, $_POST['filter']);
foreach($fields as $key => $value) if(!isset($_POST[$fields[$key]])) unset($fields[$key]);
if(count($fields) > 0){
$first = true;
foreach($fields as $key => $value){
$sql .= " " . (($first) ? "WHERE" : "OR") . " " . $value . " LIKE '%" . $filter . "%'";
$first = false;
}
}
}
// -----------------Bottoms (Above table)-----------------
echo '<input type="submit" name="action" value="Modify" /> <input onclick="return confirm(\'Are you sure you want to delete these rows?\')" type="submit" name="action" value="Delete" /> <input type="submit" name="action" value="Insert" /><br><br></form>';
$_SESSION['store'] = array();
$q = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while($r = mysqli_fetch_assoc($q)){
echo '<tr>';
foreach($r as $key => $value) echo '<td>' . $value. '</td>';
echo '<td><input type="checkbox" name="rows[]" value="' . count($_SESSION['store']) . '" /></td></tr>';
$_SESSION['store'][count($_SESSION['store'])] = $r;
}
// -----------------Bottoms (Below table)-----------------
echo '</table>';
//echo '<br><input type="submit" name="action" value="Modify" /> <input onclick="return confirm(\'Are you sure you want to delete these rows?\')" type="submit" name="action" value="Delete" /> <input type="submit" name="action" value="Insert" /></form>';
?>
<br>
// -----------------Pagination-----------------
<br>
<?php
$start=0;
$limit=50;
if(isset($_GET['page']))
{
$page=$_GET['page'];
$start=($page-1)*$limit;
}
else{
$page=1;
}
//Fetch from database first 10 items which is its limit. For that when page open you can see first 10 items.
$query=mysqli_query($conn,"select * from $table LIMIT $start, $limit");
?>
<?php
//print 10 items
while($result=mysqli_fetch_array($query))
{
//echo "<li>".$result['username']."</li>";
}
?>
<?php
//fetch all the data from database.
$rows=mysqli_num_rows(mysqli_query($conn,"select * from $table"));
//calculate total page number for the given table in the database
$total=ceil($rows/$limit);
if($page>1)
{
//Go to previous page to show previous 10 items. If its in page 1 then it is inactive
echo 'PREVIOUS';
}
if($page!=$total)
{
////Go to previous page to show next 10 items.
echo 'NEXT';
}
?>
<?php
//show all the page link with page number. When click on these numbers go to particular page.
for($i=1;$i<=$total;$i++)
{
if($i==$page) { echo "<li class='current'>".$i."</li>"; }
else { echo '<li>'.$i.'</li>'; }
}
?>
You have error on html URL syntax
echo 'NEXT';
The correct would be
echo 'NEXT';
You have to use ? only for the first URL parameter, & for the following, if any.
I'm trying to do a multiple edit function, the code goes through but the database is not updated. I figure the problem is that at WHERE id = $id no value gets called out because if I replace $id with an actual id e.g. id = 001 the entry 001 gets updated.
This page selects which entries get edited
<?php
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " . "FROM crewlist";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
if (date("Y-m-d") > $row['start_date'] && date("Y-m-d") < $row['end_date']) {
echo "<tr><th>" . "<input type = 'checkbox' name = 'checkbox2[]' value='" . $row['crew_name']. "' >" . "</th>";
echo "<th>" . "" . $row["crew_name"] . "";
echo "<th>" . $row["crew_rank"] . "</th>";
echo "<th>" . $row["start_date"] . "</th>";
echo "<th>" . $row["end_date"] . "</th>";
echo "<th>" . $row["watchkeeping"] . "</th>";
echo "<th>" . $row["active"] . "</th>";
} else {
}
}
?>
This is the edit page
<?php include 'header.php'; ?>
<div id="container4"><?php
require ("dbfunction.php");
$con = getDbConnect();
$checkbox2 = $_POST['checkbox2'];
if (!mysqli_connect_errno($con)) {
$str = implode($checkbox2);
$queryStr = "SELECT * " .
"FROM crewlist WHERE ($str) && crew_id";
}
$result = mysqli_query($con, $queryStr);
?><form action="handlemultiedit.php" method="post"><?php
if ($_POST['submit']) {
$checkbox2 = $_POST['checkbox2'];
foreach ($checkbox2 as $crewname) {
?>
<input type="hidden" name="crew_id" value="<?php $id = isset($_GET['id']) ? $_GET['id'] : ''; ?>" />
<?php echo "<tr><th>" . $crewname . ":</th><br>";
echo " <tr>
<td>Shift 1:</td>
<td><input type=\"time\" name=\"start_hour\" value=\"start_hour\" id=\"start_hour\" step=\"1800\" required> to <input type=\"time\" name=\"end_hour\" value=\"end_hour\" id=\"end_hour\" step=\"1800\" required>
</td>
</tr>
<tr>
<td>Shift 2:</td>
<td><input type=\"time\" name=\"start_hour2\" value=\"start_hour2\" id=\"start_hour2\" step=\"1800\" required> to <input type=\"time\" name=\"end_hour2\" value=\"end_hour2\" id=\"end_hour2\" step=\"1800\" required>
</td>
</tr><br><br>";
?><?php
}?><td><input type="submit" value="Submit" ></td></form><?php
}
?>
print_r($_POST);
require 'dbfunction.php';
$con = getDbConnect();
$crew_id = $_POST["crew_id"];
$start_hour = $_POST["start_hour"];
$end_hour = $_POST["end_hour"];
$start_hour2 = $_POST["start_hour2"];
$end_hour2 = $_POST["end_hour2"];
if (!mysqli_connect_errno($con)) {
$sqlQueryStr = "UPDATE crewlist SET start_hour = '$start_hour',end_hour = '$end_hour', start_hour2 = '$start_hour2',end_hour2 = '$end_hour2' WHERE crew_id = $crew_id";
mysqli_query($con, $sqlQueryStr);
}
//header('Location: crewlisting.php');
mysqli_close($con);
?>
Try placing single quotes (i.e. 's) around your final variable in your statement, as you have done with all of your other variables, i.e. change it to "WHERE crew_id = '$crew_id'";
I can get the checkboxes to update but they aren’t working exactly right. When both boxes are empty I can check either one of them and both boxes get updated to checked. If both boxes are checked I have to uncheck both boxes for them to be updated to unchecked. I can’t get one box to be checked and the other to be unchecked.
Any ideas?
I really appreciate your help.
mySQL Tabel
id | departments_fk | qsps_fk | visible
270 | 1 | 218 | 1
271 | 22 | 218 | 0
272 | 1 | 219 | 0
273 | 22 | 219 | 1
274 | 1 | 220 | 1
275 | 22 | 220 | 1
HTML Code
<form action="edit-qsps.php?qspName=<?php echo $current_qsp["id"]; ?>" method="post">
<div class="qsp-name">QSP Name:
<input type="text" name="qsp_name" class="name-box" value="<?php echo $current_qsp["qsp_name"]; ?>" />
</div>
<div class="rev">QSP Rev:
<input type="text" name="qsp_rev" class="rev-box" value="<?php echo $current_qsp["qsp_rev"]; ?>" />
</div>
<div class="qsp-departments">Department:</div>
<?php
global $db_connection;
global $department_checked;
global $current_qsp;
global $id_department;
echo "<ul>";
$qsp_department_list = find_all_departments();
$department['id'] = $id_department;
while($department = mysqli_fetch_assoc($qsp_department_list)) {
echo htmlentities($department['department_name']);
echo " : ";
$qsp_department_checks = find_all_checks_for_department($current_qsp['id']);
$checks = $department_checked;
global $department_checked;
while($checks = mysqli_fetch_assoc($qsp_department_checks)) {
if ($current_qsp['id'] == $checks['qsps_fk'] && $checks['departments_fk'] == $department['id']) {
echo "<div class='department-checked'>";
echo "<input type='hidden' name='hidden-checkBoxes[]' value='";
echo htmlentities($checks['departments_fk']);
echo "' />";
echo "<input type='checkbox' name='department-checkBoxes[]' value='";
echo htmlentities($checks['departments_fk']);
echo "' ";
if($checks['checked'] == '1'){
echo "checked='checked'";
}
echo " />";
echo "</label>";
echo "</div>";
}
}
mysqli_free_result($qsp_department_checks);
}
mysqli_free_result($qsp_department_list);
echo "</ul>";
?>
<div class="create-btn">
<input type="submit" name="submit" value="UPDATE QSP" />
</div>
</form>
PHP Process Code
<?php
if (isset($_POST['submit'])) {
global $db_connection;
global $id_department;
$id_qsp = $current_qsp["id"];
$qsp_name = mysql_prep($_POST["qsp_name"]);
$qsp_rev = mysql_prep($_POST["qsp_rev"]);
$query1 = "UPDATE qsps SET ";
$query1 .= "qsp_name = '{$qsp_name}', ";
$query1 .= "qsp_rev = '{$qsp_rev}' ";
$query1 .= "WHERE id = {$id_qsp} ";
$query1 .= "LIMIT 1";
$result1 = mysqli_query($db_connection, $query1);
foreach($_POST['hidden-checkBoxes'] as $checked) {
if (isset($_POST['department-checkBoxes'])) {
$val = 1;
} else {
$val = 0;
}
$query2 = "UPDATE junction_departments_qsps SET ";
$query2 .= "checked = {$val} ";
$query2 .= "WHERE departments_fk = {$checked} ";
$query2 .= "AND qsps_fk = {$id_qsp} ";
$result2 = mysqli_query($db_connection, $query2);
}
redirect_to("edit-qsps.php");
} else {
// Failure
$message = "Employee Update Failed.";
}
?>
Updated Process Code
if (isset($_POST['submit'])) {
global $db_connection;
global $id_department;
$id_qsp = $current_qsp["id"];
$qsp_name = mysql_prep($_POST["qsp_name"]);
$qsp_rev = mysql_prep($_POST["qsp_rev"]);
$query1 = "UPDATE qsps SET ";
$query1 .= "qsp_name = '{$qsp_name}', ";
$query1 .= "qsp_rev = '{$qsp_rev}' ";
$query1 .= "WHERE id = {$id_qsp} ";
$query1 .= "LIMIT 1";
$result1 = mysqli_query($db_connection, $query1);
if(!empty($_POST['department-checkBoxes'])) {
foreach($_POST['department-checkBoxes'] as $check) {
echo $check;
//only checked checkboxes come to $POST
$query2 = "UPDATE junction_departments_qsps SET ";
$query2 .= "checked = 1 ";
$query2 .= "WHERE departments_fk = {$check} ";
$query2 .= "AND qsps_fk = {$id_qsp} ";
$result2 = mysqli_query($db_connection, $query2);
}
}
redirect_to("edit-qsps.php");
} else {
// Failure
$message = "Employee Update Failed.";
}
You need to loop through the 'department-checkBoxes'. Now you are not getting their values, just checking if entire POST variable is set.
if(!empty($_POST['department-checkBoxes'])) {
foreach($_POST['department-checkBoxes'] as $check) {
echo $check;
//only checked checkboxes come to $POST
$query2 = "UPDATE junction_departments_qsps SET ";
$query2 .= "checked = 1 ";
$query2 .= "WHERE departments_fk = {$checked} ";
$query2 .= "AND qsps_fk = {$id_qsp} ";
$result2 = mysqli_query($db_connection, $query2);
}
Form
<form action="edit-qsps.php?qspName=<?php echo $current_qsp["id"]; ?>" method="post">
<div class="qsp-name">QSP Name:
<input type="text" name="qsp_name" class="name-box" value="<?php echo $current_qsp["qsp_name"]; ?>" />
</div>
<div class="rev">QSP Rev:
<input type="text" name="qsp_rev" class="rev-box" value="<?php echo $current_qsp["qsp_rev"]; ?>" />
</div>
<div class="qsp-departments">Department:</div>
<?php
global $db_connection;
global $current_qsp;
echo "<ul>";
$qsp_department_list = find_all_departments();
while($department = mysqli_fetch_assoc($qsp_department_list)) {
echo htmlentities($department['department_name']);
echo " : ";
$qsp_department_checks = find_all_checks_for_department($current_qsp['id']);
while($checks = mysqli_fetch_assoc($qsp_department_checks)) {
$id_checked = htmlentities($checks['id']);
if ($current_qsp['id'] == $checks['qsps_fk'] && $checks['departments_fk'] == $department['id']) {
echo "<div class='department-checked'>";
echo "<input type='checkbox' name='hidden-checkBoxes[]' value='";
echo htmlentities($checks['id']);
echo "' style='display:none' checked='checked' />";
echo "<input type='checkbox' name='department-checkBoxes[]' value='";
echo htmlentities($checks['id']);
echo "' ";
if($checks['checked'] == '1'){
echo "checked='checked'";
}
echo " />";
echo "</label>";
echo "</div>";
}
}
mysqli_free_result($qsp_department_checks);
}
mysqli_free_result($qsp_department_list);
echo "</ul>";
?>
<div class="employee-category">Employee Category:</div>
<?php echo edit_employee_category_checkBoxes(); ?>
<div class="create-btn">
<input type="submit" name="submit" value="UPDATE QSP" />
</div>
</form>
PHP Processing Code
<?php
if (isset($_POST['submit'])) {
global $db_connection;
$id_qsp = $current_qsp["id"];
$qsp_name = mysql_prep($_POST["qsp_name"]);
$qsp_rev = mysql_prep($_POST["qsp_rev"]);
$query1 = "UPDATE qsps SET ";
$query1 .= "qsp_name = '{$qsp_name}', ";
$query1 .= "qsp_rev = '{$qsp_rev}' ";
$query1 .= "WHERE id = {$id_qsp} ";
$query1 .= "LIMIT 1";
$result1 = mysqli_query($db_connection, $query1);
$departments_id = $_POST["hidden-checkBoxes"];
$hidden_depart = $_POST["department-checkBoxes"];
if(isset($_POST['hidden-checkBoxes'])) {
foreach ($departments_id as $depart_id){
$visible_check = in_array($depart_id, $hidden_depart) ? 1 : 0;
$query2 = "UPDATE junction_departments_qsps SET ";
$query2 .= "checked = {$visible_check} ";
$query2 .= "WHERE id = {$depart_id} ";
$result2 = mysqli_query($db_connection, $query2);
}
}
redirect_to("edit-qsps.php");
} else {
// Failure
$message = "Employee Update Failed.";
}
?>
I am trying to create a form page that will allow the end-user the ability to update multiple entries in a table. The user is tagged by an ID_NUM and the entries by RECORD. I want to display each row in the form, with each row stacked on the page in separate instances. As below:
School Name:
School Type:
Degree:
Major:
Graduate:
School Name:
School Type:
Degree:
Major:
Graduate:
I want the submit to trigger an update to any changes in any row. Here is the code I have for the basic form. What do I need to do to integrate the foreach loop, if that is the best way to solve the problem?
<?php
// Start the session
require_once('startsession.php');
// Insert Page Header
$page_title = 'Edit Profile';
require_once('header.php');
// Make sure the user is logged in before going any further.
if (!isset($_SESSION['email'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
// Insert navmenu
require_once('navmenu.php');
require_once('vary.php');
require_once('appvars.php');
require_once('connectvars.php');
// Connect to the database using vary.php
if (isset($_POST['submit']))
{
// Grab the profile data from the POST
$record2 = $_POST['record'];
$school2 = $_POST['school'];
$type2 = $_POST['school_code'];
$degree2 = $_POST['degree_code'];
$desc2 = $_POST['desc'];
$grad2 = $_POST['grad'];
$another2 = $_POST['another'];
// Update the profile data in the database
if (!empty($school2)) {
$query3 = "UPDATE EDUCATION SET SCHOOL = '$school2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 . "'";
mysqli_query($dbc, $query3);
}
if (!empty($type2)) {
$query4 = "UPDATE EDUCATION SET TYPE = '$type2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 . "'";
mysqli_query($dbc, $query4);
}
if (!empty($degree2)) {
$query5 = "UPDATE EDUCATION SET DEGREE = '$degree2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 . "'";
mysqli_query($dbc, $query5);
}
if (!empty($desc2)) {
$query6 = "UPDATE EDUCATION SET MAJOR = '$desc2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 . "'";
mysqli_query($dbc, $query6);
}
if (!empty($grad2)) {
$query7 = "UPDATE EDUCATION SET GRAD = '$grad2' WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 ."'";
mysqli_query($dbc, $query7);
}
// Confirm success with the user
if ($another2=="Y")
{
// Clear the variables and reload the page for new submit
$record2 = "";
$school2 = "";
$type2 = "";
$degree2 = "";
$major2 = "";
$grad2 = "";
$another2 = "";
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.avant.jobs/portal/addeducation.php">';
}
else
{
echo '<p>The education section of your profile has been successfully updated. Would you like to continue??</p>';
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.avant.jobs/portal/workcheck.php">';
}
mysqli_close($dbc);
exit();
}
else
{
echo '<p class="error">You must enter all of the profile data.</p>';
}
// End of check for form submission
// Grab the profile data from the database
$query8 = "SELECT * FROM EDUCATION WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "'";
$data = mysqli_query($dbc, $query8);
$row = mysqli_fetch_array($data);
if ($row != NULL)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$desc = $row['MAJOR'];
$grad = $row['GRAD'];
}
else
{
echo '<p class="error">There was a problem accessing your profile.</p>';
}
;
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Education History </legend>
<?php
echo '<input type="hidden" id="record" name="record" value="' . $record . '">';
// Insert Listbox here
$queryschool = "SELECT * FROM SCHOOL";
$list = mysqli_query($dbc, $queryschool);
if($list)
{
echo 'School Type? ';
echo '<select name="school_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['TYPE']}" ;
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="school">School Name:</label>';
echo '<input type="text" id="school" name="school" size="40" maxlength="40" value="' . ((!empty($school)) ? $school : "") . '" /><br />';
// Insert Listbox here
$querydegree = "SELECT * FROM DEGREE";
$list = mysqli_query($dbc, $querydegree);
if($list)
{
echo 'Degree Type? ';
echo '<select name="degree_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['DEGREE']}";
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="desc">Field of study:</label>';
echo '<input type="text" id="desc" name="desc" size="40" maxlength="40" value="' . ( (!empty($desc)) ? $desc : "") . '" /><br />';
echo '<label for="grad">Did you graduate?:</label>';
echo '<input type="radio" id="grad" name="grad" value="Y" ' . ($grad == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="grad" name="grad" value="N" ' . ($grad == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
</fieldset>
<?php
echo '<label for="another">Do you need to enter more educational experience?:</label>';
echo '<input type="radio" id="another" name="another" value="Y" ' . ($another == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="another" name="another" value="N" ' . ($another == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
<input type="submit" value="Save Profile" name="submit" />
</form>
<?php
// Insert Page Footer
require_once('footer.php');
?>
As I am new to this and trying to teach my self, any help is appreciated! Thank you.
Instead of having multiple UPDATE queries, you can integrate them to 1 query,
$comma = FALSE;
$query = "UPDATE EDUCATION SET ";
// Update the profile data in the database
if (!empty($school2)) {
$query .= "SCHOOL = '$school2'";
$comma = TRUE;
}
if (!empty($type2)) {
if($comma === TRUE)
$query .= ", ";
$query .= "TYPE = '$type2' ";
$comma = TRUE;
}
if (!empty($degree2)) {
if($comma === TRUE)
$query .= ", ";
$query5 = "DEGREE = '$degree2'";
$comma = TRUE;
}
if (!empty($desc2)) {
if($comma === TRUE)
$query .= ", ";
$query .= "MAJOR = '$desc2'";
$comma = TRUE;
}
if (!empty($grad2)) {
if($comma === TRUE)
$query .= ", ";
$query .= "GRAD = '$grad2'";
}
$query .= "WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' AND RECORD = '" . $record2 ."'";
if (!empty($school2) || !empty($type2) || !empty($degree2) || !empty($desc2) || !empty($grad2)) {
mysqli_query($dbc, $query);