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.
Related
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
I'm trying to write into a database table in a PHP script. This is my code:
$tablename = $wpdb->prefix.'test';
$wpdb->insert( $tablename, array(
'id' => DEFAULT,
'post_id' => $post_id,
'user_id' => $user_id,
array( '%s', '%s', '%s' )
));
After trying out my code I've got following error:
[29-Sep-2018 17:34:29 UTC] PHP Parse error: syntax error, unexpected 'DEFAULT' (T_DEFAULT) in C:\xampp\htdocs\wordpress\wp-content\themes\DiviChild\test.php on line 32
My table has a primary key "id" which should be autoincrement. I don't know what I'm doing wrong.
if "id" is set to be autoincrement then there is no need to include 'id'=>DEFAULT, while inserting record. It will be set automatically in your table when new record is inserted.
It seems there is mistake in argument.
$wpdb->insert takes 3 arguments and it seems you've included 3rd argument into 2nd argument.
$wpdb->insert( $tablename,
array(
'post_id' => $post_id,
'user_id' => $user_id
),
array( '%d', '%s' )
);
Removed id as it's autoincrement and modified formatting array assuming post_id to be numeric based on your comment.
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?
I dont know why is not inserting the values of the array in the db, I parse the array, but the values in the db are not changing, I manually add some data to the db table :
public function widget( $args, $instance ) {
global $wpdb;
$table_name = $wpdb->prefix . "cbrrate";
$limit=12;
$i=$x=0;
$currency = array();
$codes = array('USD','EUR');
//creando la tabla
if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name)
{
$sql = 'CREATE TABLE ' .$table_name . '(
hit_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
code CHAR(3),
rate FLOAT UNSIGNED,
PRIMARY KEY (code) )';
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
//initialise an array to hold the values to be inserted
$sqlParts1=array();
//loop through the code to create an array with keys as value
foreach($codes as $code){
//add the rate to the sql query
$sqlParts1[] = "('$code', ".((float)$currency[0][$code]).") ";
}
$sql = "INSERT INTO $table_name (code, rate) VALUES ".implode(', ', $sqlParts1).' ON DUPLICATE KEY UPDATE rate = VALUES(rate)';
print_r($sql);
the array $currency is:
Array (
[0] => Array ( [USD] => 73.63 [EUR] => 79.97 )
[1] => Array ( [USD] => 74.05 [EUR] => 80.53 )
)
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'
)
);
}