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
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();
}
I know I am doing this completely wrong, but current I have:
$genre0 = addslashes(strip_tags($movieInfo[genres][0][name]));
$genreid0 = addslashes(strip_tags($movieInfo[genres][0][id]));
...
$genre4 = addslashes(strip_tags($movieInfo[genres][4][name]));
$genreid4 = addslashes(strip_tags($movieInfo[genres][4][id]));
Then
mysql_query($query = "INSERT INTO tblMovies (movie_id, genre_id, genre_name) VALUES ($movie_id , $genreid0, $genre0");
...
mysql_query($query = "INSERT INTO tblMovies (movie_id, genre_id, genre_name) VALUES ($movie_id , $genreid4, $genre4");
I know this is extremely repetitive, but it is the only way I can figure out that works. I have tried a ton of for each statements to no avail. I have tried following this one insert multiple rows via a php array into mysql and a few others, but cannot seem to figure it out.
This is embedded in a SELECT/WHILE statement that runs through a list of movies...
Any tips or suggestions would be greatly appreciated!
Thanks!
You can use prepared statements for handy execution of your query:
$stmt = $dbh->prepare("INSERT INTO tblMovies (movie_id, genre_id, genre_name)
VALUES (:movie_id , :genreid, :genre")");
$stmt->bindParam(':movie_id ', $movie_id);
$stmt->bindParam(':genreid', $genreid);
$stmt->bindParam(':genre', $genre);
for($i=0; $i < count($movieInfo['genres']); $i++){
$movie_id = i;
$genreid = addslashes(strip_tags($movieInfo['genres'][i]['id']));
$genre = addslashes(strip_tags($movieInfo['genres'][i]['name']));
$stmt->execute();
}
If you insist on using mysql_XXX:
foreach ($movieInfo['genres'] as $genre) {
$genre = mysql_real_escape_string(strip_tags($genre['name']));
$genreid = mysql_real_escape_string(strip_tags($genre['id']));
mysql_query("INSERT INTO tblMovies (movie_id, genre_id, genre_name) VALUES ($movie_id , '$genreid', '$genre'");
}
I would insist that insert multiple records in database by firing single query instead of firing seperate query for each record.
E.g.:
INSERT INTO tblMovies
(genre_id, genre_name)
VALUES
('Name 1', 'Value 1'),
('Name 2', 'Value 2'),
('Name 3', 'Value 3'),
('Name 4', 'Value 4');
//Prepare the entire query using foreach and then fire single query.
foreach ($movieInfo['genres'] as $genre) {
$genre = mysql_real_escape_string(strip_tags($genre['name']));
$genreid = mysql_real_escape_string(strip_tags($genre['id']));
$parts[] = "('.$genreid.', '.$genre.')";
}
$str = implode("," $parts);
$query = "INSERT INTO tblMovies (genre_id, genre_name) VALUES ".$str.";";
mysql_query($query) or die(mysql_error());
Note: I have used mysql as you have mentioned in question but it is recommended to switch to mysqli or PDO. Also, from the question you have mentioned, I assume that $movie_id is auto-increment.
I have a table of checkboxes and values, if a user selects a checkbox they select the value of the id in an array called checkedHW for simplicity sake this is what code looks like:
$ids = implode(',',arrayofids);
$sql = "insert into table(id, type) values($ids,type);
$db->query($sql);
echo query for testing:
"insert into table('id1,id2','type')
I figured that if I loop through this query I could hypothetically do this:
"insert into table('id1','type');"
"insert into table('id2','type');"
but I'm not exactly quite sure how to do, any help would be wonderful :)
I actually solved it using:
for($i=0;$i<count(arrayofids); $i++){
$sql = "insert into table(id,type) values(array[$i], 'type'";
$db->query($sql);}
I hope that helps someone and thank you guys for the help!
You could do something like this:
$base = 'INSERT INTO table (id, type) VALUES (';
$array = array(1, 2, 3, 4);
$values = implode(", 'type'), (", $array);
$query = $base . $values . ", 'type')";
$db->query($query);
This is what would be getting submitted:
INSERT INTO table (id, type) VALUES (1, 'type'), (2, 'type'), (3, 'type'), (4, 'type')
Both query are completely different
insert into table('id1,id2','type') will insert single row
id1,id2 | type
whereas
insert into table('id1','type');"
insert into table('id2','type');"
will insert two rows
id1 | type
id2 | type
so if your id column is int type then you cant run first query
If you have a series of checkboxes, and wanting to insert the values into your table, you could loop through them like this:
<?php
$values = array();
foreach ($_POST['field_name'] as $i => $value) {
$values[] = sprintf('(%d)', $value);
}
$values = implode(',', $values);
$sql = "INSERT INTO `table_name` (`column_name`) VALUES $values";
This will give you a SQL query similar to:
INSERT INTO `table_name` (`column_name`) VALUES (1),(2),(3),(4)
Hope this help.
$body = $_POST['post'];
$submit = $_POST['submit'];
$date = date("Y-m-d");
require('php/connect.php');
if($submit)
{
$query = mysql_query("INSERT INTO news (`id`, `body`, `date`) VALUES (NULL, '".$body."', '".$date."')");
header("Location: index.php");
}
I do not understand why this isn't working, I took the query straight from PHP my admin after writing a line simular myself before hand and it still isn't working, can someone hep?
you definitely should escape your input values using mysql_real_escape_string
With mysql_error you can print out an error message but you need the connection identifier as a parameter.
I just suggest to handle mysql error
$query = mysql_query("INSERT INTO news (`id`, `body`, `date`) VALUES (NULL, '".$body."', '".$date."')")
or trigger_error(mysql_error());
and if id is primary key that can not be null
you should escape user input using mysql_real_escape_string function.
What happen if I put "that's it " value in your $body input, your query will fail.
Comment out your header("Location: index.php"); and append or die(mysql_error()); at the end of your query code that will show you what went wrong. You should also "mysql_real_escape_string" your user input before inserting it into your database.
$body = mysql_real_escape_string($_POST['post']);
$submit = $_POST['submit'];
$date = date("Y-m-d");
require('php/connect.php');
if($submit)
{
$query = mysql_query("INSERT INTO news (`id`, `body`, `date`) VALUES (NULL, '$body', '$date')") or die(mysql_error());
//header("Location: index.php");
}