最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Inserting choice in database table

programmeradmin8浏览0评论

So I have this code:

<?php
global $wpdb;
// This adds the prefix which is set by the user upon installation of WordPress.
$table_name = $wpdb->prefix . 'wpex_programma';
// This will get the data from your table.
$retrieve_data = $wpdb->get_results( "SELECT Anaam FROM {$table_name}" );
?>
<form action="#" enctype="multipart/form-data" method="post">
<!--Is set_programma_action and set_programma? Are they supossed to stay like this?-->
    <?php wp_nonce_field( 'set_programma_action', 'set_programma' ); ?>
    <table>
        <?php foreach ( $retrieve_data as $retrieved_data ) { ?>
            <tr>
                <th>Programma:</th>
                <td style="vertical-align: middle;"><?php echo esc_html( $retrieved_data->Anaam ); ?></td>
                <th>
                    <button name="programma" type="submit" value="<?php echo esc_attr( $retrieved_data->Anaam ); ?>">Abonneer</button>
                </th>
            </tr>
        <?php } ?>
    </table>
</form>

<?php
    // Verify nonce and save data if the user is logged in.
    // Nonce docs: /
    if (isset( $_POST['programma'] ) && isset( $_POST['set_programma'] ) && wp_verify_nonce( $_POST['set_programma'], 'set_programma_action' )) {

      $data = filter_input( INPUT_POST, 'programma', FILTER_SANITIZE_STRING );
      $current_user_id = get_current_user_id();

        if ( $current_user_id && ! empty( $data ) ) {
            update_user_meta( $current_user_id, 'programma', $data );
        }
    }
?>

With this code, I want to allow users to select a choice. Once they have made their choice, it will be saved in the database.

In my previous code, I updated the choices in the user table. I decided that it is in my advantage to save it in the wpex_usermeta table. However, the problem is that I do not know how I can update the choice in the database. For now I am just using the word 'Jimbo'. The choices are saved in the variable $retrieved_data. But that contains all choices.

How can I make sure that when a user chooses something, his/her choice is updated in the database. The updating is already done. I just need to know how the choices are updated.

As you can see the word Jimbo in the meta_value (of user id 3) table is updated to Jimbo:

I have tried to use $retrieved_data in my update_user_meta like this:

update_user_meta( $user_id, 'meta_value', $retrieved_data );

After doing var_dump(get_error_last($retrieved_data)); the following was shown:

object(stdClass)#8135 (1) { ["Anaam"]=> string(12) "Uitwerkingen" }

The most recent uploaded choice was shown. It should show the option that is choicen.

How can I make sure the choices are updated in the meta_value table?

Table structure where the data is inserted:

Table structure where the data is retrieved:

So I have this code:

<?php
global $wpdb;
// This adds the prefix which is set by the user upon installation of WordPress.
$table_name = $wpdb->prefix . 'wpex_programma';
// This will get the data from your table.
$retrieve_data = $wpdb->get_results( "SELECT Anaam FROM {$table_name}" );
?>
<form action="#" enctype="multipart/form-data" method="post">
<!--Is set_programma_action and set_programma? Are they supossed to stay like this?-->
    <?php wp_nonce_field( 'set_programma_action', 'set_programma' ); ?>
    <table>
        <?php foreach ( $retrieve_data as $retrieved_data ) { ?>
            <tr>
                <th>Programma:</th>
                <td style="vertical-align: middle;"><?php echo esc_html( $retrieved_data->Anaam ); ?></td>
                <th>
                    <button name="programma" type="submit" value="<?php echo esc_attr( $retrieved_data->Anaam ); ?>">Abonneer</button>
                </th>
            </tr>
        <?php } ?>
    </table>
</form>

<?php
    // Verify nonce and save data if the user is logged in.
    // Nonce docs: https://developer.wordpress/themes/theme-security/using-nonces/
    if (isset( $_POST['programma'] ) && isset( $_POST['set_programma'] ) && wp_verify_nonce( $_POST['set_programma'], 'set_programma_action' )) {

      $data = filter_input( INPUT_POST, 'programma', FILTER_SANITIZE_STRING );
      $current_user_id = get_current_user_id();

        if ( $current_user_id && ! empty( $data ) ) {
            update_user_meta( $current_user_id, 'programma', $data );
        }
    }
?>

With this code, I want to allow users to select a choice. Once they have made their choice, it will be saved in the database.

In my previous code, I updated the choices in the user table. I decided that it is in my advantage to save it in the wpex_usermeta table. However, the problem is that I do not know how I can update the choice in the database. For now I am just using the word 'Jimbo'. The choices are saved in the variable $retrieved_data. But that contains all choices.

How can I make sure that when a user chooses something, his/her choice is updated in the database. The updating is already done. I just need to know how the choices are updated.

As you can see the word Jimbo in the meta_value (of user id 3) table is updated to Jimbo:

I have tried to use $retrieved_data in my update_user_meta like this:

update_user_meta( $user_id, 'meta_value', $retrieved_data );

After doing var_dump(get_error_last($retrieved_data)); the following was shown:

object(stdClass)#8135 (1) { ["Anaam"]=> string(12) "Uitwerkingen" }

The most recent uploaded choice was shown. It should show the option that is choicen.

How can I make sure the choices are updated in the meta_value table?

Table structure where the data is inserted:

Table structure where the data is retrieved:

Share Improve this question edited Mar 27, 2020 at 17:25 asked Mar 26, 2020 at 13:36 user183467user183467
Add a comment  | 

1 Answer 1

Reset to default 3

The main issue with your code is that the form submission will always have the same value. This could be seen by debugging $_POST where you check if $_POST['submit'] was set.

I set up a custom database table and added some dummy data. I think this more or less mirrors your setup.

Here is the code that creates the DB table and adds some sample data.

/**
 * Quick and dirty custom DB table and data creation.
 * Only creates the DB and data if the table does not yet exists.
 */
function wpse_create_custom_table_example() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'custom_table_test';
    $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );

    // Bail if the DB already exists.
    if ( $wpdb->get_var( $query ) === $table_name ) {
        return;
    }

    // Create table.
    $sql = "CREATE TABLE `{$table_name}` (
        ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        name varchar(20),
        PRIMARY KEY  (ID)
    ) {$wpdb->get_charset_collate()}";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );

    // Define dummy data. These are the NKOTB, btw.
    $names = [
        'Danny',
        'Donny',
        'Joe',
        'Jon',
        'Jordan',
    ];

    // Add dummy data.
    foreach ( $names as $name ) {
        $sql = $wpdb->prepare(
            "INSERT INTO `$table_name` (`name`) values (%s)",
            esc_sql( $name )
        );

        $wpdb->query($sql);
    }
}
add_action( 'init', 'wpse_create_custom_table_example' );

Here is the reworked code. Each submit button now contains the name pulled from the DB. The appropriate value will be saved to user meta when the user (who must be logged in, of course) clicks a button. I also added a nonce field and some other security measures. There's still room for improvement, but this Gets R Done.

/**
 * Output a form which lists Names from the `custom_table_test` table.
 * When clicking a name, the value of the name will be saved under
 * user meta for the current user using the key, `programma`.
 *
 * Each time a name is clicked, that value will replace the previous value.
 *
 * To use: Call this function from within the loop on the single post template.
 */
function wpse_update_user_meta_from_db() {
    if ( is_single() ) {
        global $wpdb;
        // This adds the prefix which is set by the user upon installation of WordPress.
        $table_name = $wpdb->prefix . 'custom_table_test';
        // This will get the data from your table.
        $retrieve_data = $wpdb->get_results( "SELECT `name` FROM {$table_name}" );
        //error_log( var_export( $retrieve_data, true ) );
        ?>
        <form action="#" enctype="multipart/form-data" method="post">
            <?php wp_nonce_field( 'set_programma_action', 'set_programma' ); ?>
            <table>
            <?php foreach ( $retrieve_data as $retrieved_data ) { ?>
                <tr>
                    <th>Programma:</th>
                    <td style="vertical-align: middle;"><?php echo esc_html( $retrieved_data->name ); ?></td>
                    <th>
                        <button name="programma" type="submit"
                            value="<?php echo esc_attr( $retrieved_data->name ); ?>">Abonneer</button>
                    </th>
                </tr>
            <?php } ?>
        </table>
    </form>

    <?php
        // Verify nonce and save data if the user is logged in.
        // Nonce docs: https://developer.wordpress/themes/theme-security/using-nonces/
        if (
            isset( $_POST['programma'] ) &&
            isset( $_POST['set_programma'] ) && wp_verify_nonce( $_POST['set_programma'], 'set_programma_action' )
        ) {
            $data            = filter_input( INPUT_POST, 'programma', FILTER_SANITIZE_STRING );
            $current_user_id = get_current_user_id();

            if ( $current_user_id && ! empty( $data ) ) {
                update_user_meta( $current_user_id, 'programma', $data );
            }
        }
    }
}

Add the functions above to your theme's functions.php or into a plugin. Call wpse_update_user_meta_from_db() inside your post/CPT single template.

Here's what it looks like in a Twenty Twenty child theme:

Here we can see that data from our custom table was saved under the current user's meta:

发布评论

评论列表(0)

  1. 暂无评论