2

I am new to WordPress but I am good with PHP programmings, if I wanted to get value from the textbox and store it in the database in WordPress can I do?

for ex

form1.html

<form name="form" method="post" action="value_get.php">
<input type="text" id="t1" name="t1">
<input type="submit" value="submit">
</form>

value_get.php

<?php

$firstname = mysqli_real_escape_string($con, $_POST['tb1']);

$con=mysqli_connect("localhost","root","","wordpress");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"INSERT INTO wp_exTable (FirstName)
VALUES ('$firstname')");


if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

Can I do these things in WordPress? with little tweaking

4

5 Answers 5

3

From PHP to WordPress

If you are experienced in programming and in PHP, you know that saving data coming from a form basically involves these steps:

  • validation
  • sanitization
  • connection to database
  • store value in database

even if "plain" PHP would work for all of them, WordPress has helpers and specific best practices for them.

Validation

This is the only part WordPress won't help you much. PHP is your friend here.

Sanitization

WordPress has different helpers for sanitization.

For data coming from forms, there are different sanitize_* functions, like sanitize_text_field() that you can use. Find them here. Note that not all the functions you'll find in the link are useful for the scope.

Connection to database

In WordPress context, you don't connect to databse. You let WordPress do it, then you use the database API to execute queries on database.

The WordPress database API is summarized in the wpdb object, available in the global $wpdb variable.

There's nothing else to do. WordPress will also take care of close the connection when necessary.

Store value in database

A documentantion on global $wpdb API is available here. As you can see there, there are a lot of methods.

Probably the most useful are the helpers for CRUD oerations:

  • get_results() / get_row() / get_col() / get_var()
  • insert()
  • update()
  • delete()

It is impoertant to note that data sanitized with sanitize_* functions introduced above, should be escaped with database-specific methods before being saved into database.

For the scope there's the method prepare() that provides a way to escape SQL statements using a sprintf-like syntax.

Form pages and form processing routines

Everything said above is necessary to process the data coming from forms.

However you also need:

  • a "page" where to place the form
  • a "place" where to place form processing routine.

Frontend and backend form pages

In WordPress we can distinguish of two categories of forms: forms who belong in frontent and thosee in who belong in backend.

For frontent forms, you will probably place all the HTML in one of the templates, and that's it.

For backend forms, there are many possibilities.

If you want to store values that releates to a post, you will probably want to add a metabox and place a form there. Actually, in this case you don't use a "full" form, but just form inputs that become part of the whole post edit form.

The same approach can be taken, using specific "hooks", to add fields to edit / creation forms for taxonomies, users and so on. This website and the web in general are full of examples and guidance about this.

In case the data you want to store are completely unrelated to any WordPress core "entity" (for example you are going to build an option page for a custom plugin) you probably want to register an admin page and place the form there.

Form processing

How to process data coming from a form depends on how you printed it.

If you used any of the way to add fields to existing WordPress forms, you can't just use your own routine, but you have to hook the existing routine and process your data.

For example, if you added a post metabox, your fields were added to post edit/creation form, and will need to hook save_post or any other hook fired when WordPress save a post, to check for data coming from your form fields and process them.

If your form comes from frontend, or you created a completely new form in backend, you could be tempted to create a file that process the form.

This won't really work, because you are going to use WordPress environment (remember the $wpdb object?) and so you would need to bootstrap WordPress manually, which is not rellay recommended.

Instead you could:

  • send the form to the same page that contains the form and place processing code on top of markup. This is really not suggested because mixing processing code and markup code is a mess to maintain.
  • send the form to admin-ajax.php (the full URL is obtained via admin_url('admin-ajax.php')) and then use "admin_ajax_{$action}" / admin_ajax_nopriv_{$action} to hook your routine. See Codex about AJAX_in_Plugins
  • send the form to admin-post.php (the full URL is obtained via admin_url('admin-post.php')) and then use "admin_post_{$action}" / admin_post_nopriv_{$action} to hook your routine
  • Use the REST API to register a custom route and then process the form in the REST route handler

On data structure

WordPress has its own tables and a specific data structure.

Using dbDelta function you could create custom tables and the $wpdb object is still able to operate on those, however this should be avoided as possible.

Reason is that custom tables in WordPress are cumbersome to maintain (WP is missing things like migrations or fixtures) and also using custom tables you miss the possibility to use many of WordPress API that is available if you fit your data into WordPress core "Entities".

For example, if your data is related to posts you could use taxonomies or post meta to store them.

If data is user-related data you could use user meta, or terms meta for data related to taxonomy terms.

In case of "generic" data you could use options or you could use theme modifications in case of theme-specific confugration.

If you do so, when you need to retrieve/store data, instead of using wpdb methods you can use specific APIs.

Taxonomies, post meta, term meta, user meta, options, theme modifications... provide methods to interact with data at higher level, simplifing the access to data and providing other benefits like cache, filterability, compatibility with other parts of core (e.g. customizer and REST API), compatibility with plugins...

3

A simple solution to store the value in database would be by using WordPress' add_option() function. It stores the value in the wp_options table in the database.

$firstname = mysqli_real_escape_string( $con, $_POST[ 'tb1' ] );
add_option( 'first_name' , $firstname );
echo "1 record added";

You can then access the value anytime using get_option( 'first_name' ).

If you want to run more customized queries use $wpdb->query(). Read the ẁpdb Codex page for more details.

4
  • Can you tell me how to add a textbox in the page... Oct 9, 2014 at 8:19
  • Where do you want to put the textbox? In WP admin area or front end? Oct 9, 2014 at 8:23
  • front end... and the data should be stored in the database... Oct 9, 2014 at 10:08
  • You can use it as custom field this will help you yo store it in database. Jan 19, 2017 at 6:32
2

for displaying text box on the front end and storing data in database follow the below steps :

  1. Create a php file in your activated theme folder and put the following code : enter image description here

  2. Now Create a page into the Wordpress using page menu on Backend and in Add new Page section you will get the "Page Attribute" section on the right hand side of the page, Now choose the your template page from the Template dropdown and Publish the page.

  3. Now view the page and you will find the text box on page.

  4. Fill the value and save, value will be saved into the database in customized table.
4
  • For any doubt, feel free to ask Jul 6, 2016 at 12:33
  • It would be good if you paste code instead of a screenshot.
    – bravokeyl
    Jul 21, 2016 at 8:50
  • Thanks for trying to help the poster out. When you paste code into an answer, please use text rather than a graphic. This allows the poster to copy and paste should they wish and also allows others to edit the answer to correct typos and syntax errors (line 11's class property in a double quoted string without using the more complex syntax with braces, for example). Jul 21, 2016 at 8:52
  • Sure @Andy Macaulay-Brook, I'll keep this in my mind and from next time onwords i'll share the code instead of the screenshot. For this answer i'll update this Jul 25, 2016 at 6:28
1

Instead of using native PHP functions like mysqli_connect you should make use of the possibilities WordPress offers to do the same. This is better for compatibility and maintainability reasons. Namely you can use the wpdb class, which not only can be used for WordPress' own database tables, but external ones too. For adding new entries you can use the insert() method of the class - for more information see the INSERT rows section on the wpdb Codex page. Below you find some exemplary code:

global $wpdb;
$fname  = $_POST[ 'txt_fname' ];
$lname  = $_POST[ 'txt_lname' ];
$tbl    = 'wp_exTable';
$others = $_POST[ 'txt_email' ];
$wpdb->insert(
    'wp_exTable',
    array(
        'first_name' => $fname,
        'last_name'  => $lname,
        'email'      => $others
    ),
    array(
        '%s',
        '%s',
        '%s'
    )
);

Last but not least, you probably should think about the fact if you are actually in need of an extra table. You could for example make use of post meta like @RamShengale suggested.

0
0

Please try this code for updating the records in database in wordpress. For this firstly create a file.php inside your selected wordpress folder and then use this file as a template. And this code will work perfectly and if anybody knows the right regular expression for validating the name please suggest me. Thank you all.

<?php /* Template Name: your template name */ ?>
<style>
.error {color: #FF0000;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
        type="text/javascript"></script>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
        rel="Stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function() {
            //this calculates values automatically 
            $("#name").keypress(function() {
            validate();
            });
            });
function validate() {

            /*=============== Validate The Name ======================*/
                var fname =document.forms["abc"]["name"].value; 
                var name_regex = /^[a-z A-Z]+$/;
            if(fname == 0||fname==null )
            {
                    document.getElementById('nameErr').innerHTML = "* Please fill your name";
                    return false;
            }
            else
            {
                    if (!fname.match(name_regex)) {
                    document.getElementById('nameErr').innerHTML = "* Name should be alphabet";
                    return false;
                    }
                    else{
                                document.getElementById('nameErr').innerHTML = "";
                    }
            }
}

        <?php get_header(); ?>
        <?php
        if (!empty($_POST)) {
        global $wpdb;
            $table = wp_tablename;
            $data = array(
                'firstname' => $_POST['yourname']
            );
            $format = array(
                '%s'
            );
            $success=$wpdb->insert( $table, $data, $format );
            if($success){
            echo 'Thanks for submitting your information soon we will contact to you'; 
        }
        }
        else   {
        ?>
        <div class="container">
            <div class="row">
                <form method="post" class="form-horizontal" id="abc" onsubmit="return validate(this)">
                <div class="col-md-3">Full name: </div><div class="col-md-8"> <input type="text" name="yourname" class="form-control" id="name"><span class="error" id="nameErr"></span></div>

                <div class="col-md-6"><input type="reset" name="reset" class="btn btn-danger"></div><div class="col-md-6"><input type="submit" value="Register" class="btn btn-success"></div>
                </form>
            </div>
        </div>
        <?php }  ?>

<?php get_footer(); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.