I have class with function, which prepares SQL statement to put data into database, but there's an error I can not figure it out, why is happening?
public function vnos_narocila($user) //, $hvrsta_narocila, $hlastna_nabava, $hos, $hsm_dn, $hoe, $hartikel1, $hkolicina_artikel1, $hem1, $hartikel2, $hkolicina_artikel2, $hem2, $hartikel3, $hkolicina_artikel3, $hem3, $hartikel4, $hkolicina_artikel4, $hem4, $hartikel5, $hkolicina_artikel5, $hem5, $hartikel6, $hkolicina_artikel6, $hem6, $hartikel7, $hkolicina_artikel7, $hem7, $hartikel8, $hkolicina_artikel8, $hem8, $hartikel9, $hkolicina_artikel9, $hem9, $hartikel10, $hkolicina_artikel10, $hem10, $hprevzemnik, $hopomba, $hzeljen_datum)
{
$sql = "SELECT * FROM nabava ORDER BY id_nabava DESC LIMIT 1"; //pridobitev zaporedne številke v letu
if( !$this->stmt = $this->mysqli->prepare($sql) )
throw new Exception("MySQL Prepare statement failed: ".$this->mysqli->error);
$this->stmt->execute();
$zadnji_zapis = $this->stmt->get_result();
$zadnji_zapis = $zadnji_zapis-> fetch_array();
$leto = date('Y');
if ( !$zadnji_zapis or $zadnji_zapis[leto] != $leto)
$zap_st=1;
else
$zap_st = $zadnji_zapis[zap_st]+1;
$narocilo = "N-".$zap_st."-".$hoe."/".$leto; //kreiranje številke naročila
$sql_vnos = "INSERT INTO nabava (vrsta_narocila, lastna_dobava, os, sm_dn, prevzemnik, opomba, zeljen_datum_dobave, narocilo, uporabnik, datum_vnosa, zap_st, oe, leto) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ? )";
if( !$this->stmt = $this->mysqli->prepare($sql_vnos) )
throw new Exception("MySQL Prepare statement failed: ".$this->mysqli->error);
$this->stmt->bind_param("iiisssisiiii", $hvrsta_narocila, $hlastna_dobava, $hos, $hsm_dn, $hprevzemnik, $hopomba, $hzeljen_datum, $narocilo, $user, $zap_st, $hoe, $leto );
if( $this->stmt->execute() )
return $this->stmt->insert_id;
return $narocilo;
}
Here is the error:
Fatal error: Uncaught Exception: MySQL Prepare statement failed: in
/var/www/html/intra_komunalaBrezice/skripte/nabava.php:111 Stack
trace: #0 /var/www/html/intra_komunalaBrezice/nabava_vnos.php(27):
nabava->vnos_narocila(1, '1', '1', '1', '200401', '1005', '1', '1',
'1', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', 'test', 'test',
'2018-07-04') #1 {main} thrown in
/var/www/html/intra_komunalaBrezice/skripte/nabava.php on line 111
Please help...
There was a mistake in number of columns and number of values passed.
I'm sorry, I should see that.
Related
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 having problems getting Joomla to insert escaped data
Query is:
INSERT INTO #__shopper_orders (id, ordering, state, checked_out, checked_out_time, created_by, modified_by, order_paypal_ref, order_details, fulfillment_status, order_gift, terms_conditions) VALUES (NULL, '', '', '', '', '', '', '', '$newBody', '', '', '');
$newBody is
$newBody = $db->quote( $emailText );
$db->query();
the $emailText is
<h2>Website Order</h2><p>Thank you for your order. We've included a copy of it below.</p>
it throws the error as
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'you for your order. We\\'ve included a copy of it below.<\/p>\\r\\n<p>Quantiti' at line 3"
It seems to be escaping the already escaped ' character?
Any ideas?
thanks
Thought I'd add an update.
I saw nibra below and so tried his code but it didn't work. However I have code that works that looks really similar.
I like the way nibra does the code so I'd like to get it to work. So I've included both the working code and his code (commented out)
//Insert into orders table
$newBody = $db->quote( $body );
$db->query();
$db = JFactory::getDbo();
$query ="
INSERT INTO `#__shopper_orders`
(`id`, `ordering`, `state`, `checked_out`, `checked_out_time`, `created_by`, `modified_by`, `order_paypal_ref`, `order_details`, `fulfillment_status`, `order_gift`, `terms_conditions`)
VALUES (NULL, '', '1', '', '', '', '', '', $newBody, '1', '', '')
";
$db->setQuery($query);
$db->query();
$insertId = $db->insertid();
/* $values = [
'id' => null,
'ordering' => '',
'state' => '1',
'checked_out' => '',
'checked_out_time' => '',
'created_by' => '',
'modified_by' => '',
'order_paypal_ref' => '',
'order_details' => $db->quote($body),
'fulfillment_status' => '1',
'order_gift' => '',
'terms_conditions' => '',
];
$query = $db->getQuery(true);
$query
->insert('#__shopper_orders')
->columns(array_keys($values))
->values(implode(',', $values))
;
$db->setQuery($query);
$result = $db->execute();
$insertId = $db->insertid();*/
First, you should use the QueryBuilder instead of literal SQL. Users of your component might use other RDBMS than MySQL.
Second, JDatabaseDriver::quote is adding the quotes, by default it also escapes the string. Thus quoting $newBody additionally, breaks the SQL.
<?php
$db = \Joomla\CMS\Factory::getDbo();
$values = [
'id' => null,
'ordering' => '',
'state' => '',
'checked_out' => '',
'checked_out_time' => '',
'created_by' => '',
'modified_by' => '',
'order_paypal_ref' => '',
'order_details' => $db->quote($emailText),
'fulfillment_status' => '',
'order_gift' => '',
'terms_conditions' => '',
];
$query = $db->getQuery(true);
$query
->insert('#__shopper_orders')
->columns(array_keys($values))
->values(implode(',', $values))
;
$db->setQuery($query);
$result = $db->execute();
#nibra apporach is good. Below is the same one with a little modification, $db->quote also accepts array.
<?php
$db = \Joomla\CMS\Factory::getDbo();
$values = [
'id' => null,
'ordering' => '',
'state' => '',
'checked_out' => '',
'checked_out_time' => '',
'created_by' => '',
'modified_by' => '',
'order_paypal_ref' => '',
'order_details' => $emailText,
'fulfillment_status' => '',
'order_gift' => '',
'terms_conditions' => '',
];
$query = $db->getQuery(true);
$query
->insert('#__shopper_orders')
->columns(array_keys($values))
->values(implode(',', $db->quote(array_values($values))))
;
$db->setQuery($query);
$result = $db->execute();
I used wamp server to browse the database , I started connection with database from nodejs express server
When I wrote insert query there is no error but when I browse the table the added row has empty values .
this is my query code
app.post('/new_sess_mouse',function(req,res ){
var sess_name = req.body.sess_name ,
sess_id = req.session.id ,
email = req.session.email ;
var sql = "INSERT INTO ?? SET ?? = ? AND ?? = ? AND ?? = ? ";
var inserts = ['sessions', 'sess_name' , sess_name ,'sess_id',sess_id ,'email' , email ];
sql = mysql.format(sql, inserts);
console.log(sql);
connection.query( sql , function( err , results ){
if(err) {
console.log(err.message);
}
else {
//connection.destroy();
console.log('succes');
}
}); });
When I printout the results
{ fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 3,
message: '',
protocol41: true,
changedRows: 0 }
You have wrong INSERT statement format.
You can :
var sql = "INSERT INTO ?? ( ??, ??, ??) VALUES (?, ?, ?)";
var inserts = ['sessions', 'sess_name' , 'sess_id', 'email', sess_name , sess_id , email ];
or:
var sql = "INSERT INTO ?? SET ?? = ? , ?? = ? , ?? = ? ";
var inserts = ['sessions', 'sess_name' , sess_name ,'sess_id',sess_id ,'email' , email ];
How do I transform this
DB::table('partners')->insert(array($data));
laravel Query to have ON DUPLICATE KEY UPDATE
the structure look like
$data['program_name'] = $program['program']['_'];
$data['program_id'] = $program_id;
$data['status'] = $program['status'];
$data['shop_name'] = $shop->name;
$data['shop_logo'] = $shop->image;
$data['shop_description'] = $shop->description;
where program_id is unique
Use something like this (feel free to correct because it's untested):
DB::statement( 'INSERT INTO partners VALUES (' . implode( ',',
array_map( function( $val ) { return ":$val"; } , array_keys($data) )
) . ') ON DUPLICATE KEY UPDATE ' . implode( ',',
array_map( function( $val ) { return "$val = VALUES($val)"; } , array_keys($data) )
), $data);
I created a package that will wrapped INSERT ON DUPLICATE KEY UPDATE
https://packagist.org/packages/yadakhov/insert-on-duplicate-key
$users = [
['id' => 1, 'email' => 'user1#email.com', 'name' => 'User One'],
['id' => 2, 'email' => 'user2#email.com', 'name' => 'User Two'],
['id' => 3, 'email' => 'user3#email.com', 'name' => 'User Three'],
];
User::insertOnDuplicateKey($users);
// produces:
INSERT INTO `test_user_table`(`id`,`email`,`name`) VALUES
(1,'user1#email.com','User One'), (2,'user3#email.com','User Two'), (3,'user3email.com','User Three')
ON DUPLICATE KEY UPDATE `id` = VALUES(`id`), `email` = VALUES(`email`), `name` = VALUES(`name`)
Novice here. Just trying to bind values to eliminate sql injections. I've got the code below but I get this error...
called with 1 bind variables when 47 are needed at my.cgi line 803.
and output looks like..
$new_row='53616c7465645f5fd8b88f6a16704f8ebc0a2002dfg45633617bbb0446fa', 'test12', 'user', '2012-03-06', 'xcvb', 'xb', 'xcvbb', 'xcvbb', 'UT', 'US', '4566', '4564564566', 'todd#my.com', 'vbn', '', '200', 'Monthly', 'eBook', 'WebStore', '9.95', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'http://my.com', 'my.com', '', '', '', '', '', '', '', '', '2012-03-06', '30-Day-Trial'
$questionmarks=?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
I've tried it with/without quotes and commas. Any ideas appreciated.
foreach my $field (#account_field_order) {
$new_row .= "'" . param($field) . "', ";
$questionmarks .="?, ";
}#foreach
$new_row .= "'$status'";
$questionmarks .= "? ";
my $dsn = "DBI:mysql:$database";
my $dbh = DBI->connect($dsn, $MYSQLuserid, $MYSQLpassword )
or die $DBI::errstr;
my $sth = $dbh->prepare(qq(INSERT INTO $table VALUES ($questionmarks) ))
or die $DBI::errstr;
$sth->execute(qq($new_row)) or die $DBI::errstr;
You're supposed to supply a list of arguments, one for each questionmark, not a single scalar argument that contains the strings of the arguments. When I answered your question before, I told you to do:
my #values = map param($_), #account_field_order; # add values to array
push #values, $status; # for simplicity
$new_row = join ", ", ("?") x #values; # add ? for each value
... # basically same code as before, except the execute statement:
$sth->execute(#values); # arguments given will be inserted at placeholders
Where $new_row is your placeholder string, not your argument list. Not:
$new_row .= "'" . param($field) . "', ";
...
$new_row .= "'$status'";
$sth->execute(qq($new_row)) or die $DBI::errstr;
Because $new_row counts as one argument, since it is a scalar. You need an array or list of the same length as the number of questionmarks.
First, lets fix the first statements:
#new_row=('53616c7465645f5fd8b88f6a16704f8ebc0a2002dfg45633617bbb0446fa', 'test12', 'user', '2012-03-06', 'xcvb', 'xb', 'xcvbb', 'xcvbb', 'UT', 'US', '4566', '4564564566', 'todd#my.com', 'vbn', '', '200', 'Monthly', 'eBook', 'WebStore', '9.95', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'http://my.com', 'my.com', '', '', '', '', '', '', '', '', '2012-03-06', '30-Day-Trial');
$questionmarks="?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?";
These will create an array of values and a single string with all the ?s.
Then in the execute statement:
$sth->execute(#new_row) or die $DBI::errstr;
which will pass in your array of values into the execute line, rather than a single argument like you were doing before.