yii database query inside loop - loops

I didn't get the correct filter out for the following action. Here $val is an array of checked values. But the query executes only for the last element of the array even though I used the foreach loop. Please, can anyone help me?
if( isset($_POST['state']) && count($_POST['state']) > 0 ){
foreach($_POST['state'] as $row => $val ){
$criteria = new CDbCriteria;
$criteria->select='*';
$criteria->condition='pjt_user_id=:pjt_user_id && pjt_pdt_status=:pjt_pdt_status';
$criteria->params=array(':pjt_user_id'=> $user_id, ':pjt_pdt_status'=> $val);
$criteria -> order = 'pjt_id';
$projects= ProjectModel::model() -> findAll($criteria);
}
$this->render('index', array('projects'=>$projects));

Thanks Martin Komara....
I got the solution ...
I just use OR condition in SQL.
if(isset($_POST['state']) && count($_POST['state']) > 0 ){
$i = 0;
foreach($_POST['state'] as $data){
$condit[":$data"] = $data;
if($i!=0){
$var .= ' || ';
}
$var .= " pjt_pdt_status=:$data";
$i++;
}
$var = ' AND (' .$var.' )';
}
$criteria = new CDbCriteria;
$criteria->select='*';
$criteria->condition='pjt_user_id=:pjt_user_id' .$var ;
$criteria->params=$condit;
$criteria -> order = 'pjt_id';
$projects= ProjectModel::model() -> findAll($criteria);

This would be better - much more readable:
if (isset($_POST['state']) && count($_POST['state']) > 0 ) {
$criteria = new CDbCriteria;
$criteria->addInCondition('pjt_pdt_status', $_POST['state']);
$criteria->addColumnCondition(array('pjt_user_id' => $user_id));
$criteria->order = 'pjt_id';
$projects = ProjectModel::model()->findAll($criteria);
}

Related

Unable to find if one item exists in array of items and return the necessary message in Perl

I have array of IDs. I have one ID which I want to find if that ID exists in the array of IDs in Perl
I tried the following code:
my $ids = [7,8,9];
my $id = 9;
foreach my $new_id (#$ids) {
if ($new_id == $id) {
print 'yes';
} else {
print 'no';
}
}
I get the output as:
nonoyes
Instead I want to get the output as only:
yes
Since ID exists in array of IDs
Can anyone please help ?
Thanks in advance
my $ids = [7,8,9];
my $id = 9;
if (grep $_ == $id, #ids) {
print $id. " is in the array of ids";
} else {
print $id. " is NOT in the array";
}
You just need to remove the else part and break the loop on finding the match:
my $flag = 0;
foreach my $new_id (#$ids) {
if ($new_id == $id) {
print 'yes';
$flag = 1;
last;
}
}
if ($flag == 0){
print "no";
}
Another option using hash:
my %hash = map { $_ => 1 } #$ids;
if (exists($hash{$id})){
print "yes";
}else{
print "no";
}
use List::Util qw(any); # core module
my $id = 9;
my $ids = [7,8,9];
my $found_it = any { $_ == $id } #$ids;
print "yes" if $found_it;
The following piece of code should cover your requirements
use strict;
use warnings;
my $ids = [7,8,9];
my $id = 9;
my $flag = 0;
map{ $flag = 1 if $_ == $id } #$ids;
print $flag ? 'yes' : 'no';
NOTE: perhaps my #ids = [7,8,9]; is better way to assign an array to variable

Combined two arrays and the result returned has an empty key and value

I have an excel sheet which is read and converted to an array.
Here is the code :
$filename = $_FILES['importProjects']['tmp_name'];
$objPHPExcel = PHPExcel_IOFactory::load($filename);
$i = 0;
$all_sheet = $objPHPExcel->getSheetCount(); //total number of sheets
$arrayInsertProject = array();
$arrayUpdateProject = array();
while ($i < $all_sheet){
$objPHPExcel->setActiveSheetIndex($i);
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of rows from the sheet
$column = 'A';
$project_cnt=1;
$dataIns = array();
for ($row = 1; $row <= $arrayCount; $row++) { //loop through rows
if($row ==1){
$highestColumn = $objPHPExcel->getActiveSheet()->getHighestColumn();
$rowDataHeader = $objPHPExcel->getActiveSheet()->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$rowDataHeader = array_reduce($rowDataHeader, 'array_merge', array());
}else {
$highestColumn = $objPHPExcel->getActiveSheet()->getHighestColumn();
$rowData = $objPHPExcel->getActiveSheet()->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$dataIns = array_combine($rowDataHeader, $rowData);
}
}
}
When I print this array $dataIns, I get something like this :
Array
(
[intProjectSlNo] => 1069
[chvProjectNameEng] => New
[slug] => this-is -test
[nchvSecType] => 1754349
[] =>
)
How to remove the empty key => value pair ?
Add this after while loop of your code
foreach($dataIns as $key=>$value)
{
if(is_null($value) || $value == '')
unset($dataIns[$key]);
}
print_r($dataIns);

"return" in foreach will only return one set of results, but echo returns all

I have no idea why it will return all the values I'm looking for with echo, but only 1 set with "return".
I removed all the code within the first foreach statement to see if there was some conflict between the foreach statements, but it returns with the same result.
I've tried some of the suggestions on here that I thought might be relevant, but without any luck.
What could I possibly be doing wrong?
function getInvoiceTimeLog($project_unique_id, $user_id, $user_timezone, $time_format)
{
global $db;
$query = "SELECT t.task_id, t.unique_id, t.name, t.description, t.sub_total, p.project_id, p.user_id FROM task as t, task_project as tp, project as p WHERE t.task_id = tp.task_id AND tp.project_id = p.project_id AND p.unique_id = ".$db->prep($project_unique_id)." AND p.user_id = ".$db->prep($user_id)." ORDER BY t.name";
$res = $db->query($query,'assoc');
if($res != false)
{
foreach($res as $row1):
$date = '';
$prevDate = '';
$return = '';
$query = "SELECT a.track_id FROM task_track a INNER JOIN track_time b ON a.track_id = b.track_id WHERE a.task_id =".$db->prep($row1['task_id'])." ORDER BY FROM_UNIXTIME(b.time_start,'%Y-%m-%d %H:%i:%s') DESC";
$resT = $db->query($query,'assoc');
$return .= '<div class="table" id="InvoicetimeLog"><div class="thead"><div class="th date">Date</div><div class="th start">Start</div><div class="th stop">Stop</div><div class="th hours">Hours</div></div><ul class="list">';
$return .= '<li>'.$row1['description'].'</li>';
if($resT != false)
{
foreach($resT as $row):
$track_id = $row['track_id'];
$query = "SELECT comment_id FROM track_comment WHERE track_id = ".$db->prep($track_id);
$resComLink = $db->query($query,'assoc');
if($resComLink != false)
{
$query = "SELECT comment,time_left FROM comment WHERE comment_id = ".$db->prep($resComLink[0]['comment_id']);
$resComment = $db->query($query,'assoc');
$comment_class = 'comment_has';
}
else
{
$comment = '';
$comment_class = 'comment';
}
$query = "SELECT time_start,time_end FROM track_time WHERE track_id = ".$db->prep($track_id);
$resTime = $db->query($query,'assoc');
$date = format_time($resTime[0]['time_start'],'m/d/y');
if($date != $prevDate)
{
$prevDate = format_time($resTime[0]['time_start'],'m/d/y');
$timeLog_ex = '<div class="date bold">'.$prevDate.'</div>';
$group = 'grp_shw';
}
else
{
$timeLog_ex = '<div class="date bold"></div>';
$group = 'grp_no';
}
if($time_format == 'g')
{
$the_time_format = 'g:i a';
}
else
{
$the_time_format = 'G:i';
}
if(empty($resTime[0]['time_end']))
{
$return .= '<li class="'.$group.'" id="rtrack_'.$track_id.'">'.$timeLog_ex.'<div class="start inlineEdit">'.date('m/d/y - '.$the_time_format,$resTime[0]['time_start']).'</div><div class="stop" title="The current time is at '.date($the_time_format,$db->nowUnix($user_timezone)).'">Current</div><div class="hours">'.getTimeDifference($resTime[0]['time_start'],$db->nowUnix($user_timezone)).'</div></li>';
}
else
{
$return .= '<li class="'.$group.'" id="rtrack_'.$track_id.'">'.$timeLog_ex.'<div class="start inlineEdit">'.date('m/d/y - '.$the_time_format,$resTime[0]['time_start']).'</div><div class="stop">'.date('m/d/y - '.$the_time_format,$resTime[0]['time_end']).'</div><div class="hours">'.getTimeDifference($resTime[0]['time_start'],$resTime[0]['time_end']).'</div></li>';
}
endforeach;
$return .= '<li class="grp_no"><div class="date bold">Total Time</div><div class="total">'.tot_time($unique_id,$user_id, $user_timezone).'</div></li>';
}
$return .= '</ul></div>';
endforeach;
}
return $return;
}
What a dope I am. It's simple....just move the variable declarations OUTSIDE of the foreach loop!
Move these guys to above the first foreach:
$date = '';
$prevDate = '';
$return = '';

How to put a database into an array

I finally succeeded in making an image carousel by using php.
The code below works, but there are no images in it.
Now I am trying to make this array to get data from a Mysql database.
Could you show me an example of how do I do it?
<?php
//MySQL database connection
$mysqli = new mysqli('localhost', 'root', '', 'webshop');
$SQL = "SELECT image FROM productlist LIMIT 5";
$result = $mysqli->query($SQL);
$array = array(
0 => "picture1.jpg",
1 => "picture2.jpg",
2 => "picture3.jpg",
3 => "picture4.jpg",
4 => "picture5.jpg",
5 => "kalle6.jpg",
);
//Goes to previous page when clicking on prev
$index = $_GET['start'];
if ($index > 0) {
echo ' prev ';
} else {
echo ' prev ';
}
//Display 3 images
$show_img = 3;
$num_img = 0;
for($i = $_GET['start']; $i<count($array) && $num_img < $show_img; $i++) {
$num_img++;
echo "<img src=".$array[$i]."/>\n";
}
for($i=$num_img; $i<$show_img;$i++) {
echo "<img src=".(count($array) - 1)."/>\n";
}
//Goes to next page when clicking on next
if ($index < count($array) - 1) {
echo ' next ';
} else {
echo ' next ';
}
?>
You should have a look at this: http://php.net/manual/en/mysqli-result.fetch-array.php
/* numeric array */
/* $row is your $array */
$row = $result->fetch_array(MYSQLI_NUM);
echo "<pre>";
print_r($row);
echo "<pre>";
This should help you get the result you want

how to check the value of an array in codeigniter

$result=array();
$count = count($days);
for($i=0;$i<$count-1; $i++)
{
$bookDate = $days[$i];
$fromDate = $this->booking_model->Get_BookedDate($bookDate,$roomname);
if ($fromDate != 0)
{
$result[] = $bookDate;
}
}
return $result;
This is my codeigniter controller function here I want to check the value of $fromDate is zero or not. I am getting the array like this
Array ( [0] => Array ( ["2013-04-27" between fromDate and toDate] => 1 ) )
I am very new to codeigniter. Thank you for any help.
$result=array();
$count = count($days);
for($i=0;$i<$count-1; $i++)
{
$bookDate = $days[$i];
$fromDate = $this->booking_model->Get_BookedDate($bookDate,$roomname);
if (!empty($fromDate[0]['"'.$bookDate.'" between fromDate and toDate']))
{
$result[] =$bookDate;
}
}
return $result;
Try this.IT may help you
Make use of empty() function.
if(!empty($fromdate)) { //if $formdate is empty or 0 or false the loop won't be executed
//Your code.
}
if (!empty($fromDate))
{
$result[] = $bookDate;
}
Try this.

Resources