I want to execute this query in a foreach loop to use the table in the elemant orWhere Requette (depending on the number of array elements).
foreach ( $mesDeparts as $mesDepart)
{
$holidays_rh_test = holidaystate::find()
->leftJoin('holidays', '`holidays`.`id` = `holidayState`.`holiday_id`')
->leftJoin('user', '`user`.`id` = `holidays`.`user_id`')
->leftJoin('space_membership', '`user`.`id` = `space_membership`.`user_id`')
// ->where(['holidayState.user_id'=>0, 'holidayState.user_position_id'=>0, 'holidayState.stat'=>'2'])
->where(['space_membership.space_id'=>$mesDepart->space_id])
->andFilterWhere(['or',['holidayState.user_id'=>Yii::$app->user->id,'holidayState.user_position_id'=>$user_position->id ],['holidayState.user_id'=>0, 'holidayState.user_position_id'=>0, 'holidayState.stat'=>'2']])
->orderBy('holiday_id DESC')
->all();
}
You are repeating the query
You should build an array and use in clause
foreach ( $mesDeparts as $key =>$mesDepart) {
$my_array[$key] = $mesDepart->space_id;
}
$holidays_rh_test = holidaystate::find()
->leftJoin('holidays', '`holidays`.`id` = `holidayState`.`holiday_id`')
->leftJoin('user', '`user`.`id` = `holidays`.`user_id`')
->leftJoin('space_membership', '`user`.`id` = `space_membership`.`user_id`')
->andFiilterWhere(['in', 'space_membership.space_id', $my_array])
->orderBy('holiday_id DESC')
->all();
Related
I am currently working on a project (A music website) with PHP Codeigniter. I want to fetch top 15 songs by number of downloads. To my knowledge, I got all unique ID's out ranging from highest to least. But now, I want to use each of these unique ID's to fetch data from another table in the database.
I have tried using for loop; but it seems to only return one of the rows which happens to be the first and highest number of occurrence in the array. The code below echo's the ID's but how can I use each of those ID's to fetch data.
function top15(){
$this->db->select('musiccode');
$result=$this->db->get('downloads');
$query = $result->result_array();
$downloads = array();
if(!empty($query)) {
foreach($query as $row)
{
$musiccode[] = $row['musiccode'];
}
$mode = array_count_values($musiccode);
arsort($mode);
$i = 0;
foreach ($mode as $field => $number) {
$i++;
echo $field." occured ". $number." times <br>";
if ($i == 15) {
break;
}
}
}
}
for ($b=0; $b < count($field); $b++) {
$this->db->where(array('track_musiccode'=> $field));
$field = $this->db->get('tracks');
return $field->result_array();
}
The code above only produce one row for me. I expect to have more than one and according to the number of ID's in the array. Thanks in advance.
For a single column condition, you could use where_in() instead and drop the for loop :
$this->db->where_in('track_musiccode', $field);
$field = $this->db->get('tracks');
return $field->result_array();
Yes Finally i did it. Incase if anyone needs it. this works just fine
function top15(){
$this->db->where('d_month', date('m'));
$this->db->select('musiccode');
$result=$this->db->get('downloads');
$query = $result->result_array();
$downloads = array();
if(!empty($query)) {
foreach($query as $row){
$musiccode[] = $row['musiccode'];
}
$res='';
$count=array_count_values($musiccode);
arsort($count);
$keys=array_keys($count);
for ($i=0; $i < count($keys); $i++) {
$res[] .= "$keys[$i]";
}
$this->db->where_in('track_musiccode', $res);
return $this->db->get('tracks')->result_array();
}
}
And I got this too. If I wasn't going to count occurrences but just iterate the number of downloads which is far more better than counting in other not to over populate the database and make your website work slowly.
function top15(){
$tracks = '';
$this->db->group_by('counter');
$result=$this->db->get('downloads');
$query = $result->result_array();
$counter = '';
$fields = '';
if(!empty($query)) {
foreach($query as $row) {
$counter[] = $row['counter'];
}
rsort($counter);
for ($i=0; $i<=15; $i++) {
$this->db->where('downloads.counter', $counter[$i]);
$this->db->join('tracks', 'tracks.musicid = downloads.musicid');
$fields[] = $this->db->get('downloads')->row_array();
}
return $fields;
}
}
Enjoy...
Hi,
I am getting an array for string conversion when using the code below:
$sort_order = array();
foreach (getAll() as $field) {
$sort_order[$field->name] = query("SELECT sort_order
FROM field_table
WHERE field_name = '$field->name'");
$o->tag[$field->name] = $field->title. $sort_order[$field->name];
}
The error says there is an Array to string conversion in line 6. Why is that?
Thank you.
query will return an array, so you need to do something like:
$result = query("SELECT sort_order
FROM field_table
WHERE field_name = '$field->name'");
$row = $result->fetch_assoc();
sort_order[$field->name] = $row['sort_order'];
Yes because the query returns an array, which is directly assigned to the variable. Please try this :
$sort_order = array();
foreach (getAll() as $field) {
$result = query("SELECT sort_order
FROM field_table
WHERE field_name = '$field->name'");
while($res = $result->fetch_array()) {
$sort_order = $res['sort_order'];
}
$o->tag[$field->name] = $field->title.$sort_order;
}
I'm trying to save data in CakePHP in this way:
get max entry_id from table translations
(SELECT MAX(entry_id) as res FROM translations) + 1
save data into translations table
$translationData = array('entry_id' => $entry_id, 'language_id' => $key, 'text' => $item);
$translation = new Translation();
$translation->set($translationData);
$translation->save();
again get max entry_id
save next set of data
again get max entry_id
save next set of data
Please have a look at my code:
$this->request->data['Product']['name_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['name']);
$this->request->data['Product']['description_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['description']);
$this->request->data['Product']['seo_title_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_title']);
$this->request->data['Product']['seo_keywords_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_keywords']);
$this->request->data['Product']['seo_desc_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_desc']);
saveTranslations method:
public function saveTranslations($data) {
$entry_id = $this->getNextFreeId();
foreach($data as $key => $item) {
if($item != "") {
$this->create();
$temp['Translation']['entry_id'] = $entry_id;
$temp['Translation']['language_id'] = $key;
$temp['Translation']['text'] = $item;
$this->save($temp);
}
}
return $entry_id;
}
getNextFreeId method:
public function getNextFreeId() {
$result = $this->query("SELECT MAX(entry_id) as res FROM translations");
return $result[0][0]['res'] + 1;
}
I don't know why entry_id have all the time the same value.
After many hours of searching for solution I finally managed to solve the problem in very easy way - just add false parameter in query method:
$this->query("INSERT INTO translations(entry_id, language_id, text) VALUES($entry_id, $key, '$item')", false);
and
$result = $this->query("SELECT SQL_CACHE MAX(entry_id) as res FROM translations", false);
I need perform query "LOCK TABLE myTable WRITE"
<?php
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(Database::WHAT_IS_THE_TYPE_SHOULD_SPECIFY_HERE_?, $query);
In framework Kohana 3.3
file ~/modules/database/classes/Kohana/Database.php
implements folowing types:
const SELECT = 1;
const INSERT = 2;
const UPDATE = 3;
const DELETE = 4;
but none of them fit in my case.
Any idea. Thanks.
Google works wonders. http://forum.kohanaframework.org/discussion/6401/lockunlock/p1
You can pass NULL as the first argument:
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(NULL, $query);
From Kohana: http://kohanaframework.org/3.3/guide-api/Database_MySQL#query
if ($type === Database::SELECT)
{
// Return an iterator of results
return new Database_MySQL_Result($result, $sql, $as_object, $params);
}
elseif ($type === Database::INSERT)
{
// Return a list of insert id and rows created
return array(
mysql_insert_id($this->_connection),
mysql_affected_rows($this->_connection),
);
}
else
{
// Return the number of rows affected
return mysql_affected_rows($this->_connection);
}
As you can see that's why you're able to pass NULL.
I have a similar problem that the function only return the first loop data.
The result should be 2 loops and each loop has rows data.
For example, The first loop is A and has 5 rows data and second loop is B and has 5 rows.
The return value only A with 5 rows, it sould be 10 rows. 5 rows A + 5 rows B.
How is the code should be?
This function in model is bellow
function getDataForm($data_search)
{
$i=0;
if(!empty($data_search['arr_idacl']))
{
foreach($data_search['arr_idacl'] as $idx => $val)
{
if(!empty($operatingHour))
{
$sql = "SELECT be_acl_resources.description as description,DATE_FORMAT(tbl_camera_detail.start_time,'%d %M %Y ') as datadate, SUM(IF(tbl_consolid_detail.operation = 'plus' AND tbl_consolid_detail.direction = 'IN',tbl_camera_detail.enters,0))+SUM(IF(tbl_consolid_detail.operation = 'minus' AND tbl_consolid_detail.direction = 'IN',tbl_camera_detail.enters*(-1),0))+SUM(IF(tbl_consolid_detail.operation = 'plus' AND tbl_consolid_detail.direction = 'OUT',tbl_camera_detail.exits,0))+SUM(IF(tbl_consolid_detail.operation = 'minus' AND tbl_consolid_detail.direction = 'OUT',tbl_camera_detail.exits*(-1),0)) as total_enter FROM tbl_consolid JOIN tbl_consolid_detail ON tbl_consolid.id = tbl_consolid_detail.consolid_id JOIN tbl_config_data ON tbl_consolid_detail.config_data_id = tbl_config_data.id JOIN tbl_camera ON tbl_config_data.id_acl = tbl_camera.id_acl JOIN tbl_camera_detail ON tbl_camera.id = tbl_camera_detail.camera_id JOIN be_acl_resources ON tbl_consolid.id_acl = be_acl_resources.id WHERE tbl_camera.date >= '".$data_search['start_date']."' AND date_format(tbl_camera_detail.start_time, '%H, %i %S') >= '".$startOpratingHour."' AND date_format(tbl_camera_detail.start_time, '%H, %i %S') <= '".$operatingHour['finish_time']."' AND tbl_camera.date <= '".$data_search['end_date']."' AND tbl_consolid.id_acl = '".$val."' GROUP BY tbl_camera.date";
echo $sql;
$query = $this->db->query($sql);
$result_data[] = $query->result();
//return $result;
}
$i++;
}
return $result_data;
}
}
Declare $result_data = array(); just before if(!empty($data_search['arr_idacl'])) condition.
Replace $result_data[] = $query->result(); with $result_data[$i] = $query->result();
Update:
Just close to the answer. :) Try this:
Replace $result_data[] = $query->result(); with $result_data[$i][] = $query->result();