Handling duplicate keys in wordpress database - php

I'm want to write a function that saves a user data array to a custom table in my wp database. I have this working with this function.
function insert_player($playerArray){
global $wpdb;
$table_name = $wpdb->prefix . "hots_logs_plugin";
$wpdb->insert(
$table_name,
array(
'name' => $playerArray['name'],
'player_id' => $playerArray['pid'],
'hl_mmr' => $playerArray['heroLeague'],
'qm_mmr' => $playerArray['quickMatch'],
'comb_hero_level' => $playerArray['combLevel'],
'total_games_played' => $playerArray['totalGames']
)
);
}
Now I want to extend this function so that if a duplicate player_id is sent the function updates the all the cells in the row apart from the name and player_id. The player_id is a UNIQUE KEY.
I have come up with this function, which I can't seem to get to work, and to be honest is a little over my head..
function input($playerArray){
global $wpdb;
$table_name = $wpdb->prefix . "hots_logs_plugin";
$sql = "INSERT INTO $table_name(player_id, name, hl_mmr, qm_mmr, comb_hero_level, total_games_played)
VALUES(%d,%s,%s,%s,%s,%s)
ON DUPLICATE KEY UPDATE(hl_mmr = %s, qm_mmr = %s, comb_hero_level = %s, total_games_played = %s)";
$sql = $wpdb->prepare(
$playerArray['pid'],
$playerArray['name'],
$playerArray['heroLeague'],
$playerArray['quickMatch'],
$playerArray['combLevel'],
$playerArray['totalGames']
);
$wpdb->query($sql);
}
I just need a nudge in the right direction.

OK, so I was really over doing it in my first attempt. The answer is actually really easy.
I just modified the original method to use $wpdb->replace() rather than $wpdb->insert()
The following method works great.
function insert_player($playerArray){
global $wpdb;
$table_name = $wpdb->prefix . "hots_logs_plugin";
$wpdb->replace(
$table_name,
array(
'player_id' => $playerArray['pid'],
'name' => $playerArray['name'],
'hl_mmr' => $playerArray['heroLeague'],
'qm_mmr' => $playerArray['quickMatch'],
'comb_hero_level' => $playerArray['combLevel'],
'total_games_played' => $playerArray['totalGames']
),
array (
'%d',
'%s',
'%s',
'%s',
'%s',
'%s'
)
);
}

Related

How to add nested data into MySQL tables using PHP

I have 3 tables and I'm working with wordpress too: wp7s_g_bookings, wp7s_g_tests and wp7s_g_clients. This is a study project, not to sell.
I want to be able to save 1 booking with X clients and Y tests.
I read about LAST_INSERT_ID() but I don't think it will work in this case and I'm lost.
Possible scenarios:
You are a partner, then the data is beeing pulled, so we have the ID because it exist already;
In this case we are adding other users data inside repeatable fields like name="client_birth[]" ... // client_vat only show/exist if the partner don't exist.
You are a normal client, in this case you fill the same client data plus client_vat (so I'm sure when adding into database that only the guy that have client_vat is the booking_client)
if (!empty($_POST)) {
$wpdb->query('START TRANSACTION');
//All this fields are repeatable inputs, except client_vat that can only be the 1st record. I think it's missing a foreach
$default = array(
'client_name' => $_POST['client_name'],
'client_birth' => $_POST['client_birth'],
'client_sns' => $_POST['client_sns'],
'client_vat' => $_POST['client_vat'],
'client_city' => $_POST['client_city'],
'client_email' => $_POST['client_email'],
'client_phone' => $_POST['client_phone']
);
$item = shortcode_atts( $default, $_REQUEST );
$addClients = $wpdb->insert( 'wp7s_g_clients', $item );
$default = array(
'test_client' => ???, //ID of previous client that have client_vat filled [0]
);
$item = shortcode_atts( $default, $_REQUEST );
$addTests = $wpdb->insert( 'wp7s_g_tests', $item );
$collectDate = date('Y-m-d H:i:s', strtotime($_POST['booking_collect_date']));
$default = array(
'booking_status' => 1,
'booking_partner' => $_POST['booking_partner'], //ID of the partner, if not empty
'booking_client' => ???, //If partner don't exist -> ID of client that have client_vat filled
'booking_type' => $_POST['booking_type'],
'booking_clients' => ???, //Array of all IDs previously added in wp7s_g_clients table
'booking_city' => $_POST['booking_city'],
'booking_address' => $_POST['booking_address'],
'booking_collect_date' => $collectDate,
'booking_payment' => $_POST['booking_payment'],
'booking_amount' => $_POST['booking_amount'],
'booking_obs' => nl2br($_POST['booking_obs']),
);
$item = shortcode_atts( $default, $_REQUEST );
$addBookings = $wpdb->insert( 'wp7s_g_bookings', $item );
if($addClients && $addTests && $addBookings) {
$wpdb->query('COMMIT');
$msg = "Success";
wp_redirect( esc_url( get_page_link( 6 ) ) );
exit;
}
else {
$wpdb->query('ROLLBACK');
$msg = "Error";
}
}
My issues are adding this properly into database the repeatable fields and using a previous created ID(s).
I tried to explain everything and comment so it's better to understand.
After you perform a query with $wpdb you can access the $wpdb->insert_id to get the last inserted id. You can find more details on the documentation page of wpdb
If you need more ids because u have more $wpdb->insert all you need to do is store $wpdb->insert_id after each insert, like:
...
$item = shortcode_atts( $default, $_REQUEST );
$addClients = $wpdb->insert( 'wp7s_g_clients', $item );
$clientId = $wpdb->insert_id;
....
$default = array(
'test_client' => ???, //ID of previous client that have client_vat filled [0]
);
$item = shortcode_atts( $default, $_REQUEST );
$addTests = $wpdb->insert( 'wp7s_g_tests', $item );
$testId = $wpdb->insert_id;
...
rest of your code

get_users() when meta_key has multiple serialized values

I can't seem to find any information online, but what I am trying to do is to get an array of all users based on a value in a serialised meta_key, for example:
$get_users = get_users(array(
'meta_key' => 'value_one_of_array'
));
Then in the db, the meta_value columns would have two stored values such as:
meta_key
value_one_of_array , value_two_of_array
Is this possible?
May be it's help you.
$args = array();
if($values_of_array){
foreach($values_of_array as $key=>$val){
$args['meta_query'][] = array(
'key' => '#your_meta_key',
'value' => $val
);
}
$get_users = get_users($args);
}

Wordpress update query not working

I have an update query which is not working for me. I am able to make selects quite happily on the same page but I cannot get an update statement to work.
The table is not a part of wordpress so Im wondering if that could be it or if I have just got something wrong.
$query = "UPDATE login_count SET `count` = '100' WHERE `user_id` = $userID ";
$insrt = $wpdb->query($query);
Try this,
$insrt = $wpdb->update(
'login_count', //table_name
array('count'=>'100'),//data
array('user_id'=>$userID),//where
array('%s'),//data format
array('%s')
);
$insrt = $wpdb->update(
'login_count', //table_name
array(
'count' => '100', // string
),
array( 'user_id' => $user_id ), //Where Condition
array(
'%d', // value1
),
array( '%d' )
);
Try this ..user_id = {$userID} ";
Edit
See: Use a $variable inside a SQL string?

Wordpress plugin table not being created

I'm creating a wordpress plugin for woocommerce and the table i've created is not being inserted into the database? I get the error The plugin generated 5090 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
Here is the code:
register_activation_hook( __FILE__, 'pato_install' );
register_activation_hook( __FILE__, 'pato_install_data' );
function pato_install() {
global $wpdb;
$table_name = $wpdb->prefix . 'pato_shipping';
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
pato_shipping_data text NOT NULL,
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
function pato_install_data() {
global $wpdb;
$table_name = $wpdb->prefix . 'pato_shipping';
//shipping options flat rate charges
$option_array = array(
'plants_fast' => '45.5',
'plants_standard' => '0');
//shipping condition values
$condition_array = array(
'plant_quantity_m1_1' => '3',
'plant_quantity_m1_2' => '6',
'plant_quantity_m2_1' => '6',
'plant_quantity_m3_1' => '3');
//shipping item charges
$item_charge_array = array(
'plants_ml_1_charge' => '49.5',
'plants_m2_1_charge' => '69.5',
'plants_m3_1_charge' => '89.5');
$data_array = array_merge($option_array,$condition_array,$item_charge_array);
$data_array = serialize($data_array);
$wpdb->insert(
$table_name,
array('pato_shipping_data' => $data_array)
);
}
Where did i go wrong?
You have some errors in your create table query. Your auto increment column needs to be a key and you have an extra trailing comma after your second column. Try:
CREATE TABLE $table (
id mediumint(9) NOT NULL PRIMARY KEY AUTO_INCREMENT,
pato_shipping_data text NOT NULL
)
I usually try to run my queries directly before incorporating them into a plugin. It makes debugging a lot easier.

wpdb->query prepare doesn't work

I followed the introduction to use prepare to insert some data to the table.
The code is like this:
$wpdb->query(
$wpdb->prepare(
"INSERT INTO {$wpdb->prefix}awpcp_adphotos VALUES
(ad_id, image_name, disabled, isprimary)
(%d, %s, %d,%d)",
$ad_id,
$ad_img,
0,
0));
Also, disabled and is_primary should be Boolean. But I am not sure what the data type in here.
I also tried
$wpdb->insert(
'{$wpdb->prefix}awpcp_adphotos', // Table name
array(
'ad_id' => $ad_id,
'image_name' => $ad_img,
'disabled' => 0,
'is_primary' => 0,
), // Columns
array(
'%s',
'%d',
'%d',
'%d'
) // Explicit formatting
);
But haven't got any luck yet.
Shouldn't it be (?) :
$wpdb->query(
$wpdb->prepare(
"INSERT INTO {$wpdb->prefix}awpcp_adphotos(`ad_id`, `image_name`, `disabled`, `isprimary`)
VALUES(%d, %s, %d,%d)",
$ad_id, $ad_img, 0, 0)
);
I think you wrote the entire thing wrong, maybe by mistake :)
For your edit, if using insert() should be like:
$wpdb->insert($wpdb->prefix.'awpcp_adphotos', array(
'ad_id' => $ad_id,
'image_name' => $image_name,
'disabled' => $disabled,
'isprimary' => $isprimary,
));

Categories