mysql is not inserting to custom database table wordpress - mysql
I have a function that creates a custom database table in wordpress and insert data from csv file.
The function work as expected. but the problem is if i add 'join_date ' =>$name . Then it will create the datatable with all defined table columns, but won't insert anything from the csv file.
this is the error i am getting from debugging
[09-Oct-2020 11:50:07 UTC] WordPress database error Unknown column 'join_date ' in 'field list' for query INSERT INTO `wp_lubuvna_subscribers` (`first_name`, `last_name`, `email`, `phone`, `birthday`, `gender`, `customer_type`, `id_company_number`, `street_address`, `address_line_2`, `city`, `state_area`, `zip`, `customer_from`, `groups`, `last_visit`, `send_sms`, `send_email`, `join_date `) VALUES ('John', 'Doe', '532223334', 'info#desingash33r543.com', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John') made by do_action('wp_ajax_new_subscriber_batch'), WP_Hook->do_action, WP_Hook->apply_filters, maybe_insert_new_subscriber_batch_database_table
[09-Oct-2020 11:50:07 UTC] WordPress database error Unknown column 'join_date ' in 'field list' for query INSERT INTO `wp_lubuvna_subscribers` (`first_name`, `last_name`, `email`, `phone`, `birthday`, `gender`, `customer_type`, `id_company_number`, `street_address`, `address_line_2`, `city`, `state_area`, `zip`, `customer_from`, `groups`, `last_visit`, `send_sms`, `send_email`, `join_date `) VALUES ('John', 'Doe', '532223334', 'info#desingash33r543.com', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John', 'John') made by do_action('wp_ajax_new_subscriber_batch'), WP_Hook->do_action, WP_Hook->apply_filters, maybe_insert_new_subscriber_batch_database_table
[09-Oct-2020 11:50:09 UTC] WordPress database error Unknown column 'username' in 'where clause' for query SELECT count(*) as count FROM wp_lubuvna_subscribers where username='Melin' made by do_action('wp_ajax_new_subscriber_batch'), WP_Hook->do_action, WP_Hook->apply_filters, maybe_insert_new_subscriber_batch_database_table
[09-Oct-2020 11:50:09 UTC] PHP Notice: Undefined offset: 0 in /Applications/MAMP/htdocs/nl/wp-content/plugins/lubuvna-newsletter/inc/options/shortcodes/submit-subscriber-batch.php on line 535
[09-Oct-2020 11:50:09 UTC] PHP Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/nl/wp-content/plugins/lubuvna-newsletter/inc/options/shortcodes/submit-subscriber-batch.php on line 535
[09-Oct-2020 11:50:09 UTC] WordPress database error Unknown column 'join_date ' in 'field list' for query INSERT INTO `wp_lubuvna_subscribers` (`first_name`, `last_name`, `email`, `phone`, `birthday`, `gender`, `customer_type`, `id_company_number`, `street_address`, `address_line_2`, `city`, `state_area`, `zip`, `customer_from`, `groups`, `last_visit`, `send_sms`, `send_email`, `join_date `) VALUES ('Edward', 'Melin', '543214321', 'infef#dsignash343.com', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward') made by do_action('wp_ajax_new_subscriber_batch'), WP_Hook->do_action, WP_Hook->apply_filters, maybe_insert_new_subscriber_batch_database_table
[09-Oct-2020 11:50:09 UTC] WordPress database error Unknown column 'join_date ' in 'field list' for query INSERT INTO `wp_lubuvna_subscribers` (`first_name`, `last_name`, `email`, `phone`, `birthday`, `gender`, `customer_type`, `id_company_number`, `street_address`, `address_line_2`, `city`, `state_area`, `zip`, `customer_from`, `groups`, `last_visit`, `send_sms`, `send_email`, `join_date `) VALUES ('Edward', 'Melin', '543214321', 'infef#dsignash343.com', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward', 'Edward') made by do_action('wp_ajax_new_subscriber_batch'), WP_Hook->do_action, WP_Hook->apply_filters, maybe_insert_new_subscriber_batch_database_table
the error on line 535 is this : if($record[0]->count==0){
The Function
function maybe_insert_new_subscriber_batch_database_table() {
// get entered form data
parse_str( $_POST['form_data'], $form_data );
$postarr = array();
// merge all array and make new array, now get data for each input like following: $form_data[LUBUVNA_PREFIX.'from']
$postarr = array_merge( $postarr, $form_data );
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
//$version = (int) get_site_option( 'lubivna-newsletter' );
$table_name = $wpdb->prefix . "lubuvna_subscribers";
if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
$sql = "DROP TABLE IF EXISTS $table_name";
//if ( $version < 1 ) {
$sql = "CREATE TABLE `{$wpdb->base_prefix}lubuvna_subscribers` (
ID bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
phone varchar(255),
birthday varchar(255),
gender varchar(255),
customer_type varchar(255),
id_company_number varchar(255),
street_address varchar(255),
address_line_2 varchar(255),
city varchar(255),
state_area varchar(255),
zip varchar(255),
customer_from varchar(255),
groups varchar(255),
last_visit varchar(255),
send_sms varchar(255),
send_email varchar(255),
join_date varchar(255),
post_author varchar(255),
post_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
post_status varchar(20),
PRIMARY KEY (ID)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
$success = empty( $wpdb->last_error );
//update_site_option( 'captcorecore_db_version', 1 );
//}
} else {
//$sql = "DROP TABLE IF EXISTS $table_name";
}
$tablename = $wpdb->prefix."lubuvna_subscribers";
$csvFile = fopen(get_option(LUBUVNA_PREFIX.'file_url'), 'r');
fgetcsv($csvFile); // Skipping header row
// Read file
while(($csvData = fgetcsv($csvFile)) !== FALSE){
$csvData = array_map("utf8_encode", $csvData);
// Row column length
$dataLen = count($csvData);
// Skip row if length != 4
//if( !($dataLen == 4) ) continue;
// Assign value to variables
$name = trim($csvData[0]);
$username = trim($csvData[1]);
$email = trim($csvData[2]);
$age = trim($csvData[3]);
// Check record already exists or not
$cntSQL = "SELECT count(*) as count FROM {$tablename} where username='".$username."'";
$record = $wpdb->get_results($cntSQL, OBJECT);
if($record[0]->count==0){
// Check if variable is empty or not
if(!empty($name) && !empty($username) && !empty($email) && !empty($age) ) {
// Insert Record
$wpdb->insert($tablename, array(
'first_name' =>$name,
'last_name' =>$username,
'email' =>$email,
'phone' => $age,
'birthday' => $name,
'gender' => $name,
'customer_type' => $name,
'id_company_number' => $name,
'street_address' => $name,
'address_line_2' => $name,
'city' => $name,
'state_area' => $name,
'zip' => $name,
'customer_from' => $name,
'groups' => $name,
'last_visit' => $name,
'send_sms' => $name,
'send_email' => $name,
'join_date ' =>$name
));
if($wpdb->insert_id > 0){
$totalInserted++;
}
}
}
$wpErrors = $wpdb->print_error();
$wpHideErrors = $wpdb->hide_errors();
$email = 'enabled';
if( $email == 'enabled'){
$headers = [
'MIME-Version: 1.0',
'From: myemailfrom#mail.com',
'Content-Type: text/html; charset=UTF-8',
];
$headers = implode("\r\n", $headers);
wp_mail('myemailto#hotmail.com','WP Errors',print_r($wpErrors) . $wpHideErrors . '<br><br><br>hide Errors<br>' . print_r($wpHideErrors) ,$headers);
}
}
}
add_action( 'wp_ajax_new_subscriber_batch', 'maybe_insert_new_subscriber_batch_database_table' );
Once i remove 'join_date ' =>$name from the array. it works just fine. I think am really missing something in there or there is any limitation in MySQL? i am new to this.
You have space in some linesin the at the end of the
fieldname between the ticks like this:
'join_date ' =>$name
change to:
'join_date' =>$name
Related
How to check if record was changed on db after inserting data?
I insert some data from a db.table1 to db.table2 with a cronjob which runs every minutes. But I need to check if any record has changed after data is inserted on table2 because I get some wrong data on this table when data is inserted. this is crontab function $data = DB::connection('mysql2') ->table('students') ->where('status', '=', 'Y') ->get(); foreach ($data as $key => $aStudent) { // Check if student_id duplicated $existing_data_in = DB::table('student') ->where("student_id", $aStudent->student_id) ->first(); if (! $existing_data_in) { DB::connection('mysql')->table('student')->insert([ "first_name" =>$aStudent->first_name, "last_name" =>$aStudent->last_name, "age" =>$aStudent->age, "student_id" =>$aStudent->student_id, "created_at" =>$aStudent->created_at ]); } } Log::info('Success, Data Updated'); Or maybe should I run cronjob rarely? My problem is when some record on table1 are filed with data and when this record goes to table2 are empty on table2. If I check same student_id on table1 is okay but on table2 are saved empty i have loged my query on cronjob and this is what i get in case i find an empty filed on table 2. So last name on table 1 in this case is filled with really last name but on table 2 is inserted as empty and this is query (what hapend) [2022-01-19 14:16:17] local.INFO: select `student_id` `first_name`, `last_name`, `age`, `created_at` from `students` where `student_id` = ? limit 1 [421] // this comes from query where i check for dublicated lines i think [2022-01-19 14:16:17] local.INFO: select * from `student` where `student_id` = ? limit 1 [421] [2022-01-19 14:16:17] local.INFO: insert into `student` (`student_id`, `first_name`, `last_name`, `age`, `created_at`) values (?, ?, ?, ?, ?) ["421","name","","38","2022-01-19 14:13:35"]
If the tables contain created_at and updated_at columns, you can tell if a record has been updated by comparing the two columns. ->whereRaw('created_at != updated_at')->get();
You could wrap everything in a transaction to make sure it works as it should. $data = DB::connection('mysql2') ->table('students') ->where('status', '=', 'Y') ->get(); $dataToInsert = $data->map(function ($item) { return [ 'first_name' => $item->first_name, 'last_name' => $item->last_name, 'age' => $item->age, 'student_id' => $item->student_id, 'created_at' => $item->created_at ]; })->all(); $columnsToCheck = ['student_id']; $columnsToUpdate = []; $conn = DB::connection('mysql'); $conn->beginTransaction(); try { $conn->table('student')->upsert($dataToInsert, $columnsToCheck, $columnsToUpdate); $conn->commit(); Log::info('Success'); } catch (\Exception $e) { $conn->rollBack(); Log::error($e); } I'm using upsert. You can read more about it here. https://laravel.com/docs/8.x/queries#upserts
Node mysql ER_PARSE_ERROR 1064
I am inserting a row into table like this but its not working i searched on internet and tried all solutions for no luck for me i don't know what i am doing wrong here var b = req.body; mysqlConnection.query( 'INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES ?', [[ b.nid, b.name, b.dob, b.gender ]], (error, results) => { if(!error) res.status(201).send(result.insertId); else res.send(error) } ); Error "code": "ER_PARSE_ERROR", "errno": 1064, "sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '123, 'Alex', '2020-10-30', 'male' at line 1", "sqlState": "42000", "index": 0, "sql": "INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES 123, 'Alex', '2020-10-30', 'male'" }
There is a missing parenthesis just after VALUES, try this mysqlConnection.query( 'INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES (?)', [[ b.nid, b.name, b.dob, b.gender ]], (error, results) => { if(!error) res.status(201).send(result.insertId); else res.send(error) } );
[You can see attached image and do something like that. I think you are doing bulk insert. var b = req.body; mysqlConnection.query( INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES ?', b.map(item => (item.nid, item.name, item.dob, item.gender)), (error, results) => { if(!error) res.status(201).send(result.insertId); else res.send(error) } ] Attached Image:1 And if you are not doing bulk insert then do something like below: mysqlConnection.query('INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES (?,?,?,?)',[b.nid,b.name,b.dob,b.gender], (error, results) => { if(!error) res.status(201).send(result.insertId); else res.send(error) }
Codeigniter database backup - Insert multiple rows without repeating “INSERT INTO”
I'm trying out to find a way to backup my database using Codeigniter "Database Utility" but without repeating “INSERT INTO”, I mean everything works perfectly, but when we see the generated sql file we see something like this: INSERT INTO Membership (ID, FirstName, LastName, DOB) VALUES (1, 'John', 'Smith', '5/5/1960') INSERT INTO Membership (ID, FirstName, LastName, DOB) VALUES (2, 'Hello", 'World", '4/9/1975') INSERT INTO Account(ID, Type, Effective_Date, Status) VALUES (1, 'Gold', GetDate(), 'Active') INSERT INTO Account(ID, Type, Effective_Date, Status) VALUES (2, 'Platinum', GetDate(), 'Inactive') INSERT INTO Participant(ID, Code, Type) VALUES (1, 002, 'A') INSERT INTO Participant(ID, Code, Type) VALUES (2, 002, 'A') The which is so slow whenever we import in another database. I want to get something like this: INSERT INTO #temp_table (1, 'John', 'Smith, '5/5/1960', 'Gold', 'Active', '002', 'A') . . . . so on using only one INSERT INTO, is there any way to achieve this? Thanks.
You can make use of CodeIgniter insert_batch() function Follow this link here to see how it works:
Create a multi-dimensional array with field and values like this, and use codeigniter inset_batch() function to insert all these in a single query. $data = array( array( 'ID' => 1, 'FirstName' => 'John', 'LastName' => 'Doe', 'DOB' => '5/5/1960' ), array( 'ID' => 2, 'FirstName' => 'John', 'LastName' => 'Smith', 'DOB' => '5/5/1960' ) ); $this->db->insert_batch('temp_table', $data);
I understand your problem, Database Utility is quite slow also, due to string concatenation, if passthru() is enabled on your server, then mysqldump can be used, here is working code, which will export current database. public function backup_current_db() { $db_user=$this->db->username; $password=$this->db->password; $db=$this->db->database; $filename = $db . "-" . date("Y-m-d_H-i-s") . ".sql"; $mime = "application/octet-stream"; header( "Content-Type: " . $mime ); header( 'Content-Disposition: attachment; filename="' . $filename . '"' ); $cmd = "mysqldump -u '$db_user' --password='$password' --no-create-info --complete-insert '$db' "; passthru( $cmd ); die(); }
wordpress wpdb update difficulties
Suppose I have a table in my wp database fruits: CREATE TABLE `fruits` ( `fruit` varchar(99), `istasty` tinyint(1) ) INSERT INTO `fruits` (`fruit`, `istasty`) VALUES ('pear', 1), ('peach', 1), ('rotten strawberry', 1), ('strawberry', 1), ('banana', 1), ('apple', 1); the goal is to update istasty to 0 in the 'rotten strawberry' row. the class reference for wpdb in the wordpress codex gives: $wpdb->update( $table, $data, $where, $format = null, $where_format = null ); so I've attempted the following: $wpdb->update( 'fruits', array( 'fruit' => 'rotten strawberry', 'istasty' => '0' ), array( 'fruit' => 'rotten strawberry' ), array( '%s', // value1 '%d' // value2 ), array( '%d' ) ); Apparently this updates EVERY record to 'rotten strawberry', '1'. What am I doing wrong here?
Try changing up that last array from array( '%d' ) into array( '%s' ). You are now telling the script that the where variable is an integer, which it is not. Also you could remove 'fruit' => 'rotten strawberry' from your first array. In this array you place whatever you want to update. And all you want to do is set istasty to 0.
Merge multiple insert queries into one
Is it possible to simplify the following code using only one insert query? if(isset($_POST['colore'])) { $range = array_keys($_POST['colore']); foreach ($range as $key) { $colore = $_POST['colore'][$key]; $s = $_POST['S'][$key]; $m = $_POST['M'][$key]; $l = $_POST['L'][$key]; $xl = $_POST['XL'][$key]; $xxl = $_POST['XXL'][$key]; $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) VALUES ('$last_id', '$colore', 's', '$s')"; $query = mysql_query($sql) or die(mysql_error()); $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) VALUES ('$last_id', '$colore', 'm', '$m')"; $query = mysql_query($sql) or die(mysql_error()); $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) VALUES ('$last_id', '$colore', 'l', '$l')"; $query = mysql_query($sql) or die(mysql_error()); $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) VALUES ('$last_id', '$colore', 'xl', '$xl')"; $query = mysql_query($sql) or die(mysql_error()); $sql = "INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) VALUES ('$last_id', '$colore', 'xxl', '$xxl')"; $query = mysql_query($sql) or die(mysql_error()); } }
You can rewrite it like this: $colore = mysql_real_escape_string($_POST['colore'][$key]); $s = mysql_real_escape_string($_POST['S'][$key]); $m = mysql_real_escape_string($_POST['M'][$key]); $l = mysql_real_escape_string($_POST['L'][$key]); $xl = mysql_real_escape_string($_POST['XL'][$key]); $xxl = mysql_real_escape_string($_POST['XXL'][$key]); $sql = " INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) VALUES ('$last_id', '$colore', 's', '$s'), ('$last_id', '$colore', 'm', '$m'), ('$last_id', '$colore', 'l', '$l'), ('$last_id', '$colore', 'xl', '$xl'), ('$last_id', '$colore', 'xxl', '$xxl')"; $query = mysql_query($sql) or die(mysql_error()); Important: Make sure to mysql_real_escape_string() all your values used in the query! And while you're on this, better switch to MySQLi or PDO, because the use of the mysql extension is discouraged.
You can try : INSERT INTO store_product_attributes (`prod_id`, `color`, `size`, `qty`) VALUES ('$last_id', '$colore', 's', '$s'), ('$last_id', '$colore', 'm', '$m'), ('$last_id', '$colore', 'l', '$l'), ('$last_id', '$colore', 'xl', '$xl'), ('$last_id', '$colore', 'xxl', '$xxl'); But your code is dangerous. SQL injection is very easy with that code, you should learn more about security (type on google : "owasp" or "sql injection")
If I get the point right, it should be possible to insert multible values with this schema: INSERT INTO table (field1, field2, ...) VALUES (...), (...)