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']) . "' ";
Related
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;
}
}
I'm creating a page in which room reservations are displayed in a table, with the possibilty to update or delete them.
The reservations come from a MySQL-database, table reservations.
It works, but I would like that the information from the database is updated on the page immediately after pressing the buttons.
For instance, if now I set the username from 'person' to 'another person', the field gets updated correctly in the database, but I need to refresch the page to see the update in my table.
How can I do this?
<table border="1">
<tr><td>Datum</td><td>Start</td><td>Stop</td><td>Gebruikersnaam</td></tr>
<?php
$now = date("Y-m-d");
$query = "SELECT * FROM reservations WHERE (roomid = " . 45 . " AND end > NOW() ) ORDER BY start";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$reservationid=$row["reservationid"];
$username=$row["username"];
$aantal=$row["numberingroup"];
$reservationid=$row["reservationid"];
$start=$row["start"];
$end=$row["end"];
$roomid=$row["roomid"];
?>
<form action="" method="post">
<tr><td><input name="StartDate" value="<? echo $StartDate; ?>" /></td><td><input name="StartTime" value="<? echo $StartTime; ?>" /></td><td><input name="StopTime" value="<? echo $StopTime; ?>" /></td><td><input name="username" value="<? echo $username;?>" /></td><td><input type="submit" value="update" name="<?php echo 'update_' . $reservationid; ?>" /></td><td><input type="submit" value="delete" name="<?php echo 'delete_' . $reservationid; ?>" /></td><td><? echo $reservationid; ?></td></tr></form>
<?php
//DELETE
if(isset($_POST['delete_' . $reservationid]))
{
$deletequery = "DELETE FROM reservations WHERE reservationid=" . $reservationid;
if(mysql_query($deletequery)){
echo "<p><b>Boeking verwijderd</b></p>";}
else {
echo "<p><b>Boeking niet verwijderd</b></p>";}
}
//UPDATE
if(isset($_POST['update_' . $reservationid]))
{
$NewStartDate = explode("-",$_POST[StartDate]);
$newstartdate = $NewStartDate[2] . "-" . $NewStartDate[1] . "-" . $NewStartDate[0];
$newstarttime = $_POST[StartTime] . ":00";
$newenddate = $newstartdate;
$NewEndTime = explode(":",$_POST[StopTime]);
$newendtime = mktime($NewEndTime[0],($NewEndTime[1]-1),59);
$newendtime = date("H:i:s",$newendtime);
$UpdateStart = $newstartdate . " " . $newstarttime;
$UpdateEnd = $newenddate . " " . $newendtime;
$UpdateUsername = $_POST[username];
$updatequery = "UPDATE reservations SET start='$UpdateStart', end='$UpdateEnd', username='$UpdateUsername' WHERE reservationid=" . $reservationid;
if(mysql_query($updatequery)){
echo "<p><b>Updated " . $reservationid . " " . $UpdateStart . " " . $UpdateEnd . " " . $UpdateUsername . "</b></p>";}
else {
echo "<p><b>FAILURE IS NOT AN OPTION. AGAIN!</b></p>";}
}
?>
<?php
}
mysql_close();
?>
The working code is:
<?php
//DELETE
if(isset($_POST['delete_' . $_POST[updateid]]))
{
$deletequery = "DELETE FROM reservations WHERE reservationid=" . $_POST[updateid];
if(mysql_query($deletequery)){
echo "<p><b>Boeking verwijderd</b></p>";
}
else {
echo "<p><b>FAILURE IS NOT AN OPTION. AGAIN!</b></p>";
}
}
//UPDATE
if(isset($_POST['update_' . $_POST[updateid]]))
{
$UpdateID = $_POST[updateid];
$NewStartDate = explode("-",$_POST[StartDate]);
$newstartdate = $NewStartDate[2] . "-" . $NewStartDate[1] . "-" . $NewStartDate[0];
$newstarttime = $_POST[StartTime] . ":00";
$newenddate = $newstartdate;
$NewEndTime = explode(":",$_POST[StopTime]);
$newendtime = mktime($NewEndTime[0],($NewEndTime[1]-1),59);
$newendtime = date("H:i:s",$newendtime);
$UpdateStart = $newstartdate . " " . $newstarttime;
$UpdateEnd = $newenddate . " " . $newendtime;
$UpdateUsername = $_POST[username];
$updatequery = "UPDATE reservations SET start='$UpdateStart', end='$UpdateEnd', username='$UpdateUsername' WHERE reservationid='$UpdateID'";
if(mysql_query($updatequery)){
echo "<p><b>Updated " . $reservationid . " " . $UpdateStart . " " . $UpdateEnd . " " . $UpdateUsername . "</b></p>";
}
else {
echo "<p><b>FAILURE IS NOT AN OPTION. AGAIN!</b></p>";
}
// echo "<p><b>Updated " . $reservationid . " " . $UpdateStart . " " . $UpdateEnd . " " . $UpdateUsername . "</b></p>";
}
?>
<?php
$query = "SELECT * FROM reservations WHERE (roomid = " . 45 . " AND end > NOW() ) ORDER BY start";
$result = mysql_query($query) or die(mysql_error());
?>
<table border="1">
<tr><td>Datum</td><td>Start</td><td>Stop</td><td>Gebruikersnaam</td></tr>
<?php
while($row = mysql_fetch_array($result)){
$reservationid=$row["reservationid"];
$username=$row["username"];
$aantal=$row["numberingroup"];
$reservationid=$row["reservationid"];
$start=$row["start"];
$end=$row["end"];
$roomid=$row["roomid"];
$startdate = explode(" ",$start);
$startdate[0] = explode("-",$startdate[0]);
$startdate[1] = explode(":",$startdate[1]);
$StartFormat = mktime($startdate[1][0],$startdate[1][1],$startdate[1][2],$startdate[0][1],$startdate[0][2],$startdate[0][0]);
$StartDate = date("d-m-Y",$StartFormat);
$StartTime = date("H:i",$StartFormat);
$stopdate = explode(" ",$end);
$stopdate[0] = explode("-",$stopdate[0]);
$stopdate[1] = explode(":",$stopdate[1]);
$StopFormat = mktime($stopdate[1][0],$stopdate[1][1],($stopdate[1][2]+1),$stopdate[0][1],$stopdate[0][2],$stopdate[0][0]);
$StopDate = date("d-m-Y",$StopFormat);
$StopTime = date("H:i",$StopFormat);
?>
<form action="" method="post">
<tr><td><input type="hidden" name="updateid" value="<?php echo $reservationid; ?>" /> <input name="StartDate" value="<? echo $StartDate; ?>" /></td><td><input name="StartTime" value="<? echo $StartTime; ?>" /></td><td><input name="StopTime" value="<? echo $StopTime; ?>" /></td><td><input name="username" value="<? echo $username;?>" /></td><td><input type="submit" value="update" name="<?php echo 'update_' . $reservationid; ?>" /></td><td> <input type="submit" value="delete" name="<?php echo 'delete_' . $reservationid; ?>" /></td> </tr>
</form>
<?php
}
mysql_close();
?>
</table>
Move the logic that does the updating and deleting above the logic that does the rendering:
<?php
// DELETE (your delete stuff)
// UPDATE (your update stuff)
// RETRIEVE (your SELECT query)
?>
<table> <!-- your table markup -->
<?php
// RENDER (your while loop and such)
You'll also need to adjust your logic a bit. You're using the $reservationid from the SELECT to do the deleting and updating. This doesn't work, because the execution context for the PHP is refreshed with each page load. What you need is to store the reservation id in each form (maybe in a hidden field), and then to retrieve that from $_POST.
Incidentally, your code is very vulnerable to SQL injection. Also, you should look at using mysqli or PDO; mysql_connect is deprecated in the current version of PHP.
You could use jQuery for this. You have to make an $.ajax (http://api.jquery.com/jquery.ajax/) call. From the callback you can fill/set the fields you want to. You'll need $('#idofelement').html()(http://api.jquery.com/html/) for this. If you have got any questions don't be affraid to ask ;) Good luck!
I have created a website with a comments page for users to delete the comments that they upload. However the delete comment button appears however it doesn't seem to work. Can anyone shed some light on this for me please?
<?php
require_once("checklog.php");
include_once("nihome_start_logged.php");
require_once("nifunctions.php");?>
<div id="navigation">
<ul class="container">
<li><a href='nihome.php'>Home</a></li>
<li> Search for your service</li>
<li><a href='nisalons.php' class='button'>Salons and Reviews</a></li>
<li><a href='nichangepassword.php' class='button'>Change Password</a></li>
<li><a href='nilogout.php' class='button'>Logout</a></li>
</ul>
</div>
<?php
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error($db_server));
$db_status = "not connected";
}else{
//Capture form data, if anything was submitted
if (isset($_GET['salonid']) and ($_GET['salonid'] != '')){
$salonid = clean_string($db_server, $_GET['salonid']);
//code to delete comments
if($db_server){
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, "DELETE FROM comments WHERE username = '$username' and salonid = '$salonid' ");
$message= "<p> Comment deleted </p>";
//If connected, get Salons from database and write out
mysqli_select_db($db_server, $db_database);
$query = "SELECT ID, salon_name, address, postcode, telephone, email, website FROM salon WHERE ID=$salonid";
$result = mysqli_query($db_server, $query);
if (!$result) die("Query failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_result .= "<h2>" . $row[ 'salon_name'] . "</h2>";
$str_result .= "<p>" . $row['address'] . "</p>";
$str_result .= "<p>" . $row['postcode'] . "</p>";
$str_result .= "<p>" . $row['telephone'] . "</p>";
$str_result .= "<p>" . $row['email'] . "</p>";
$str_result .= "<p>" . $row['website'] . "</p>";
}
}
mysqli_free_result($result);
}else{
$str_result = "<h2>No salon selected</h2>";
}
}
echo $str_result;
?>
<?php
if(trim($_POST['submit']) == "Submit comment"){
//Get any submitted comments and insert
$comment = clean_string($db_server, $_POST['comment']);
if ($comment != '') {
$name=$_FILES['photo']['name'];
if ($name == "") $error .= "<p class='error'>You must write a review and upload an image!</p>";
$originalname=$_FILES['photo']['name'];
$type=$_FILES['photo']['type'];
if ($type=="image/jpeg") $type=".jpeg"; //if true change
else if ($type=="image/jpg") $type=".jpg";// if not true check this one
else if ($type=="image/png") $type=".png";
$name=uniqid() . $type;
$path="images/" . $name;
$tempname=$_FILES['photo']['tmp_name'];
$size=$_FILES['photo']['size'];
//Error checking
if ($size >1000000) $error .= "<p class='error'>Your image file is to big, it have to be less than 200 mb</p>";
if ($error=="") {
if (move_uploaded_file($tempname, $path)){
$uploadquery="INSERT INTO comments (comment, imagename, salonID, userID) VALUES ('$comment', '$path', $salonid, ". $_SESSION['userID'].")";
mysqli_query($db_server,$uploadquery) or die ("Insert failed " . mysqli_error($db_server) . " " . $uploadquery);
$message= "<h2>Thanks for your comment!</h2><p>Your upload was succesful</p>";
}
}
}
}
//Print out existing comment
$query = "SELECT * FROM comments JOIN users ON comments.userID = users.ID WHERE salonID=$salonid";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)){
if ($_SESSION['username'] == $row['username']){
$deletecomment = "<input class='delete comment' type='submit' id='submit' name='submit' value='Delete comment'/>";
}else{
$deletecomment = " ";
}
$str_comments .= "<p><span class='comments'>" . $row['Username'] ." : " . $row['comment'] . "</span></p>";
$str_comments .="<p><img src='" . $row['imagename'] ."' /></p>";
$str_comments .= $deletecomment ;
}
mysqli_free_result($result);
?>
<div id="form">
<table><form id='review' action='salonpage.php?salonid=<?php echo $salonid; ?>' method='post' enctype='multipart/form-data'>
<th><h2> Do you want to review the service you recieved?</h2></th>
<tr><td><textarea name="comment" rows="6" cols="40">Write something here!</textarea></td></tr>
<tr><td><input type='file' name='photo' accept='image/jpg, image/jpeg, image/png'/></td></tr>
<br/>
<tr><td><input type='submit' id='submit' name='submit' value='Submit comment' /></td></tr>
</form></table>
<?php echo $error;
echo $message;?></div>
<h2> Reviews and comments </h2>
<?php echo $str_comments; ?>
<?php mysqli_close($db_server); ?>
<div id='footer'>
Privacy Statement
Accessibility Statement
</div>
<?php include_once("nihome_end.php"); ?>
From you code, you used form-submit-button to delete the record -- and it's stored in $str_comments.
You need
<form .....>
<?php echo $str_comments ?>
</form>
Because the submit-button needs form to live in.
#1 I suggest you start using classes.
#2 if you're using mysqli(i stands for improved) why are you doing things the "old way"?
#3 a classfull example
$drop = new CLASS_NAME_GOES_HERE;
$drop->drop_comment($id,$un);
class CLASS_NAME_GOES_HERE {
private $con; // only access from this class and its children and dont need $ anymore
function __construct() { // constructor function
$this->con = new mysqli(DB,DB_USER,DB_PASS,DB_NAME) or
die('Cannot connect.');
}
function drop_comment($id,$un) {
$sql= "DELETE FROM upload WHERE id = ? AND username = ?";
if($try = $this->con->prepare($sql)) {
$try->bind_param('ss', $id, $un);
if($try->execute()) return true;
}
}//END FUNCTION
}//end class
I have a database called test. In it there is a table called people. People has 4 fields: fname, lname, age, city. I have a page with a form where people can enter in data.
<?php
include('header.php');
?>
<body>
<form action="getinformation.php" method="post" id="getinformation">
<div id="header">
<h1><strong>Search For Data</h1></strong>
</div>
<div id="main">
<table border="0" width="75%">
<tr>
<td align="right" width="10%">First Name: </td>
<td><input type="text" name="fname" id="fname" size="20" /></td>
</tr>
<tr>
<td align="right" width="10%">Last Name: </td>
<td><input type="text" name="lname" id="lname" size="20" /></td>
</tr>
<tr>
<td align="right" width="10%">Age: </td>
<td><input type="text" name="age" id="age" size="3" /></td>
</tr>
<tr>
<td align="right" width="10%">City: </td>
<td><input type="text" name="city" id="city" size="20" /></td>
</tr>
</table>
<input type="submit" />
</div>
</body>
<?php
include('footer.php');
?>
When the submit button is clicked it will send the data to another page named getinformation.php.
<?php
require_once('model.php');
$query = "SELECT * FROM people WHERE";
if (isset ($POST_fname) {
$fname = $_POST['fname'];
$query = $query . " fname = " . $fname . " AND" }
if (isset ($POST_lname) {
$lname = $_POST['lname'];
$query = $query . " lname = " . $lname . " AND" }
if (isset ($POST_age) {
$age = $_POST['age'];
$query = $query . " age = " . $age . " AND" }
if (isset ($POST_city) {
$city = $_POST['city'];
$query = $query . " city = " . $city . " AND" }
$query = rtrim($query, " AND");
?>
<div id=/"header/">
<h1><strong>This is the information you requested</h1></strong>
</div>
<div id=/"main/">
<?php
$statement = $db->prepare($query);
$statement->execute();
$products = $statement->fethAll();
$statement->closeCursor();
foreach ($products as $product) {
echo $product['fname'] . " " . $product['lname'] . " | " . $product['age'] . " | " . $product['city'] . '<br />';
?>
</div>
<?php
include('footer.php');
?>
I get an error
Parse error: syntax error, unexpected '{' in C:\Program Files\wamp\www\testwebpage\Model\getinformation.php on line 6
I have had this problem before with my isset function but aside from that working I'm wondering if the rest of the code looks fine (assuming isset worked perfectly)
You have a syntax error - missing closing parenthesis:
if (isset ($POST_fname) {
Should be
if (isset ( ..... ) ) {
You forgot to close the ) everywhere after isset and didn't put semicolons after "AND". Here is the fixed file:
<?php
require_once('model.php');
$query = "SELECT * FROM people WHERE";
if (isset ($POST_fname)) {
$fname = $_POST['fname'];
$query = $query . " fname = '" . $fname . "' AND";
}
if (isset ($POST_lname)) {
$lname = $_POST['lname'];
$query = $query . " lname = '" . $lname . "' AND";
}
if (isset ($POST_age)) {
$age = $_POST['age'];
$query = $query . " age = '" . $age . "' AND";
}
if (isset ($POST_city)) {
$city = $_POST['city'];
$query = $query . " city = '" . $city . "' AND";
}
$query = rtrim($query, " AND");
?>
<div id=/"header/">
<h1><strong>This is the information you requested</h1></strong>
</div>
<div id=/"main/">
<?php
$statement = $db->prepare($query);
$statement->execute();
$products = $statement->fethAll();
$statement->closeCursor();
foreach ($products as $product) {
echo $product['fname'] . " " . $product['lname'] . " | " . $product['age'] . " | " . $product['city'] . '<br />';
}
?>
</div>
<?php
include('footer.php');
?>
Forgot the ( at end of the if. look at the line 6 as said in the error output.
(isset ($POST_fname)
be carfull
isset() is a expression that have 2 parenteses"(" ")" you opened, but din't close.
on every 'if' do this
if(isset(anything))
any other problem, come here !
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);