Quantcast
Channel: Question and Answer » wpdb
Viewing all articles
Browse latest Browse all 44

Why Do I Still Getting Duplicate Rows in SQL?

$
0
0

I’m creating a Custom Freight System which stores the order and the products requested by the user into the WordPress Database.

The Problem

When I insert the product into the wp_my_custom_products table it works like a charm. I basically store the products data entered by the user via WordPress AJAX in a set of Cookies using the JavaScript Cookies Repository because that was the only way I could set a LIMIT number of Multi-Dimensinal Cookie Array (I don’t even know if I wrote it right), by the way, if anyone knows how to store dynamically Arrays in a $_COOKIE superglobal, it would’ve been more than welcome.

I get data from two forms the Destination and the Origin form and each of them has a separate AJAX Request, it’s something like this:

add_action( 'wp_ajax_origin', 'my_origin_function' );
add_action( 'wp_ajax_nopriv_origin', 'my_origin_function' );
function my_origin_function() {
    // Here I sanitize and validate properly the data entered and
    // set the cookies in a non-array format.
}

add_action( 'wp_enqueue_scripts', 'enqueuing_origin_scripts' );
function enqueuing_origin_scripts() {
    wp_enqueue_script( 'origin', get_template_directory_uri() . 'PATH/OF/THE/FILE', array( 'jquery' ) );
    wp_localize_script( 'origin', 'origin', array(
        'admin_ajax' => admin_url( 'admin-ajax.php' )
    ) );
}

The code above is the same for the Destination AJAX Request except (of course) that I’ve changed their respective name from Origin to Destination.

After setting up every single cookie in the Back-end, I have a button that when it’s clicked, it’ll create an Array of Cookies using the JavaScript Cookie Repository, it also looks something like this:

// this variable is responsible for making the cookies expire in about 5 minutes after it's creation
var date = new Date(); date.setTime( date.getTime() + ( 300 * 1000 ) );

// if index 0 of orders array do not exist, then it creates for me, and it keeps doing until the index reach 5
if ( Cookies.get( 'orders[0]' ) == null ) {
    Cookies.set( 'orders[0]', {
        distance: Cookies.get('api_distance'),
        duration: Cookies.get('api_duration'),
        destination: Cookies.get('api_destination'),
        origin: Cookies.get('api_origin'),
        price: Cookies.get('api_price')
    }, { expires: date } );
} else if ( Cookies.get( 'orders[1]' ) == null ) {
    Cookies.set( 'orders[1]', {
        distance: Cookies.get('api_distance'),
        duration: Cookies.get('api_duration'),
        destination: Cookies.get('api_destination'),
        origin: Cookies.get('api_origin'),
        price: Cookies.get('api_price')
    }, { expires: date } );
}

Unfortunately I had to define the LIMIT number of arrays (in this case five) manually, again, if anyone knows a better way, please it would’ve been more than welcome.

Alright, now that we’re getting the data properly (as I suppose), we need to store it into the WordPress Database. Here follows the code:

add_action( 'admin_init', 'store_data_to_database' );
function store_data_to_database() {
    global $wpdb;

    // get the current user information, it'll return 0 if it's a guess
    $username = get_userdata( get_current_user_id() );

    if ( isset( $_COOKIE[ 'orders' ] ) ) {
        $orders_table = $wpdb->prefix . 'my_custom_orders';
        $orders_table_rows = array(
            'id'               => $wpdb->get_results( $wpdb->prepare( 'SELECT id FROM ' . $orders_table . ' WHERE user_id = %s', $username->ID ) ),
            'user_id'          => $wpdb->get_results( $wpdb->prepare( 'SELECT user_id FROM ' . $orders_table . ' WHERE user_id = %s', $username->ID ) ),
            'user_name'        => $wpdb->get_results( $wpdb->prepare( 'SELECT user_name FROM ' . $orders_table . ' WHERE user_name = %s', $username->display_name ) ),
            'number_of_orders' => $wpdb->get_results( $wpdb->prepare( 'SELECT number_of_orders FROM ' . $orders_table . ' WHERE number_of_orders = %s', count( $_COOKIE[ 'orders' ] ) ) ),
            'timestamp'        => $wpdb->get_results( $wpdb->prepare( 'SELECT timestamp FROM ' . $orders_table . ' WHERE timestamp = %s', date( 'd/m/Y h:i:s a', time() ) ) )
        );

        foreach ( $_COOKIE[ 'orders' ] as $order ) {
            // JSON received from the JavaScript Cookies Repository
            $product_manipulated = json_decode( str_replace( '\', '', $order ), true );

            $products_table = $wpdb->prefix . 'my_custom_products';
            $products_table_rows = array(
                'origin'          => $wpdb->get_results( $wpdb->prepare( 'SELECT origin FROM ' . $products_table . ' WHERE origin = %s', $product_manipulated[ 'origin' ] ) ),
                'destination'     => $wpdb->get_results( $wpdb->prepare( 'SELECT destination FROM ' . $products_table . ' WHERE destination = %s', $product_manipulated[ 'destination' ] ) ),
                'distance'        => $wpdb->get_results( $wpdb->prepare( 'SELECT distance FROM ' . $products_table . ' WHERE distance = %s', $product_manipulated[ 'distance' ] ) ),
                'duration'        => $wpdb->get_results( $wpdb->prepare( 'SELECT duration FROM ' . $products_table . ' WHERE duration = %s', $product_manipulated[ 'duration' ] ) ),
                'price'           => $wpdb->get_results( $wpdb->prepare( 'SELECT price FROM ' . $products_table . ' WHERE price = %s', $product_manipulated[ 'price' ] ) ),
                'user_id'         => $wpdb->get_results( $wpdb->prepare( 'SELECT user_id FROM ' . $products_table . ' WHERE user_id = %s', $username->ID ) ),
                'user_name'       => $wpdb->get_results( $wpdb->prepare( 'SELECT user_name FROM ' . $products_table . ' WHERE user_name = %s', $username->display_name ) ),
                'timestamp'       => $wpdb->get_results( $wpdb->prepare( 'SELECT timestamp FROM ' . $products_table . ' WHERE timestamp = %s', date( 'd/m/Y h:i:s a', time() ) ) )
            );

            if ( ! empty( $product_manipulated[ 'origin' ] ) || ! empty( $product_manipulated[ 'destination' ] ) ) {
                $wpdb->insert( $order_table, array(
                    'origin'          => $order_manipulated[ 'origin' ],
                    'destination'     => $order_manipulated[ 'destination' ],
                    'distance'        => $order_manipulated[ 'distance' ],
                    'duration'        => $order_manipulated[ 'duration' ],
                    'price'           => $order_manipulated[ 'price' ],
                    'user_id'         => $username->ID,
                    'user_name'       => $username->display_name,
                    'timestamp'       => date( 'd/m/Y h:i:s a', time() ) )
                );
            } else {
                return false;
            }
        }

        // this will insert into the wp_my_custom_orders table
        if ( ! empty( $username->ID ) || ! $username->ID == 0 ) {
            $wpdb->insert( $wpdb->prefix . 'my_custom_orders', array(
                'user_name'        => $username->display_name,
                'user_id'          => $username->ID,
                'number_of_orders' => count( $_COOKIE[ 'orders' ] ),
                'timestamp'        => date( 'd/m/Y h:i:s a', time() ) )
            );
        }
    }

    $wpdb->flush();
}

This code is only triggered if the current user is logged in. I get that thanks to the admin_init action, the function storaging_data_to_database() is triggered every time that the user refreshes the page.

The thing is that I cannot stop inserting into the wp_my_custom_orders table, each time the user refreshes the page. Is there anyway for me to filter and delete duplicate insertions or even avoid it to happen?


Viewing all articles
Browse latest Browse all 44

Trending Articles