best way use db_select in Drupal 7 Tpl file? - drupal-7

Can any one suggest me how to write SQL query in .tpl file?
I tried to write db_select('node', 'n'); But it is not best way! and i tried write this in template.php but not work !
My code work well in tpl!
Please give me a solution to write sql query in tpl file
My Query :
$node = $variables['node'];
$author = user_load($node->uid);
$query = db_select('node', 'n')
->condition('n.uid', $author->uid, '=')
->condition('type', 'agahi');
$count_query = $query->countQuery()->execute()->fetchField();
print $count_query;

in your themes template.php file use preprocess functions for example for getting some data from mysql and passing to node.tpl
function ample_preprocess_node(&$variables) {
if( $variables['type'] == 'your_content_type_name') {
$queryresult = db_select('tablename', 'tn')
->fields('n')
->condition('field_name', 123,'=')
->execute()
->fetchAll();
foreach ($queryresult as $queryres) {
$your_variable_name = $queryres->table_col_name;
}
$variables['your-variable-name'] = $your_variable_name;
}
}
then in in your node--your_content_type_name.tpl.php
print $your_variable_name;

Related

CodeIgniter - displaying view based on variable from database

I've been learning codeigniter recently and trying to push an application out. im running into problems with the if else statements displaying views. i am trying to pull in_party from the databaseci_admin_info and display views depending if its set to 1 or 0. its bypassing any condition and just displaying the first view set.
Model
function get_in_par(){
$this->db->select('in_party');
$this->db->from('ci_admin_info');
$query = $this->db->get();
$ret = $query->row();
return $ret->in_party;
}
Controller
public function index(){
$data['title'] = 'Party';
$data['party'] = $this->party_model->get_party();
$data['prov'] = $this->party_model->get_prov_name();
$data['info'] = $this->party_model->get_all();
$data['res'] = $this->party_model->get_party_res();
$data['rank'] = $this->party_model->get_pa_rank();
$this->load->view('admin/includes/_header', $data);
$inpar = $this->party_model->get_in_par();
if(isset($inpar['in_party'])==0){
$this->load->view('admin/party/join');
} else {
$this->load->view('admin/party/index');
}
$this->load->view('admin/includes/_footer');
}
I've tried rearranging it into the parent construct as well and it just bypassed it completely. just trying to make it load the join view if in_party = 0 . i've tried without isset bypasses it as well. i've tried switch but don't think it registered that as well. i think i'm missing something in my model
$query = $this->db->select('*')
->from('ci_admin_info')
->get();
$result = $query->result_array();
return $result[0];
$inpar = $this->party_model->get_in_par();
if(!isset($inpar['in_party']) || $inpar['in_party']=="0"){....

How to Unserialize this data in wordpress

CURRENT ISSUE: I am making one plugin for listing users with there user role in WP_LIST_TABLE table.
This is my query
$this->items = $wpdb->get_results($wpdb->prepare("SELECT {$wpdb->users}.*, {$wpdb->usermeta}.meta_value as roles FROM {$wpdb->users}
LEFT JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID = {$wpdb- >usermeta}.user_id
WHERE {$wpdb->usermeta}.meta_key = '{$wpdb->get_blog_prefix()}capabilities'
ORDER BY {$wpdb->users}.display_name", $per_page, $paged), ARRAY_A);
It display out like This
[roles] => a:1:{s:13:"administrator";b:1;}
How to Unserialize this data. and I want to display the First name too using this query please help me
Finally this helps me.
$input = unserialize($item['roles']);
$result = array();
foreach($input as $key => $value){
$result[] = $key;
}
$userRole = implode(",", $result);
return $userRole;
Try below code:
foreach($this->items as $value){
echo $value->COLUMN_NAME ."<br>";
}
Please change the COLUMN_NAME to whichever column you want to display. If there's a column named e_name, then write "$value->e_name".
Its tried and tested. It works for me. Let me know if it works for you!

FAL insertion into sys_file TYPO3

I'm trying to insert a file into TYPO3 db through frontend using core functions or FileRepository, exactly into sys_file table.
While investigating I've seen few solutions like,
$storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
$storage = $storageRepository->findByUid(1);
$fileObject = $storage->addFile('/tmp/myfile', $storage->getRootLevelFolder(), 'newFile');
echo $fileObject->getIdentifier(); // Should output "/newFile"
But I still can't find this addFile() in storageRepository class. Am I missing some thing here?
The line $storageRepository->findByUid(1) return a ResourceStorage Object with the Method addFile().
Here is a Documenttion of this class.
https://typo3.org/api/typo3cms/class_t_y_p_o3_1_1_c_m_s_1_1_core_1_1_resource_1_1_resource_storage.html
#mario Thanks. By the way I've achieved what I planned. Here's what I did..
public function uploadFile($uploadedfile) {
$storage = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
$filePath = 'uploads/tx_fileupload/'.$uploadedfile['updata']['name'];
$title = $uploadedfile['updata']['name'];
$size = $uploadedfile['updata']['size'];
// Moving the physical file to destined folder
\TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($uploadedfile['updata']['tmp_name'],$filePath);
// Adding a record in sys_file_storage
$fileObject = $storage->createLocalStorage($uploadedfile['updata']['name'],$uploadedfile['updata']['tmp_name'],$filePath,'');
// Inserting file in sys_file
$repositoryFileObject = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->retrieveFileOrFolderObject($filePath);
return $repositoryFileObject;
}
Now moving onto adding corresponding sys_file_reference record.

cakephp pagination set condistion from array

I am using a form with several check boxes i need to display only those data which is in check box category.
How to write conditions for that.
for($i=0;$i<count($this->request->data['filter']['delivering']);$i++)
{
$opt1=".'Gig.bangsalsodeliverings' => ".$this->request->data['filter']['delivering'][$i];
$opt2=$opt2.$opt1.',';
}
$options=array('conditions' => array($opt2));
$this->Paginator->settings = $options;
$agetGigsItem = $this->Paginator->paginate('Gig');
But getting error.
Thanks in advance
It seems you're using a string contatenation instead of array to build the conditions array.
Also it's not clear to me if the filter delivering is a set of strings or integers.
I guess you can try:
// Merge the filters into a csv string
$filters = array();
foreach($this->request->data['filter']['delivering'] as $v){
$filters[] = "'{$v}'";
}
$csv_filters = implode(",", $filters);
// Use the csv to make a IN condition
$this->Paginator->settings = array('conditions' => array(
"Gig.bangsasodeliverings IN ({$csv_filters})",
));
Please note that sql injection can be made here, so prepare your data before creating $csv_filters.

Saving multiple rows in a single query

Is there anyway to have cake do a multi-row insert in a single query without writing raw SQL to do this? The saveMany and saveAssociated options will only save multiple rows in a single transaction, but that transaction contains multiple insert statements so these methods are clearly not a solution to write heavy applications.
Thanks for reading.
Yes
Though it's not a common practice to do so in app-land code, and doing so removes the possibility to use almost any application logic (validation rules, behaviors, events etc.). You can see an example of doing this in the way fixtures are loaded:
$db = ConnectionManager::getDataSource('default');
$table = "stuffs";
$fields = array('id', 'name');
$values = array(
array(1, 'one'),
array(2, 'two'),
...
);
$result = $db->insertMulti($table, $fields, $values);
You may also find this repository useful (either directly or as a basis for your code) which loads fixture files into your app database - using multi-inserts.
Yes, Big_Data is good idea for inserting bulk. But as AD7six note, it still use basic value quoting and does not return insert ids. And base on your ideas, i wrote small script to inserting bulk in a single query, using default CakePHP quoting and returning ids of inserted records.
$count = count($records);
$dbSource = $this->getDataSource();
$table = $dbSource->fullTableName($this->table);
$fields = $dbSource->prepareFields($this, array('fields' => array_keys($records[0])));
$values = array();
foreach ($records as $index => $record) {
if (!is_array($record) || !$record) {
return null;
}
foreach ($record as $column => $value) {
$values[$index][$column] = $dbSource->value($value, $this->getColumnType($column));
}
$values[$index] = '(' . implode(',', $values[$index]) . ')';
}
$query = 'INSERT INTO %s (%s) VALUES %s;';
$query = sprintf($query, $table, implode(',', $fields), implode(',', $values));
if (!$dbSource->execute($query)) {
return false;
}
$lastInsertId = $dbSource->getConnection()->lastInsertId();
$insertIds = array();
for ($i = 0; $i < $count; $i++) {
$insertIds[] = $lastInsertId + $i;
}
return $insertIds;
Someone pointed me towards the Big Data Behavior https://github.com/jmillerdesign/CakePHP_Big_Data
If you are using CakePHP 3.0 you can check the answer to this question: How to use insert in query builder insert multiple records?
If you are using CakePHP 2 you will have to use raw SQL like this:
$sql = "INSERT INTO `people` (`name`,`title`) VALUES ";
foreach($people as $person){
list($name,$title) = $person;
$sql.= "('$name','$title'),";
}
$this->query(substr($sql,0,-1));
Source: Inserting Multiple Rows with CakePHP 3
yes you can use like below
The getDataSource() method is static in CakePHP 2.x, so you should be able to use:
$db = ConnectionManager::getDataSource('default');
$db->rawQuery($some_sql);
here i am posting method to do. you have to create some SQL statement manually to insert multiple row in one time.
Please let me know if i can help you more.

Resources