Posting HTML form to new wp database table - mysql

I'm trying to make a HTML form post the input values to a custom table in the WordPress database. I've managed to get something to show up in a new row, but almost all of my values return N; instead of the value from the form.
Here's the code I have in my page template:
<?php
global $wpdb;
global $current_user;
$userID = $current_user->ID;
$brand = serialize($_POST["brand"]);
$url = serialize($_POST["url"]);
$sector = serialize($_POST["sector"]);
$keywords = serialize($_POST["keywords"]);
if (
'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'updateSearch' ) {
$ufDataUpdate = $wpdb->insert( 'wp_wct3', array(
'date' => current_time('mysql'),
'userid' => $userID,
'brand' => $brand,
'url' => $url,
'sector' => $sector,
'keywords' => $keywords ) );
}
?>
<form method="post">
<label for="brand">Brand/Product Name: </label>
<input type="text" id="brand" placeholder="eg: Spidr" class="clearfix" required />
<label for="website">Website address: </label>
<input type="url" id="url" placeholder="eg: www.spidr.co.uk" class="clearfix" required />
<label for="sector">Market sector: </label>
<input type="text" id="sector" placeholder="eg: Internet Marketing Tools" class="clearfix" required />
<label for="keyword">Keywords/Phrases:<br><span class="orange">(comma separated)</span></label>
<textarea cols="0" rows="8" class="light" id="keywords" required></textarea>
<input type="submit" id="submit" name="submit" class="button-65 mobile-button" value="release the spiders!">
<?php wp_nonce_field( 'updateSearch' ); ?>
<input name="action" type="hidden" id="action" value="updateSearch" />
</form>
Where wp_wct3 is the database name and each item in the array is the name of each column in that table.
I'm not sure if my issue lies in this code, or in the set-up of the database itself. I've used the Wordpress custom tables plugin to make the new table. The brand, url and sector simply use the text definition, while the keywords use enum('0','1').
Anyone have any ideas why the values aren't returning and I'm just getting N; ?

this is my custom-form template.. it works for me
<?php
/**
Template Name: Custom-Form
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* #package WordPress
* #subpackage Twenty_Twelve
* #since Twenty Twelve 1.0
*/
get_header(); ?>
<div id="primary" class="site-content">
<div id="content" role="main">
<?php
if (!empty($_POST)) {
global $wpdb;
$table = wp_achord;
$data = array(
'name' => $_POST['yourname'],
'chord' => $_POST['chord']
);
$format = array(
'%s',
'%s'
);
$success=$wpdb->insert( $table, $data, $format );
if($success){
echo 'data has been save' ;
}
}
else {
?>
<form method="post">
<input type="text" name="yourname">
<textarea name="chord"></textarea>
<input type="submit">
</form>
<?php } ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>

Figured out the main issue. I'd missed out the name attribute from the form itself, so my PHP wasn't picking up the field values!

Related

Wordpress. Insert form values to custom table

How can i on click on submit send values to my custom mysql table??
Form html:
<form action="/ekz.php" method="post">
<input type="text" name="jjkk1">
<input type="text" name="jjkk2">
<input type="text" name="jjkk3">
<input type="text" name="jjkk4">
<input type="submit" name="submit">
</form>
Table name is wp_ekz2020:
Try doing like this :
<?php
if(isset($_POST['submit']))
{
global $wpdb;
$a=$_POST['jjkk1'];
$b=$_POST['jjkk2'];
$c=$_POST['jjkk3'];
$d=$_POST['jjkk4'];
$wpdb->insert( 'wp_ekz2020', array( 'num1' => $a, 'num2' => $b,'num3' => $c,
'num4' => $d), array( '%s', '%s','%s', '%s' ) );
}
?>
please try to place both html and php in single file
here is code i have try and it works
<form action="<?php the_permalink(); ?>" method="post">
<input type="text" name="num1">
<input type="text" name="num2">
<input type="text" name="num3">
<input type="text" name="num4">
<input type="submit" name="submit">
</form>
if(isset($_POST['submit']))
{
function insertnumber(){
global $wpdb;
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$num3 = $_POST['num3'];
$num4 = $_POST['num4'];
$table_name = "newtab";
$wpdb->insert( $table_name, array(
'num1' => $num1,
'num2' => $num2,
'num3' => $num3,
'num4' => $num4
) );
}
insertnumber();
}
put <?php the_permalink(); ?> in your form action
i hope above code will help you : )
change table name and also variable
in this case, whenever you submit the form with action attribute then the page gets reloaded, and '$wpdb' returns null. So this will cause error.
To prevent this you have to include 'wp-load.php' in your file or you can use
add_action('init', 'your_function_name')

WooCommerce - Add Country/State Select Fields to Registration Form?

I've read through, and followed the following tutorial How to add custom fields in user registration on the "My Account" page and successfully added several custom fields to the registration form on the My Account page (seen when users are logged out).
I'd like to add billing country/state as select fields if the shop owner has defined them. (i.e. If the shop only services Canada, load only Provinces).
Unfortunately the tutorial doesn't cover select fields, just basic text fields. I did find another thread that lists how to add countries but it's all countries, not the ones specified by the shop owner.
Anyone have any further insight in loading Countries/Provinces/States that are set by the shop owner? So far I've got the following:
/**
* Add new register fields for WooCommerce registration.
*
* #return string Register fields HTML.
*/
function wooc_extra_register_fields() {
$countries_obj = new WC_Countries();
$countries = $countries_obj->__get('countries');
?>
<fieldset>
<legend><h3>Address</h3></legend>
<p>Please provide the main contact address for this account.</p>
<p class="form-row form-row-wide">
<label for="reg_billing_address_1"><?php _e( 'Address', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_address_1" id="reg_billing_address_1" placeholder="Street/P.O Box address" value="<?php if ( ! empty( $_POST['billing_address_1'] ) ) esc_attr_e( $_POST['billing_address_1'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-wide">
<label for="reg_billing_address_2"><?php _e( 'Address Line 2', 'woocommerce' ); ?></label>
<input type="text" class="input-text" name="billing_address_2" id="reg_billing_address_2" placeholder="Apartment, suite, unit etc. (optional)" value="<?php if ( ! empty( $_POST['billing_address_2'] ) ) esc_attr_e( $_POST['billing_address_2'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-wide">
<label for="reg_billing_city"><?php _e( 'Town/City', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_city" id="reg_billing_city" value="<?php if ( ! empty( $_POST['billing_city'] ) ) esc_attr_e( $_POST['billing_city'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-wide">
<label for="reg_billing_postcode"><?php _e( 'Postal Code', 'woocommerce' ); ?></label>
<input type="text" class="input-text" name="billing_postcode" id="reg_billing_postcode" value="<?php if ( ! empty( $_POST['billing_postcode'] ) ) esc_attr_e( $_POST['billing_postcode'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-wide">
<label for="reg_billing_country"><?php _e( 'Country', 'woocommerce' ); ?> <span class="required">*</span></label>
<select class="country_select" name="billing_country" id="reg_billing_country">
<?php foreach ($countries as $key => $value): ?>
<option value="<?php echo $key?>"><?php echo $value?></option>
<?php endforeach; ?>
</select>
</p>
</fieldset>
<?php
}
add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );
To add Woocommerce Country/State fields in some other form use the following code in template:
<?php
$field = [
'type' => 'country',
'label' => 'Country',
'required' => 1,
'class' => ['address-field']
];
woocommerce_form_field( 'billing_country', $field, '' );
$field = [
'type' => 'state',
'label' => 'State',
'required' => 1,
'class' => ['address-field'],
'validate' => ['state']
];
woocommerce_form_field( 'billing_state', $field, '' );
?>
To tie the Country field selection with State field options put these fields into some container with class woocommerce-billing-fields AND include woocommerce country-select.js at page with the form:
<?php
$handle = 'wc-country-select';
wp_enqueue_script($handle, get_site_url().'/wp-content/plugins/woocommerce/assets/js/frontend/country-select.min.js', array('jquery'), true);
?>
Maybe it's too late but :
Instead of :
<p class="form-row form-row-wide">
<label for="reg_billing_country"><?php _e( 'Country', 'woocommerce' ); ?> <span class="required">*</span></label>
<select class="country_select" name="billing_country" id="reg_billing_country">
<?php foreach ($countries as $key => $value): ?>
<option value="<?php echo $key?>"><?php echo $value?></option>
<?php endforeach; ?>
</select>
</p>
place :
<?php
$countries_obj = new WC_Countries();
$countries = $countries_obj->get_allowed_countries();
woocommerce_form_field('billing_country', array(
'type' => 'select',
'class' => array( 'chzn-drop' ),
'label' => __('Pays'),
'placeholder' => __('SĂ©lectionnez un pays'),
'options' => $countries
)
); ?>
You'll get a select dropdown of allowed countries
If you want a list of all countries, replace "get_allowed_countries();" by "__get('countries');"
Source
States are treated in this source

Update multiple rows with same id using foreach loop

I echo 2 input-fields (2 db columns) foreach row in the database (where id=$id) with each row's data being inside the input field. Admin-user can change data inside input-field and click update.
Currently, when clicking the update-button, it does update the rows (where id=$id) but it updates each row with the input-data of the first input field instead of updating input-data foreach input field. Thank you in advance for help.
view:
<form action='<?= site_url("admin/do_edit_page"); ?>' method='POST'>
<?php foreach($link_data as $row) : ?>
Link:<br />
<input type='text' name='page_link_title' value='<?= $row->link_title; ?>'>
<input type='text' name='page_link_sub_title' value='<?= $row->link; ?>'><br />
<?php endforeach; ?>
<input type='submit' name='update_site' value='Update'>
</form>
controller:
public function do_edit_page(){
$id = $this->input->post('page_id', TRUE);
$this->content_model->update_links($id);
}
model:
public function update_links($id){
foreach($_POST as $update_rows){
$update_rows = array(
array(
'page_id' => $id,
'link_title' => $this->input->post('page_link_title', TRUE),
'link' => $this->input->post('page_link_sub_title', TRUE)
)
);
$this->db->update_batch('content_links', $update_rows, 'page_id');
}
}
you have to move your form tag between the foreach loop so that it can submit the data of single row. something like this
<?php foreach($link_data as $row) : ?>
<form action='<?= site_url("admin/do_edit_page"); ?>' method='POST'>
Link:<br />
<input type='text' name='page_link_title' value='<?= $row->link_title; ?>'>
<input type='text' name='page_link_sub_title' value='<?= $row->link; ?>'><br />
<input type='submit' name='update_site' value='Update'>
</form>
<?php endforeach; ?>

Wordpress Custom Registration Form

I have a client that needs a custom registration form.
I need to make a custom design on this page
I need to add custom fields like First Name, Company, Phone, etc.
Someone can help me with this?
A better place to ask WordPress questions is probably on WordPress Answers. Anyhoo, if you want to solve this without plugins, you need three things:
A custom WordPress theme
A Page Template
A WordPress Page that uses the Page Template
When you have these three parts in place, you can do the following in your Page Template:
<?php
/*
Template Name: Registration
*/
global $current_user;
wp_get_current_user();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$company = $_POST['company'];
if (($firstname != '') && ($lastname != '') && ($company != '')) {
// TODO: Do more rigorous validation on the submitted data
// TODO: Generate a better login (or ask the user for it)
$login = $firstname . $lastname;
// TODO: Generate a better password (or ask the user for it)
$password = '123';
// TODO: Ask the user for an e-mail address
$email = 'test#example.com';
// Create the WordPress User object with the basic required information
$user_id = wp_create_user($login, $password, $email);
if (!$user_id || is_wp_error($user_id)) {
// TODO: Display an error message and don't proceed.
}
$userinfo = array(
'ID' => $user_id,
'first_name' => $firstname,
'last_name' => $lastname,
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_usermeta($user_id, 'company', $company);
}
if (is_user_logged_in()) : ?>
<p>You're already logged in and have no need to create a user profile.</p>
<?php else : while (have_posts()) : the_post(); ?>
<div id="page-<?php the_ID(); ?>">
<h2><?php the_title(); ?></h2>
<div class="content">
<?php the_content() ?>
</div>
<form action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
<div class="firstname">
<label for="firstname">First name:</label>
<input name="firstname"
id="firstname"
value="<?php echo esc_attr($firstname) ?>">
</div>
<div class="lastname">
<label for="lastname">Last name:</label>
<input name="lastname"
id="lastname"
value="<?php echo esc_attr($lastname) ?>">
</div>
<div class="company">
<label for="company">Company:</label>
<input name="company"
id="company"
value="<?php echo esc_attr($company) ?>">
</div>
</form>
</div>
<?php endwhile; endif; ?>
Now, when you want to retrieve the stuff you've stored, you need to know whether the information is within the User object itself or in metadata. To retrieve the first and last name (of a logged-in user):
global $current_user;
$firstname = $current_user->first_name;
$lastname = $current_user->last_name;
To retrieve the company name (of a logged-in user):
global $current_user;
$company = get_usermeta($current_user->id, 'company');
That's the basic gist of it. There's still a lot of stuff missing here, like validation, error message output, the handling of errors occurring within the WordPress API, etc. There's also some important TODO's that you have to take care of before the code will even work. The code should probably also be split into several files, but I hope this is enough to get you started.
An advantage of using a custom registration form is that modifying the code according to the user's needs becomes easy. For a custom submit form you can make use of existing hooks in Wordpress like template_redirect and then map that hook to some function which will do the post-processing of the form, like validation and submitting data to the site's database. You can refer to an in-depth article here.
<div class="employee">
<input type="hidden" name="show_msg">
<form name="customer_details" method="POST" required="required" class="input-hidden">
Your Name: <input type="text" id="name" name="customer_name">
Your Email: <input type="text" id="email" name="customer_email">
Company: <input type="text" id="company" name="company">
Sex: <input type="radio" name="customer_sex" value="male">Male <input type="radio" name="customer_sex" value="female">Female
<textarea id="post" name="experience" placeholder="Write something.." style="height:400px;width:100%"></textarea>
<input type="submit" value="Submit">
<!--?php wp_nonce_field( 'wpshout-frontend-post','form-submit' ); ?-->
</form></div>
PHP function
function wpshout_frontend_post() {
wpshout_save_post_if_submitted();
}
add_action('template_redirect','wpshout_frontend_post', 2);
A custom WordPress registration form has two major advantages over the standard form.
The first is the integration with the overall look and feel of the website theme. Standard forms often don’t work well with custom themes and there is always a chance that the custom CSS files do not render well with the form. A custom form, on the other hand, can be easily set up to work with custom CSS.
The second and more popular reason of using a custom registration form is the option of custom fields that are not included on the standard form. A small custom registration form speeds up the process and collects all the necessary data from a neat interface.
function wordpress_custom_registration_form( $first_name, $last_name, $username, $password, $email) {
global $username, $password, $email, $first_name, $last_name;
echo '
<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
First Name :
<input type="text" name="fname" value="' . ( isset( $_POST['fname']) ? $first_name : null ) . '">
Last Name:
<input type="text" name="lname" value="' . ( isset( $_POST['lname']) ? $last_name : null ) . '">
Username <strong>*</strong>
<input type="text" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '">
Password <strong>*</strong>
<input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '">
Email: <strong>*</strong>
<input type="text" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '">
<input type="submit" name="submit" value="Register"/>
</form>
';
}
This form can be inserted anywhere by using the shortcode [wp_registration_form]. Here is the code snippet for setting up the shortcode:
function wp_custom_shortcode_registration() {
ob_start();
wordpress_custom_registration_form_function();
return ob_get_clean();
}
I hope that by now you have a fair idea of creating a WordPress custom Registration form.Still any confusion kindly check Build Custom WordPress Registration Forms

Passing data from DB to update form using CI CRUD

I'm trying to write a compact update controller for CRUD activity. Here is the basic code:
Controller:
function update($id)
{
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('age','Age','required|is_numeric');
$this->form_validation->set_rules('country','Country','');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) {
//Failed validation or first run
$data = $this->my_model->get_record($id);
$this->load->view('myform_view', $data);
} else {
//Validation success, update DB
}
}
View:
<?php
$attributes = array('class' => '', 'id' => '');
echo form_open('my_form', $attributes); ?>
<p>
<label for="name">Name</label>
<?php echo form_error('name'); ?>
<br /><input id="name" type="text" name="name" value="<?php echo set_value('name'); ?>" />
</p>
<p>
<label for="age">Age</label>
<?php echo form_error('age'); ?>
<br /><input id="age" type="text" name="age" value="<?php echo set_value('age'); ?>" />
</p>
<p>
<label for="country">Country</label>
<?php echo form_error('country'); ?>
<br /><input id="country" type="text" name="country" value="<?php echo set_value('country'); ?>" />
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
This is the basic structure, however the first time the form is run there is no validated data. Therefore I have to grab this from the DB. Whats the best way to pass this to the view on the first run? And then once the form has been submitted, if validation fails then I want the failed data to show not to reload from the DB again. Whats the best way to do this?
You should have another method for the viewing aspect. Then submit your form against the "update" method. In there, you define the the form_validation as you have now.
I asked a similar question. See this link
grab the data in update controller first for edit such as
$query = $this->db->where('id',$id)->get('table_name');
$data['edit'] = $query->result_array();
and then check it in view file
value="<?php if(isset($edit[0]['age'])){echo $edit[0]['age'];}else{echo set_value('age');}?>"