joomla escape text for inserrt - mysql

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();

Related

MySQL: Prepare statement failed

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.

Custom template order by id issue

I'm trying to sort post by ID in ASC order, I'm able to do that when I use single query but when use array query I'm unbale to sort post by ID in ASC order my code looks like below
<?php
$ourCurrentPage = get_query_var('paged');
$newposts = new WP_Query(array(
'category_name' => 'stock-market-basics',
'orderby' => 'ID',
'order' => 'ASC',
'paged' => $ourCurrentPage
));
?>
<?php
if ($newposts->have_posts()):
while ($newposts->have_posts()):
$newposts->the_post();
?>
// Some display code and after closing code //
<?php endwhile; else : ?>
<p><?php esc_html_e( 'Sorry, no results matched your criteria.' ); ?</p>
<?php endif; ?>
<li><?php
echo paginate_links(array(
'total' => $newposts->max_num_pages
));
?></li>
WordPress query by category name
<?php $args = array(
'posts_per_page' => 5,
'offset' => 0,
'category' => '',
'category_name' => '',
'orderby' => 'date',
'order' => 'DESC',
'include' => '',
'exclude' => '',
'meta_key' => '',
'meta_value' => '',
'post_type' => 'post',
'post_mime_type' => '',
'post_parent' => '',
'author' => '',
'author_name' => '',
'post_status' => 'publish',
'suppress_filters' => true
);
$posts_array = get_posts( $args ); ?>
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();
// Contents of the queried post results go here.
}
}
Hope this works for you.

cakephp hasmany query on same class

i am using this binding
$this->Company->bindModel( array(
'hasMany' => array(
'CompanyContactPerson'=>array('conditions' => array('Company.name Like'=>'%'.$a.'%'),),
),
'belongsTo' => array(
'Status',
'User'
)
));
$this->paginate = array(
'limit' =>20,
'conditions'=>$conditions,
'order' =>array('Company.id'=> 'desc') ,
);
$all_companies = $this->paginate('Company');
It give this query as a result.
SELECT `Company`.`id`, `Company`.`user_id`, `Company`.`name`, `Company`.`status_id`, `Company`.`email`, `Company`.`modified`, `Company`.`created`, `Status`.`id`, `Status`.`name`, `User`.`id`, `User`.`roll`, `User`.`username`, `User`.`email`, `User`.`password`, `User`.`first_name`, `User`.`last_name`, `User`.`gender`, `User`.`address`, `User`.`city`, `User`.`state`, `User`.`country`, `User`.`modified`, `User`.`created`
FROM `companyinfo`.`companies` AS `Company`
LEFT JOIN `companyinfo`.`statuses` AS `Status` ON (`Company`.`status_id` = `Status`.`id`)
LEFT JOIN `companyinfo`.`users` AS `User` ON (`Company`.`user_id` = `User`.`id`)
WHERE 1 = 1 ORDER BY `Company`.`id` desc LIMIT 20
it make seperate query for CompanyContactPerson model. so as a result i got all result from Company table. I need only those rows from company table where CompanyContactPerson conditions is satisfied . how i achieved this
put this in your Company model so it can have a relationship. :)
public $hasMany = array(
'CompanyContactPerson' => array(
'className' => 'CompanyContactPerson',
'foreignKey' => 'ForeignKeyinCompanyContactPerson',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => '',
'dependent' => true
)
));
or put this to your CompanyContactPerson Model
public $belongsTo = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'ForeignKeyofCompanyContactPersonTABLE',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Use limit in Query
'limit' => 2, //int
So only two rows will be returned.
Your code should be like
'CompanyContactPerson'=>array('conditions' =>
array('Company.name Like'=>'%'.$a.'%'),
'limit' => 2
),

ON DUPLICATE KEY UPDATE Query in Laravel4

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`)

Retrieving Data From two tables that are associated with a forign key in CakePhp

I have two tables named login and userDetail
Login
login_id
uname
pswd
userdetail_id
and
userdetails
userdetail_id
name
address
email
the login table contain userdetails_id in the userDetail table. i want to get all data from Login table and userDetail table and save it to a variable
if anyone knows, please answer me......
First of all your table structure must be as below.
logins Table.
Id auto_increment
username
password
userDetails Table.
Id auto_increment
user_id
name
address
etc...
Now model for each table would be.
Login
<?php
class Login extends AppModel
{
var $name = 'User';
var $hasMany = array
(
'UserDetail' => array
(
'className' => 'UserDetail',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
}
?>
UserDetail
<?php
class UserDetail extends AppModel
{
var $name = 'UserDetail';
var $belongsTo = array
(
'User' => array
(
'className' => 'User',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => ''
)
}
?>
And finally in controller where you need to fetch login detail.
$login_detail = $this->Login->find('all');
You will see userDetail table records in resulting $login_detail.
use pr($login_detail); in controller to see it in action.
Cheers.
Feel Free to ask.
Make sure ContainableBehavior has been enabled. After that you can use following query:
$login = $this->Login->find('first', array(
'contain' => array(
'Userdetail.userdetail_id'
'Userdetail.name',
'Userdetail.address',
'Userdetail.email'
),
'fields' => array(
'Login.login_id'
'Login.uname',
'Login.pswd'
),
'conditions' => array(
'Login.login_id' => 1
)
));
The query for this task would be:
SELECT Login.*, name,address,email
FROM Login JOIN userdetails
ON Login.userdetail_id=userdetails.userdetail_id
The results of this query could be saved to variables by looping in cakephp.