Add delete row in jquery wordpress issue - php

Hi there i make meta box with jQuery in wordpress. I am trying to add more than one meta boxes with jQuery.
It works all perfectly, it add meta fields and save data, remove meta fields and remove data.
but the issue is that the remove button is also shown on first (default) meta filed, when i click on remove, it remove first (default) meta field, i dont want remove button on First row.
And second issue is, when i remove the field and update the post the data in this meta field is delete but the meta field does not rove from there
My Code:
add_action('add_meta_boxes', 'add_multiple_urls');
function add_multiple_urls($post) {
add_meta_box( 'multiple-urls-id', 'Download Links', 'repeatable_download_link', 'post', 'normal', 'default');
}
function repeatable_download_link($post) {
$repeatable_fields = get_post_meta($post->ID, 'repeatable_fields', true);
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#add-row').on('click', function() {
var row = $('.empty-row.screen-reader-text').clone(true);
row.removeClass('empty-row screen-reader-text');
row.insertBefore('#repeatable-fieldset-one tbody>tr:last');
return false;
});
$('.remove-row').on('click', function() {
$(this).parents('tr').remove();
return false;
});
});
</script>
<table id="repeatable-fieldset-one" width="100%">
<thead>
<tr>
<th width="92%" align="left">URL</th>
<th width="8%"></th>
</tr>
</thead>
<tbody>
<?php
if($repeatable_fields ) :
foreach($repeatable_fields as $field ) {
?>
<tr>
<td>
<input type="text" class="widefat" name="url[]" value="<?php if ($field['url'] != '') echo esc_attr( $field['url'] ); else echo 'http://'; ?>" />
</td>
<td><a class="button remove-row" href="#">Remove</a></td>
</tr>
<?php
}
else :
// show a blank one
?>
<tr>
<td><input type="text" class="widefat" name="url[]" value="http://" /></td>
</tr>
<?php endif; ?>
<!-- empty hidden one for jQuery -->
<tr class="empty-row screen-reader-text">
<td><input type="text" class="widefat" name="url[]" value="http://" /></td>
<td><a class="button remove-row" href="#">Remove</a></td>
</tr>
</tbody>
</table>
<p><a id="add-row" class="button" href="#">Add another</a></p>
<?php
}
add_action('save_post', 'save_multiple_download_link');
function save_multiple_download_link() {
global $post;
$old = get_post_meta($post->ID, 'repeatable_fields', true);
$new = array();
$urls = $_POST['url'];
$count = count( $urls );
for($i = 0; $i < $count; $i++ ) {
if($urls[$i] == 'http://' ){
$new[$i]['url'] = '';
}
else{
$new[$i]['url'] = stripslashes( $urls[$i] ); // and however you want to sanitize
}
}
if(!empty($new) && $new != $old)
update_post_meta($post->ID, 'repeatable_fields', $new);
elseif(empty($new) && $old)
delete_post_meta($post->ID, 'repeatable_fields', $old);
}
?>

Okay. The first issue should be fixed already by just removing the remove button.
<?php
}
else :
// show a blank one
?>
<tr>
<td><input type="text" class="widefat" name="url[]" value="http://" /></td>
</tr>
<?php endif; ?>
For second issue, the meta field is removed but you're adding empty/default meta field back into the post_meta. You don't want to add empty field into $new.
Use this instead.
for($i = 0; $i < $count; $i++ ) {
if($urls[$i] != 'http://' ){
$new[$i]['url'] = stripslashes( $urls[$i] ); // and however you want to sanitize
}
}
If you still want to have an empty/default field at the end, you can add an blank field after the foreach loop and you might want to add the remove button back on this one.
<?php
if($repeatable_fields ) :
foreach($repeatable_fields as $field ) {
?>
<tr>
<td>
<input type="text" class="widefat" name="url[]" value="<?php if ($field['url'] != '') echo esc_attr( $field['url'] ); else echo 'http://'; ?>" />
</td>
<td><a class="button remove-row" href="#">Remove</a></td>
</tr>
<?php
}
?>
<tr>
<td><input type="text" class="widefat" name="url[]" value="http://" /></td>
<td><a class="button remove-row" href="#">Remove</a></td>
</tr>
<?php
else :
// show a blank one
?>

Related

Save Edit button then disabled readonly metabox

Hello I am just starting out with php and I have managed to get a repeatable metabox and managed to add a 'Save' button which saves the input meta data to the database which works, how can I change the fields to disabled readonly when the 'Save' button is pressed, and then the 'Save' button becomes 'Edit' which when pressed the fields are editable and the button becomes 'Save'? any help will be appreciated
metabox
add_action( 'wp_ajax_handle_Inventory_in_db', 'handle_Inventory_in_db' );
function mdr_add_meta_boxes() {
add_meta_box( 'mdrinventory-group', 'Inventory', 'Repeatable_meta_box_display', 'rvs_video', 'normal', 'high');
}
function Repeatable_meta_box_display() {
global $post;
global $wpdb;
$sql="SELECT * FROM $wpdb->postmeta WHERE post_id = '".$post->ID."' AND meta_key='inventory_group'";
$allData = $wpdb->get_results($wpdb->prepare($sql));
wp_nonce_field( 'mdr_repeatable_meta_box_nonce', 'mdr_repeatable_meta_box_nonce' );
?>
<script type="text/javascript">
jQuery(document).ready(function( $ ){
$( '#add-row' ).on('click', function() {
var row='';
var data = {
'post_id':'<?=$post->ID?>',
'action': 'handle_Inventory_in_db',
'command': 'add_new_blank_row_in_db',
}
$.post(ajaxurl, data, function(resp){
row=resp;
$('#dynamic-rows').append(row);
});
return false;
});
$('body' ).on('click','.update-row',function() {
var meta_id=$(this).attr('data-uid');
var data = {
'meta_id': meta_id,
'serial': $("#serial_"+meta_id).val(),
'barcode':$("#barcode_"+meta_id).val(),
'action': 'handle_Inventory_in_db',
'command': 'update_row',
}
$.post(ajaxurl, data, function(resp){
console.log(resp);
});
$(this).val('Update');
return false;
});
$('body' ).on('click','.remove-row',function() {
var meta_id=$(this).attr('data-uid');
var data = {
'meta_id': meta_id,
'action': 'handle_Inventory_in_db',
'command': 'remove_row',
}
$.post(ajaxurl, data, function(resp){
console.log(resp);
});
$(this).parents('tr').remove();
return false;
});
});
</script>
<table id="repeatable-fieldset-one" width="100%" class="wp-list-table widefat fixed striped table-view-list">
<thead>
<tr>
<th>Serial No.</th>
<th>Barcode No.</th>
</tr>
</thead>
<tbody id="dynamic-rows">
<?php
if ( $allData ) :
foreach ($allData as $singleRow) {
$save_btn_label= $singleRow->meta_value==''?'Save':'Update';
$meta_value = unserialize( $singleRow->meta_value);
?>
<tr>
<td width="15%"><input type="text" id="serial_<?=$singleRow->meta_id;?>" placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();" value="<?php if($meta_value['serial'] != '') echo esc_attr($meta_value['serial']); ?>" /></td>
<td width="70%"><input type="text" id="barcode_<?=$singleRow->meta_id;?>" placeholder="Barcode" value="<?php if($meta_value['barcode'] != '') echo esc_attr($meta_value['barcode']); ?>" /></td>
<td width="15%"><input data-uid="<?=$singleRow->meta_id;?>" type="button" class="update-row mdr_bk_btn1" value="<?=$save_btn_label;?>"></td>
<td width="15%"><a data-uid="<?=$singleRow->meta_id;?>" class="button remove-row" href="#1">Remove</a></td>
</tr>
<?php
}
else :
// insert a blank row
$meta_id=add_post_meta( $post->ID, 'inventory_group', '', false ); //Add new meta to table and store id in $uid
?>
<tr>
<td width="15%"><input type="text" id="serial_<?=$meta_id;?>" placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();"/></td>
<td width="70%"><input type="text" id="barcode_<?=$meta_id;?>" placeholder="Barcode"/></td>
<td width="15%"><input data-uid="<?=$meta_id;?>" type="button" class="update-row mdr_bk_btn1" value="Save"></td>
<td width="15%"><a data-uid="<?=$meta_id;?>" class="button remove-row" href="#1">Remove</a></td>
</tr>
<?php endif; ?>
</tbody>
</table>
<p><a id="add-row" class="button" href="#">Add Inventory</a></p>
<?php
}
function handle_Inventory_in_db()
{
global $wpdb;
$table_name = $wpdb->prefix . 'postmeta';
$conditions = array( 'meta_id' => $_POST['meta_id'] );
switch ($_POST['command']) {
case 'add_new_blank_row_in_db':
$meta_id=add_post_meta( $_POST['post_id'], 'inventory_group', null, false );
$row='<tr>
<td width="15%"><input type="text" id="serial_'.$meta_id.'" placeholder="Serial" onkeyup="this.value = this.value.toUpperCase();"/></td>
<td width="70%"><input type="text" id="barcode_'.$meta_id.'" placeholder="Barcode"/></td>
<td width="15%"><input data-uid="'.$meta_id.'" type="button" class="update-row mdr_bk_btn1" value="Save"></td>
<td width="15%"><a data-uid="'.$meta_id.'" class="button remove-row" href="#1">Remove</a></td>
</tr>';
echo $row;
break;
case 'update_row':
$serial=$_POST['serial'];
$barcode=$_POST['barcode'];
$meta_value=serialize(array('serial'=> $serial,'barcode'=>$barcode));
$data=array(
'meta_value'=>$meta_value,
);
$result = $wpdb->update( $table_name,$data, $conditions );
echo $response=$result?"The row successfully updated":"There was an error updating the row";
break;
case 'remove_row':
$result = $wpdb->delete( $table_name, $conditions );
echo $response=$result?"The row successfully deleted":"There was an error deleting the row";
break;
default:
echo "Silence is golden";
break;
}
wp_die();
} ``

How to create custom repeater field which contains select menu and input field in wordpress without using any plugin?

Here I created the custom repeater field which works perfectly for input field, but I want select menu instead of input box, so I modified the above code, but it is not working. Whenever I click on update button, it adds a new repeater field and previously selected values are not displayed. Can anyone help?
```
<?php
add_action('admin_init', 'gpm_add_meta_boxes', 2);
function gpm_add_meta_boxes()
{
add_meta_box('gpminvoice-group', 'Paper Publication Information', 'Repeatable_meta_box_display', 'paper_publication', 'normal', 'default');
}
function Repeatable_meta_box_display()
{
global $post;
$gpminvoice_group = get_post_meta($post->ID, 'ra_publications', true);
wp_nonce_field('gpm_repeatable_meta_box_nonce', 'gpm_repeatable_meta_box_nonce');
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#add-row').on('click', function() {
var row = $('.empty-row.screen-reader-text').clone(true);
row.removeClass('empty-row screen-reader-text');
row.insertBefore('#repeatable-fieldset-one tbody>tr:last');
return false;
});
$('.remove-row').on('click', function() {
$(this).parents('tr').remove();
return false;
});
});
</script>
<table id="repeatable-fieldset-one" width="100%">
<tbody>
<?php
$publications = array('deccan-herald' => "Deccan Herald", 'kannada-prabha' => "Kannada Prabha", "times-now" => "Times Now", "vijayavani" => "Vijayavani");
if ($gpminvoice_group) :
foreach ($gpminvoice_group as $field) {
?>
<tr>
<td width="15%">
<select name="publicationName[]" value="<?php if ($field['publicationName'] != '') echo esc_attr($field['publicationName']); ?>">
<?php foreach ($publications as $publicationKey => $publicationValue) : ?>
<option value="<?php echo $publicationValue; ?>"><?php echo $publicationKey; ?></option>
<?php endforeach; ?>
</select>
</td>
<td width="70%">
<input type="text" placeholder="Enter article url" name="publicationUrl[]" value="<?php if ($field['publicationUrl'] != '') echo esc_attr($field['publicationUrl']); ?>" />
</td>
<td width="15%"><a class="button remove-row" href="#1">Remove</a></td>
</tr>
<?php
}
else :
// show a blank one
?>
<tr>
<td>
<!-- <input type="text" placeholder="Title" title="Title" name="TitleItem[]" /> -->
<select name="publicationName[]">
<?php foreach ($publications as $publicationKey => $publicationValue) : ?>
<option value="<?php echo $publicationValue; ?>"><?php echo $publicationKey; ?></option>
<?php endforeach; ?>
</select>
</td>
<td>
<!-- <textarea placeholder="Description" name="TitleDescription[]" cols="55" rows="5"> </textarea> -->
<input type="text" placeholder="Enter article url" name="publicationUrl[]" />
</td>
<td><a class="button cmb-remove-row-button button-disabled" href="#">Remove</a></td>
</tr>
<?php endif; ?>
<!-- empty hidden one for jQuery -->
<tr class="empty-row screen-reader-text">
<td>
<select name="publicationName[]">
<?php foreach ($publications as $publicationKey => $publicationValue) : ?>
<option value="<?php echo $publicationValue; ?>"><?php echo $publicationKey; ?></option>
<?php endforeach; ?>
</select>
</td>
<td>
<!-- <textarea placeholder="Description" cols="55" rows="5" name="TitleDescription[]"></textarea> -->
<input type="text" placeholder="Enter article url" name="publicationUrl[]" />
</td>
<td><a class="button remove-row" href="#">Remove</a></td>
</tr>
</tbody>
</table>
<p><a id="add-row" class="button" href="#">Add another</a></p>
<?php
}
add_action('save_post', 'custom_repeatable_meta_box_save');
function custom_repeatable_meta_box_save($post_id)
{
if (
!isset($_POST['gpm_repeatable_meta_box_nonce']) ||
!wp_verify_nonce($_POST['gpm_repeatable_meta_box_nonce'], 'gpm_repeatable_meta_box_nonce')
)
return;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if (!current_user_can('edit_post', $post_id))
return;
$old = get_post_meta($post_id, 'ra_publications', true);
$new = array();
$invoiceItems = $_POST['publicationName'];
$prices = $_POST['publicationUrl'];
$count = count($invoiceItems);
for ($i = 0; $i < $count; $i++) {
if ($invoiceItems[$i] != '') :
$new[$i]['publicationName'] = stripslashes(strip_tags($invoiceItems[$i]));
$new[$i]['publicationUrl'] = stripslashes($prices[$i]); // and however you want to sanitize
endif;
}
if (!empty($new) && $new != $old)
update_post_meta($post_id, 'ra_publications', $new);
elseif (empty($new) && $old)
delete_post_meta($post_id, 'ra_publications', $old);
}
?>
```

wordpress plugin development page form is being displayed at the bottom of every post and page edit

I am developing a wordpress CRUD plugin for a custom data table and it is working pretty well. However the page form that is used in the plugin for inserting or editing new records is also being displayed at the bottom of all page and post new page/post and edit page/post within the admin area.
Screenshot of page html from plugin displaying at the bottom of the add new page
The other pages within the plugin do not display anywhere else within wordpress as expected. I am completely lost to what I have done incorrectly and hope that someone can point me in the right direction to resolving this.
If I deactivate the plugin the issue remains.
I have used the boilerplate template as a base for developing the plugin found here:
https://wppb.me
This is adding the menu option and callback for it:
$sub2_cb = array(&$this,'new_award_category_page'); // callback function. name
add_submenu_page(
'Settings',
'Award Categories Add New',
'Add New',
'manage_options',
'add-category',
$sub2_cb
);
Here is the callback function that includes the page:
public function new_award_category_page() {
include_once( 'partials/new-award-category-page.php' );
}
The same page is being called from the row edit links in a wp_list_table for edits to existing records:
function column_category($item){
//Build row actions
$actions = array(
'edit' => sprintf('%s', $item['id'], __('Edit', 'new_award_category_page')),
);
//Return the title contents
return sprintf('%1$s <span style="color:silver"></span>%3$s',
/*$1%s*/ $item['category'],
/*$2%s*/ $item['id'],
/*$3%s*/ $this->row_actions($actions)
);
}
Here is the include file with the page php/html to check if insert or update new record, validation and display the form (split into sections to put in here):
global $wpdb;
$table_name = 'wp_categories'; // do not forget about tables prefix
$message = '';
$notice = '';
// this is default $item which will be used for new records
$default = array(
'id' => null,
'category' => '',
'paragraph_1' => '',
'paragraph_2' => '',
'img' => '',
'manager' => ''
);
// here we are verifying does this request is post back and have correct nonce
if (wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
// combine our default item with request params
$item = shortcode_atts($default, $_REQUEST);
// validate data, and if all ok save item to database
// if id is zero insert otherwise update
$item_valid = award_category_validate($item);
if ($item_valid === true) {
if ($item['id'] == 0) {
$result = $wpdb->insert($table_name, $item);
$item['id'] = $wpdb->insert_id;
if ($result) {
$message = __('Item was successfully saved', 'new_award_category_page');
} else {
$notice = __('There was an error while saving item', 'new_award_category_page');
}
} else {
$result = $wpdb->update($table_name, $item, array('id' => $item['id']));
if ($result) {
$message = __('Item was successfully updated', 'new_award_category_page');
} else {
$notice = __('There was an error while updating item', 'new_award_category_page');
}
}
} else {
// if $item_valid not true it contains error message(s)
$notice = $item_valid;
}
}
else {
// if this is not post back we load item to edit or give new one to create
$item = $default;
if (isset($_REQUEST['id'])) {
$item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $_REQUEST['id']), ARRAY_A);
if (!$item) {
$item = $default;
$notice = __('Item not found', 'new_award_category_page');
}
}
}
hhhh
function award_category_validate($item) {
$messages = array();
if (empty($item['category'])) $messages[] = __('Category title is required ', 'new_award_category_page');
if (empty($item['paragraph_1'])) $messages[] = __('Introductory paragraph is required', 'new_award_category_page');
if (empty($item['img'])) $messages[] = __('Representation image is required', 'new_award_category_page');
if (empty($messages)) return true;
return implode('<br />', $messages);
}
div class="wrap">
<h2><?php _e('Awards Entry Category Maintenenace', 'new_award_category_page')?></h2>
<?php if (!empty($notice)): ?>
<div id="notice" class="error"><p><?php echo $notice ?></p></div>
<?php endif;?>
<?php if (!empty($message)): ?>
<div id="message" class="updated"><p><?php echo $message ?></p></div>
<?php endif;?>
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-1">
<div id="post-body-content">
<div class="meta-box-sortables ui-sortable">
<form method="post">
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>
<?php /* NOTICE: here we storing id to determine will be item added or updated */ ?>
<input type="hidden" name="id" value="<?php echo $item['id'] ?>"/>
<table class="form-table">
<tr valign="top">
<td scope="row"><label for="tablecell"><?php esc_attr_e('Category Title:', 'WpAdminStyle'); ?></label>
</td>
<td>
<input type="text" name="category" id="category" value="<?php echo $item['category'] ?>" class="large-text" required />
</td>
</tr>
<tr valign="top">
<td scope="row"><label for="tablecell"><?php esc_attr_e('Introductory Paragraph:', 'WpAdminStyle'); ?></label>
</td>
<td>
<textarea id="" name="paragraph_1" cols="80" rows="8" class="large-text" required><?php echo $item['paragraph_1'] ?></textarea>
</td>
</tr>
<tr valign="top">
<td scope="row"><label for="tablecell"><?php esc_attr_e('Supplimentary Paragraph:', 'WpAdminStyle'); ?></label>
</td>
<td>
<textarea id="paragraph_2" name="paragraph_2" cols="80" rows="8" class="large-text"><?php echo $item['paragraph_2'] ?></textarea>
</td>
</tr>
<tr valign="top">
<td scope="row"><label for="tablecell"><?php esc_attr_e('Category Representation Image:', 'WpAdminStyle'); ?> required></label>
</td>
<td>
<input type="text" name="img" id="img" class="regular-text" value="<?php echo $item['img'] ?>">
<input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image" required>
</td>
</tr>
<tr valign="top">
<td scope="row">
</td>
<td>
<img id="previewImg" src="<?php echo $item['img'] ?>" style="width:150px;height:auto;">
</td>
</tr>
<tr valign="top">
<td scope="row"><label for="tablecell"><?php esc_attr_e('Owner:', 'WpAdminStyle'); ?></label>
</td>
<td>
<input type="text" name="manager" value="<?php echo $item['manager'] ?>" class="large-text" required />
</td>
</tr>
<tr valign="top">
<td scope="row">
</td>
<td>
<div align="right">
<input type="submit" value="<?php _e('Save', 'new_award_category_page')?>" id="submit" class="button-primary" name="submit">
</div>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
<br class="clear">
</div>
</div>
Thanks in advance for your help.

custom wordpress settings page doesn't save color

Found good sample of wordpress settings page code. Copy-pasted it with minor changes. Almost everything seems to be working and saving no problem. Except color and another thing (separate question). Does wordpress require some extra code for color picker, or am I doing something wrong?
Here is the code
add_action('admin_init', 'ozh_sampleoptions_init' );
add_action('admin_menu', 'ozh_sampleoptions_add_page');
function ozh_sampleoptions_init(){
register_setting( 'ozh_sampleoptions_options', 'ozh_sample', 'ozh_sampleoptions_validate' );
}
function ozh_sampleoptions_add_page() {
add_options_page('Ozh\'s Sample Options', 'Sample Options', 'manage_options', 'ozh_sampleoptions', 'ozh_sampleoptions_do_page');
}
function ozh_sampleoptions_do_page() {
?>
<div class="wrap">
<h2>Ozh's Sample Options</h2>
<form method="post" action="options.php">
<?php settings_fields('ozh_sampleoptions_options'); ?>
<?php $options = get_option('ozh_sample'); ?>
<table class="form-table">
<tr valign="top"><th scope="row">A Checkbox</th>
<td><input name="ozh_sample[option1]" type="checkbox" value="1" <?php checked('1', $options['option1']); ?> /></td>
</tr>
<tr valign="top"><th scope="row">A color</th>
<td><input name="ozh_sample[optioncolor1]" type="color" value="#000" /></td>
</tr>
<tr valign="top"><th scope="row">Some text</th>
<td><input type="text" name="ozh_sample[sometext]" value="<?php echo $options['sometext']; ?>" /></td>
</tr>
<tr valign="top"><th scope="row">Another text</th>
<td><input type="text" name="ozh_sample[blabla]" value="<?php echo $options['blabla']; ?>" /></td>
</tr>
</table>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
</p>
</form>
</div>
<?php
}
function ozh_sampleoptions_validate($input) {
$input['option1'] = ( $input['option1'] == 1 ? 1 : 0 );
$input['sometext'] = wp_filter_nohtml_kses($input['sometext']);
$input['blabla'] = wp_filter_nohtml_kses($input['blabla']);
$input['optioncolor1'] = wp_filter_nohtml_kses($input['optioncolor1']);
return $input;
}
To execute a task after a option has been updated, you can use updated_option action hook:
add_action( 'update_option_{option-name}', 'update_new_option_name_callback', 10, 2 );
function update_new_option_name_callback( $old_value, $value ) {
//Do something
}
Try this one with your option name
add_action( 'update_option_ozh_sample', 'update_new_option_name_callback', 10, 2 );
function update_new_option_name_callback( $old_value, $value )
{
//Do something
}

Pass back values to form to populate it? (lots of values)

I need to pass back a large string of results to a form, so that the form can read those results from the URL and then populate the form with them. Problem is, the link ends up being:
&key=value&key=value ... until it can't process anymore (I assume a URL has a length limit?) resulting in my form not being able to fully populate. I need another way to pass values back to my form file.
VIEW.php file (basically just a table of values right as they are from the database, with the first column "id" being a link. When I click on "id", it goes back to my add.php(form page) and populates the form with the data matching that id)
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETED</th>
<th></th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// loop to fetch data
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='molszewski1_a2_add.php'>$row[id]</a></td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td>$row[deleted]</td>";
$status = "$row[deleted]";
echo "<td><a href='molszewski1_a2_delete.php?id=$row[id]&flag=$status&sort=$sort'>";
$status = "$row[deleted]";
if ($status == 'n') {
$flag = "restore";
echo "delete";
} else if ( $status == 'y') {
$flag = "delete";
echo "restore";
}
echo "</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
ADD.php (form page where the form is supposed to fetch the data and populate it)
<?php
// If no form has been submitted, present form
if (empty($_GET))
{
add_form();
}
// if a form has been submitted
else
{
// if form_validity() == 1, proceed to connect
if (form_validity() == 1)
{
// connect to mysql + database
connect();
$saleItem = "n";
$discountItem = "n";
if( array_key_exists( 'saleItem', $_GET ) && $_GET['saleItem'] == 'y' )
{ $saleItem = "y"; }
if( array_key_exists( 'discountItem', $_GET ) && $_GET['discountItem'] == 'y' )
{ $discountItem = "y"; }
// get values from form, insert into database
$sql=("INSERT INTO inventory (name,
manufac,
model,
descrip,
onhand,
reorder,
cost,
price,
sale,
discont,
deleted)
VALUES ('$_GET[itemName]',
'$_GET[manufacturer]',
'$_GET[model]',
'$_GET[description]',
'$_GET[numberOnHand]',
'$_GET[reorderLevel]',
'$_GET[cost]',
'$_GET[sellingPrice]',
'$saleItem',
'$discountItem', 'n')");
// if the query doesn't work, display error message
if (!(mysql_query($sql))) { die ("could not query: " . mysql_error()); }
add_form();
// redirect to view.php after form submission
// use php instead
echo "<meta http-equiv='REFRESH' content='0;url=molszewski1_a2_view.php'>";
}
else
{
// if form is not valid (form_validity returns 0), display error messages
add_form();
}
}
?>
FUNCTIONS.php (all my functions for stuff like the form)
<?php function page_navigation(){ ?>
<div class="center">
<input type="button" value="ADD" />
<input type="button" value="VIEW" />
<input type="button" value="VIEW DELETED" />
<input type="button" value="VIEW ACTIVE" />
<br />
<br />
</div>
<?php } ?>
<?php function add_form() { ?>
<form action="molszewski1_a2_add.php" method="get" id="form">
<table width="529px">
<tr>
<td>ITEM NAME</td>
<td><input name="itemName" size="30" type="text" value="<?php echo $_GET["itemName"] ?>"/></td>
</tr>
<tr>
<td>MANUFACTURER</td>
<td><input name="manufacturer" size="30" type="text" value="<?php echo $_GET["manufacturer"] ?>"/></td>
</tr>
<tr>
<td>MODEL</td>
<td><input name="model" size="30" type="text" value="<?php echo $_GET["model"] ?>"/></td>
</tr>
<tr>
<td>DESCRIPTION</td>
<td><textarea name="description" rows="3" cols="20"><?php echo $_GET["description"] ?></textarea></td>
</tr>
<tr>
<td>ON HAND</td>
<td><input name="numberOnHand" size="30" type="text" value="<?php echo $_GET["numberOnHand"] ?>"/></td>
</tr>
<tr>
<td>REORDER LEVEL</td>
<td><input name="reorderLevel" size="30" type="text" value="<?php echo $_GET["reorderLevel"] ?>"/></td>
</tr>
<tr>
<td>COST</td>
<td><input name="cost" size="30" type="text" value="<?php echo $_GET["cost"] ?>"/></td>
</tr>
<tr>
<td>SELLING PRICE</td>
<td><input name="sellingPrice" size="30" type="text" value="<?php echo $_GET["sellingPrice"] ?>"/></td>
</tr>
<tr>
<td>SALE ITEM</td>
<td>
<input type="checkbox" name="saleItem" value="y" <?php if( isset( $_GET['saleItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td>DISCOUNTED ITEM</td>
<td>
<input type="checkbox" name="discountItem" value="y" <?php if( isset( $_GET['discountItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="save" name="submit" id="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Use method="post" and $_POST (instead of $_GET).
POST requests can be much larger than GET requests as GET requests are limited by the maximum length of a URL. POST requests are limited by the size of the max_post_size ini-value which is usually a few megabytes.

Categories