How to use prepared statements in Joomla? - joomla

How to use Prepare methods in joomla model?
for example in pdo we use :
db->prepare('INSERT INTO tbl (`city`,`date`,`uid`,`title`) VALUES(:city,:date,:uid,:title)');
How can I do it in the Joomla!

In Joomla, you always stick to the API which caters for the supported database types, like so:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$columns = array('city', 'date', 'uid', 'title');
$values = array($db->quote('value1'), $db->quote('value2'), $db->quote('value3'), $db->quote('value4'));
// Prepare the insert query.
$query
->insert($db->quoteName('#__tablename')) //make sure you keep #__
->columns($db->quoteName($columns))
->values(implode(',', $values));
$db->setQuery($query);
$db->query();
and for Joomla 3.x, you can replace $db->query(); with $db->execute();
Update:
As far as I know, Joomla 4 will use prepared statements in core. Here is a something I've mocked up, however have not tested:
use Joomla\CMS\Factory;
use Joomla\Database\ParameterType;
$db = Factory::getDbo();
// Your data
$city = $db->quote('London');
$date = $db->quote('21/01/2020');
$uid = $db->quote(1234);
$title = $db->quote('My Title');
// Prepared query
$query = $db->getQuery(true)
->insert($db->quoteName('#__tablename'))
->columns([
$db->quoteName('city'),
$db->quoteName('date'),
$db->quoteName('uid'),
$db->quoteName('title'),
])
->values(':city, :date, :uid, :title')
->bind(':city', $city, ParameterType::STRING)
->bind(':date', $date)
->bind(':uid', $uid, ParameterType::INTEGER)
->bind(':title', $title, ParameterType::STRING);
$db->setQuery($query);
$db->execute();

Related

magento catalog search not working

I have to make custom catalog search. For this I have made a file in /var/www/magento/customsearch.php and put following code:
$searchText = 'test';
$query = Mage::getModel('catalogsearch/query')->setQueryText($searchText)->prepare();
$fulltextResource = Mage::getResourceModel('catalogsearch/fulltext')->prepareResult(
Mage::getModel('catalogsearch/fulltext'),
$searchText,
$query
);
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->getSelect()->joinInner(
array('search_result' => $collection->getTable('catalogsearch/result')),
$collection->getConnection()->quoteInto(
'search_result.product_id=e.entity_id AND search_result.query_id=?',
$query->getId()
)
);
print_r($collection->getData());
But the collection returns blank array.It update catalogsearch query table each time but not update catalogsearch result table. Please help.
I put your same code on my Magento website:
<?php
include "app/Mage.php";
Mage::app();
$searchText = 'test';
$query = Mage::getModel('catalogsearch/query')->setQueryText($searchText)->prepare();
$fulltextResource = Mage::getResourceModel('catalogsearch/fulltext')->prepareResult(
Mage::getModel('catalogsearch/fulltext'),
$searchText,
$query
);
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->getSelect()->joinInner(
array('search_result' => $collection->getTable('catalogsearch/result')),
$collection->getConnection()->quoteInto(
'search_result.product_id=e.entity_id AND search_result.query_id=?',
$query->getId()
)
);
print_r($collection->getData());
And got an array with three of my products. So I guess, check your setup? You have products right? With the keyword 'test' some where in the attribute values?

Using JFactory::getDbo()->insertObject with on duplicate key update

How to use:
JFactory::getDbo()->insertObject('#__card_bonus', $object);
with on duplicate key update ?
You have a few options:
1) Check for an entity id. This is my preferred option, because it only uses a single query, is reusable for any object, and is database agnostic - meaning it will work on whichever DBMS you choose, whereas the other two options are exclusive to MySQL.
if (isset($object->id)) {
$db->updateObject('#__card_bonus', $object);
}
else {
$db->insertObject('#__card_bonus', $object, 'id');
}
I often create an abstract model with a save(stdClass $object) method that does this check so I don't have to duplicate it.
2) Write your own query using the MySQL ON DUPLICATE KEY UPDATE syntax, which is a proprietary extension to the SQL standard, that you have demonstrated understanding of.
3) Write your own query using MySQL's proprietary REPLACE INTO extension.
<?php
$jarticle = new stdClass();
$jarticle->id = 1544;
$jarticle->title = 'New article';
$jarticle->alias = JFilterOutput::stringURLSafe($jarticle->title);
$jarticle->introtext = '<p>re</p>';
$jarticle->state = 1;
$jarticle->catid = 13;
$jarticle->created_by = 111;
$jarticle->access = 1;
$jarticle->language = '*';
$db = JFactory::getDbo();
try {
$query = $db->getQuery(true);
$result = JFactory::getDbo()->insertObject('#__content', $jarticle);
}
catch (Exception $e){
$result = JFactory::getDbo()->updateObject('#__content', $jarticle, 'id');
}
I use this method - are not fully satisfied, but ...
or for not object method:
$query = $db->getQuery(true);
$columns = array('username', 'password');
$values = array($db->quote($username), $db->quote($password));
$query
->insert($db->quoteName('#__db_name'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$query .= ' ON DUPLICATE KEY UPDATE ' . $db->quoteName('password') . ' = ' . $db->quote($password);
$db->setQuery($query);
JFactory::getDbo()->insertObject('#__card_bonus', $object, $keyName);
The name of the primary key. If provided the object property is updated.
Joomla doc ...

How to get parameters in JFormField from a disabled plugin in Joomla 1.6/2.5?

How i can get some parameters from a disabled/not yet actived plugin in joomla 1.6/2.5?
$module = JPluginHelper::getPlugin('system','myplugin');
$moduleParams = new JParameter($module->params);
$val = $moduleParams->get("key");
This method didn't work becouse i need to use within an element JFormField generator.
Thanks for help!
With JPluginHelper::getPlugin it's possible to access only enabled plugins, so here's the code for direct access to database.
// Build query
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select( 'params' )
->from( '#__extensions' )
->where( 'type = ' . $db->q('plugin') )
->where( 'folder = ' . $db->q('authentication') ) // Plugin type
->where( 'element = ' . $db->q('gmail') ) // Plugin element
;
// Execute query
$db->setQuery($query);
try
{
$result = $db->loadResult();
}
catch (RuntimeException $e)
{
return false;
}
// Parse parameters
if (!empty($result))
{
$params = new JRegistry($result);
$val = $params->get('key', 'defaultValue');
}
You may store query results in in the JFormField Object so save database queries in case field is availabile multiple times.
protected $results = null;
Perhaps you may want to try this:
// Get plugin parameters
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('`params`')
->from ('`#__extensions`')
->where ("`type` = 'plugin'")
->where ("`folder` = 'system'")
->where ("`element` = 'myplugin'");
$db->setQuery($query);
$res = json_decode($db->loadResult(), true);
$val = $res['key'];
Just find the answer by myself.
$data = null;
foreach ((array) $this->form as $k => $v) {
if($val instanceof JRegistry){
$data = &$v;
break;
}
}
$data = $data->toArray();
$val = $data['params']['key'];
Thanks! Bye!

Joomla 2.5 database $query->where warning

I have this simple code to select custom string from database:
protected function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from('#__person');
$name = 'tom';
$query->where('name LIKE %'.$db->quote($name).'%');
return $query;
}
Unfortunately it gives me an error:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean
given in xxx\public\libraries\joomla\database\database\mysql.php on
line 293
If I remove where call, so everything goes ok. Can I debug the datase query? I would like to see whats the final query goes to MySQL server.
Your help would be appreciated.
I've managed to work this for me:
protected function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from('#__person');
$name = 'tom';
$name = $db->Quote('%'.$db->escape($name, true).'%');
$query->where($db->nameQuote('name').' LIKE '.$name);
//debug the query
// echo nl2br(str_replace('#__','prefix_',$query)); die;
return $query;
}

How to Get User Group Names in Joomla 2.5

I'm writing a Joomla 2.5 component that I had been developing in Joomla 1.7. I have been using code like this:
$user = JFactory::getUser();
$groups = $user->get('groups');
The $groups array would contain a list of ids with the group name as the index. Joomla 2.5 seems to have scrapped this functionality. I have been unable to find out how to get the group names without directly querying the database. Is there any method for getting a list of the groups a user is a member of without having to resort to querying the database?
The code I generated below gets the names of all the groups the user is a part of and stores them in the variable $groupNames separated by line breaks:
foreach ($user->groups as $groupId => $value){
$db = JFactory::getDbo();
$db->setQuery(
'SELECT `title`' .
' FROM `#__usergroups`' .
' WHERE `id` = '. (int) $groupId
);
$groupNames .= $db->loadResult();
$groupNames .= '<br/>';
}
print $groupNames;
It technically queries the database but is done via the Joomla API. This is working well for me on Joomla 2.5.
Yes, this changed.
But what you should be using instead is:
JFactory::getUser()->getAuthorisedGroups();
or just getUserGroups
Real snippet:
$user = JFactory::getUser();
$db = JFactory::getDBO();
$db->setQuery($db->getQuery(true)
->select('*')
->from("#__usergroups")
);
$groups=$db->loadRowList();
$userGroups = $user->groups;
$return=array();
foreach ($groups as $key=>$g){
if (array_key_exists($g[0],$userGroups)) array_push($return,$g[4]);
}
$groups=$return;
/////printing groupnames for current user/////////////
print_r($groups);
Here it is:
<?php
$user =& JFactory::getUser();
foreach ($user->groups as $key => $value){
echo $key.'<br>';
}
?>
This will print all the user group names to the screen. The user group names are the "keys" of the array $user->groups.

Resources