0

I am trying to build a plugin, in the plugin I want the admin to be able to send data to database and let the user view the data in the front end, but I am still having problems with sending data to database

I am trying to validate this code to keep it safe from injection This is my code

<?php
    if (!empty($_POST)) {
        global $wpdb;
        $table = wp_save;
        $data = array(
            'name' => $_POST['yourname'],
            'chord'    => $_POST['number']
        );
        $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="number"></textarea>
             <input type="submit">
         </form>
        <?php 
    }  
?>
  • $table = wp_save; should be $table = 'wp_save'; - do you have the same error in your actual code? Do you have debugging enabled and get any error messages? – kero Jul 2 '18 at 11:17
2
$table = wp_save;

This is setting $table to a PHP constant wp_save. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to wp_save. To do that you need to put the table name between quotes, so that it's a String:

$table = 'wp_save';

However, given that WordPress users can change the wp_ prefix in the database to whatever they like, you should use $wpdb->prefix to use the correct prefix as set by the user:

$table = $wpdb->prefix . 'save';

Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress.

-1
<?php
if (!empty($_POST)) {
    global $wpdb;
    $table   = $wpdb->prefix . 'wp_save'; //wp_save or save only?
    $data    = array(
        'name' => $_POST['yourname'],
        'chord' => $_POST['number']
    );
    $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="number"></textarea>
             <input type="submit">
         </form>
        <?php
}
?>

Hope this helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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