modify a query of a joomla module - php

i have a module which executes two functions. the first filters and showsthe latest comments per category. the second one filters and shows the top commenters of all categories. i want to hack it in order to show the top commenters per category. for the first one there is in the backend the option to select category but for the top commenters there is not.
here is the code of the module. forgive me for its length.
class modK2CommentsHelper
{
public static function getLatestComments(&$params)
{
$mainframe = JFactory::getApplication();
$limit = $params->get('comments_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$cid = $params->get('category_id', NULL);
$jnow = JFactory::getDate();
$now = K2_JVERSION != '15' ? $jnow->toSql() : $jnow->toMySQL();
$nullDate = $db->getNullDate();
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
$query = "SELECT c.*, i.catid, i.title, i.alias, category.alias as catalias, category.name as categoryname
FROM #__k2_comments as c
LEFT JOIN #__k2_items as i ON i.id=c.itemID
LEFT JOIN #__k2_categories as category ON category.id=i.catid
WHERE i.published=1
AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
AND i.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND i.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND i.access<={$aid} ";
}
$query .= " AND category.published=1 AND category.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND category.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND category.access<={$aid} ";
}
$query .= " AND c.published=1 ";
if ($params->get('catfilter'))
{
if (!is_null($cid))
{
if (is_array($cid))
{
JArrayHelper::toInteger($cid);
$query .= " AND i.catid IN(".implode(',', $cid).")";
}
else
{
$query .= " AND i.catid=".(int)$cid;
}
}
}
if (K2_JVERSION != '15')
{
if ($mainframe->getLanguageFilter())
{
$languageTag = JFactory::getLanguage()->getTag();
$query .= " AND category.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
}
}
$query .= " ORDER BY c.commentDate DESC ";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
if (count($rows))
{
foreach ($rows as $row)
{
if ($params->get('commentDateFormat') == 'relative')
{
$config = JFactory::getConfig();
$now = new JDate();
if (K2_JVERSION == '30')
{
$tzoffset = new DateTimeZone(JFactory::getApplication()->getCfg('offset'));
$now->setTimezone($tzoffset);
}
else
{
$tzoffset = $config->getValue('config.offset');
$now->setOffset($tzoffset);
}
$created = new JDate($row->commentDate);
$diff = $now->toUnix() - $created->toUnix();
$dayDiff = floor($diff / 86400);
if ($dayDiff == 0)
{
if ($diff < 5)
{
$row->commentDate = JText::_('K2_JUST_NOW');
}
elseif ($diff < 60)
{
$row->commentDate = $diff.' '.JText::_('K2_SECONDS_AGO');
}
elseif ($diff < 120)
{
$row->commentDate = JText::_('K2_1_MINUTE_AGO');
}
elseif ($diff < 3600)
{
$row->commentDate = floor($diff / 60).' '.JText::_('K2_MINUTES_AGO');
}
elseif ($diff < 7200)
{
$row->commentDate = JText::_('K2_1_HOUR_AGO');
}
elseif ($diff < 86400)
{
$row->commentDate = floor($diff / 3600).' '.JText::_('K2_HOURS_AGO');
}
}
}
$row->commentText = K2HelperUtilities::wordLimit($row->commentText, $params->get('comments_word_limit'));
$row->commentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->commentText);
$row->itemLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($row->itemID.':'.urlencode($row->alias), $row->catid.':'.urlencode($row->catalias))));
$row->link = $row->itemLink."#comment{$row->id}";
$row->catLink = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($row->catid.':'.urlencode($row->catalias))));
if ($row->userID > 0)
{
$row->userLink = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
$getExistingUser = JFactory::getUser($row->userID);
$row->userUsername = $getExistingUser->username;
}
else
{
$row->userUsername = $row->userName;
}
// Switch between commenter name and username
if ($params->get('commenterName', 1) == 2)
$row->userName = $row->userUsername;
$row->userImage = '';
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
$comments[] = $row;
}
return $comments;
}
}
public static function getTopCommenters(&$params)
{
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
$limit = $params->get('commenters_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$query = "SELECT COUNT(id) as counter, userName, userID, commentEmail FROM #__k2_comments WHERE userID > 0 AND published = 1 GROUP BY userID ORDER BY counter DESC";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
if (count($rows))
{
foreach ($rows as $row)
{
if ($row->counter > 0)
{
$row->link = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
if ($params->get('commenterNameOrUsername', 1) == 2)
{
$getExistingUser = JFactory::getUser($row->userID);
$row->userName = $getExistingUser->username;
}
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
if ($params->get('commenterLatestComment'))
{
$query = "SELECT * FROM #__k2_comments WHERE userID = ".(int)$row->userID." AND published = 1 ORDER BY commentDate DESC";
$db->setQuery($query, 0, 1);
$comment = $db->loadObject();
$item = JTable::getInstance('K2Item', 'Table');
$item->load($comment->itemID);
$category = JTable::getInstance('K2Category', 'Table');
$category->load($item->catid);
$row->latestCommentText = $comment->commentText;
$row->latestCommentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->latestCommentText);
$row->latestCommentLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias), $item->catid.':'.urlencode($category->alias))))."#comment{$comment->id}";
$row->latestCommentDate = $comment->commentDate;
}
$commenters[] = $row;
}
}
if (isset($commenters))
return $commenters;
}
}
}
every help is appreciated. thank you very much

Related

PHP PDO Prepare select where ? Query Error

public function listeFilitreAltKategoriId($filitre,$limit,$offset) {
$sorgu = self::$db->prepare( "SELECT * FROM urun WHERE (?) LIMIT ?,?" );
$sorgu->execute(array($filitre,$limit,$offset));
return $sorgu;
}
$limit=0;
$offset=10;
$strSemt= implode(',',$semt);
$where=[];
$where[]="altkategoriid={$sorguAltMenu[ 'id' ]}";
if($strSemt!=""){
$where[]="semt IN ($strSemt)";
}
if(!empty($min) || !empty($max)){
if(!empty($min) && empty($max)){
$where[]="fiyat >= $min ";
}
if(!empty($max) && empty($min)){
$where[]="fiyat <= $max";
}
if(!empty($max) && !empty($min)){
$where[]="fiyat BETWEEN $min AND $max";
}
}
if($kur!=""){
$where[]="kur=$kur";
}
$filitre = implode(" AND ",$where);
$UrunList = ( new UrunModel() )->listeFilitreAltKategoriId($filitre,$limit,$offset);
I Use Similar to This And The Result Freezes To Zero.
This Is The Way The Query Works.
But I Wanna Make It Work Like The Master.
I know you have received a question similar to this, but I haven't solved it for 2 hours.
//$db=(new UrunModel())->database();
// $UrunList = $db->prepare( "SELECT * FROM urun WHERE ".implode(" AND ",$where)." LIMIT $limit,$offset" );
// $UrunList->execute();
$value = [
"min_limit" => $min,
"max_limit" => $max
];
$where[] = "altkategoriid = :id";
$value["id"] = $sorguAltMenu['id'];
if( !empty($min) && empty($max) ){
$where[] = "fiyat >= :min";
$value["min"] = $min;
}
if( !empty($max) && empty($min) ){
$where[] = "fiyat <= :max";
$value["max"] = $max;
}
if( !empty($max) && !empty($min) ){
$where[] = "fiyat BETWEEN :min AND :max";
$value["min"] = $min;
$value["max"] = $max;
}
if( !empty($kur) ){
$where[] = "kur = :kur";
$value["kur"] = $kur;
}
if( count($semt) ){
$place_holders = [];
$count = 1;
foreach($semt as $semt_value){
$place_holders[] = ":semt_{$count}";
$value["semt_{$count++}"] = $semt_value;
}
$place_holder_string = implode(", ", $place_holders);
$where[] = "semt IN ({$place_holder_string})";
}
$where_clause = implode(" AND ", $where);
$sql = "
SELECT *
FROM urun
WHERE {$where_clause}
LIMIT :min_limit, :max_limit
";
$query = $pdo->prepare($sql);
$query->execute($value);
while( $row = $query->fetchObject() ){
// Do something...
}

my php code is secure? php to pdo over eval function

i'm writing a php web script with mvc, but i'm concerned about code is safe.
i fear most "eval($str)", but i try a lot of php function string but nothing happened.
$a = func_get_args();
if((func_num_args()-1)%2 == 0){
$str = "";
array_shift($a);
for($i = 0;$i<sizeof($a);$i++){
if($i%2==0){
if(!is_numeric($a[$i])){
if($a[$i] == 'filter'){
$filter=1;
}
$str.= "$".stripslashes($a[$i])." = ";
}else{
$str.= 'page';
}
}else{
if($filter != 1){
if(is_numeric($a[$i])){
$str.= stripslashes($a[$i]).";";
}else{
$str.=1;
}
}else{
$arr = explode("-",$a[$i]);
$dizz = 'array(';
for($j=0;$j<sizeof($arr);$j++){
if(($j%2)==0){
$dizz .= '\''.stripslashes($arr[$j]).'\'=>';
}else{
$dizz .= '\''.stripslashes($arr[$j]).'\',';
}
}
$dizz = rtrim($dizz,',');
$dizz .= ');';
$str.= $dizz;
}
}
}
eval($str);
}
$filter = isset($filter) ? $filter : false;
$page= isset($page) ? $page: '';
$count= isset($count) ? $count: '';
if($count == ''){
switch ($process) {
case 'table':
$count = 40;
break;
case 'detailed':
$count = 3;
break;
case 'mobile':
$count = 12;
break;
default:
$count = '';
break;
}
}
if($count != ''){
if(is_numeric($count )){
if($count <=200 && $count >0){
$count = $count ;
}else{
$count = 40;
}
}else{
$count = 1;
}
}
if(!is_numeric($page)){
$page= 1;
}
to sql query->
$new_filter = "Where ";
if($filter){
foreach ($filteras $key => $value) {
$new_filter .= 'k.'.$key.'='.$value.' and ';
}
$new_filter = rtrim($new_filter,' and ');
$filter= $new_filter;
}else{
$filter= '';
}
$limit = ($limit) ? 'LIMIT 30' : '';
if($id == ''){
$where = $filter;
}else{
$where = $id;
}
$query = 'select * from kullanici as k join kisiler as ki on k.id = ki.kullanici_id join iletisim as i on k.id = i.kullanici_id '.$where.' '.$siralama.' '.$limit;
$query = $this->_db->prepare($query);
$query->execute();
example url:
profile/show/mobile/page/4/count/5/filter/echo-"'xzcxza'"-sadas-asdxc
this results:
$page = 4;$count= 5;$filter= array('echo'=>'%22%27xzcxza%27%22','sadas'=>'asdxc');

I can't show multiple days of absent

my client ask me to show the in and out of their employees from biometrics..i already did it but it only shows data for 1 day. Can somebody help me..If you can see I had a lot of codes there and it doesn't satisfy my client.I'am working on it for almost a month
this is my code..I'm a beginner.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_REQUEST['startdate']) && isset($_REQUEST['enddate']))
{
$startdate = $_REQUEST['startdate'];
$enddate = $_REQUEST['enddate'];
$shiftdate = $_REQUEST['shiftdate'];
$category= $_REQUEST['category'];
$counterless = 0;
$ncounter = 0;
$count =0 ;
$loop=0;
$holder=0;
$checker=0;
$wala = 0;
$present = 0;
/*$_SESSION['nightname'] = array();
$_SESSION['nighttime'] = array();
$_SESSION['testname'] = array();
$_SESSION['testtime'] = array();*/
$con = mysqli_connect("localhost","root","","testingdb");
$connect = mysqli_connect("localhost","root","","inoutchecking");
mysqli_query($con,"delete from forprint");
mysqli_query($con,"delete from absentforprint");
$result = mysqli_query($con,"select * from wawart where Column_2 = '$startdate' order by Column_2 asc");
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$time = $row['Column_3'];
$times = (int)($time);
$inout = $row['Column_4'];
$dates = $row['Column_2'];
if(($times <= 14 and $inout == '1') or ($times >=17 and $inout == '4'))
{
$_SESSION['testname'][$counterless] = $row['Column_1'];
$_SESSION['testtime'][$counterless] = $time;
$counterless++;
}
if(($times <= 20 and $times >= 15) and $inout == '1')
{
$_SESSION['nightname'][$ncounter] = $row['Column_1'];
$_SESSION['nighttime'][$ncounter] = $time;
$ncounter++;
}
}
$wala=1;
}
else
{
$wala=0;
}
if($category == 'dayshift')
{
$shift = 'Day Shift';
}
else if($category == 'nightshift')
{
$shift = 'Night Shift';
}
else
{
$shift = 'Night Shift and Day Shift';
}
echo "<label class='cat'>".$shift."</label>";
echo "<label class='absent'>Absentees ".$startdate."</label>";
if($category == 'dayshift')
{
mysqli_query($connect,"insert into forprint (empid,lastname,firstname,department,section,timein,timeout,stat) values('Employee Number','Lastname','Firstname','Department','Section','Time in','Time out','Shift')");
echo "<div class='dayshift'> <table class='CSSTableGenerator'><tr><th>Emp#</th><th>LASTNAME</th><th>FIRSTNAME</th><th>DEPARTMENT</th><th>SECTION</th><th>DATE</th><th>IN</th><th>OUT</th></tr>";
for($x = 0; $x<$counterless;$x++)
{
$dempid = $_SESSION['testname'][$x];
$day = mysqli_query($connect,"select * from nightshiftlist where empid = '$dempid' and shift ='dayshift' and datefrom = '$shiftdate' and datehired <= '$startdate'");
while($empinfo = mysqli_fetch_array($day))
{
$count++;
if($loop == '1')
{
echo "<td>NO OUT</td></tr>";
$loop=0;
}
$empid = $empinfo['empid'];
$empshift = $empinfo['shift'];
$name = $empinfo['lastname'];
$fname = $empinfo['firstname'];
$dept = $empinfo['department'];
$section = $empinfo['section'];
$checking = mysqli_query($con,"select * from wawart where Column_1='$empid' and (Column_2 between '$startdate' and '$enddate') order by Column_2 asc");
if($holder == $empinfo['empid'])
{
break;
}
echo"<tr><td>".$empinfo['empid']."</td><td>".$empinfo['lastname']."</td><td>".$empinfo['firstname']."</td><td>".$empinfo['department']."</td><td>".$empinfo['section']."</td>";
if(mysqli_num_rows($checking)>0)
{
while($row=mysqli_fetch_array($checking))
{
$time = $row['Column_3'];
$times = (int)$time;
if($holder == $empinfo['empid'])
{
break;
}
else
{
$inout = $row['Column_4'];
$time = $row['Column_3'];
if($loop ==0)
{
$date = $row['Column_2'];
echo"<td>".$row['Column_2']."</td>";
}
if($loop ==0 )
{
if($inout == '1')
{
$timein = $time;
echo "<td>".$time."</td>";
$loop = 1;
}
if($inout == '4')
{
$timein = 'NO IN';
$timeout = $time;
echo "<td><B>NO IN</td><td>".$time."</td></tr>";
$holder = $empinfo['empid'];
$loop = 0;
}
}
else
{
if($loop =='1' && $inout == '4')
{
$timeout = $time;
echo "<td>".$time."</td></tr>";
}
if($loop =='1' && $inout == '1')
{
$timeout = 'NO OUT';
echo "<td><B>NO OUT</td></tr>";
}
$loop = 0;
$counter = 0;
$holder = $empinfo['empid'];
$checker = 2;
if($checker == 2)
{
mysqli_query($connect,"insert into forprint (empid,lastname,firstname,department,section,timein,timeout,stat) values('$empid','$name','$fname','$dept','$section','$timein','$timeout','$empshift')");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
}
}
}
}
ini_set('max_execution_time', 999999);
}
}
echo"</table></div>";
/*absentees*/
if($wala == 1)
{
$count = 0;
mysqli_query($connect,"insert into absentforprint (empid,lastname,firstname,department,section) values ('Employee Number','Lastname','Firstname','Department','Section')");
echo "<div class='absentees'> <table class='CSSTableGenerator'><tr><th>Emp#</th><th>LASTNAME</th><th>FIRSTNAME</th><th>DEPARTMENT</th><th>SECTION</th></tr>";
$day = mysqli_query($connect,"select * from nightshiftlist where shift ='dayshift' and datefrom = '$shiftdate' and datehired <= '$startdate'");
while($empinfo = mysqli_fetch_array($day))
{
$id = $empinfo['empid'];
$shift = $empinfo['shift'];
$lname = $empinfo['lastname'];
$fname = $empinfo['firstname'];
$date = $empinfo['datefrom'];
$dept = $empinfo['department'];
$section = $empinfo['section'];
for($x = 0; $x<$counterless;$x++)
{
$dempid = $_SESSION['testname'][$x];
if($id == $dempid)
{
$present = 1;
break;
}
else
{
$present = 0;
}
ini_set('max_execution_time', 999999);
}
if($present == 0)
{
echo "<tr><td>".$id."</td><td>".$lname."</td><td>".$fname."</td><td>".$dept."</td><td>".$section."</td></tr>";
mysqli_query($connect,"insert into absentforprint (empid,lastname,firstname,department,section) values ('$id','$lname','$fname','$dept','$section')");
ini_set('max_execution_time', 999999);
$count++;
}
}
echo"</table></div>";
echo"<label class='totalabs'>Total Number of Absentees ".$count."</label>";
}
}/*end of absentees*/
if($category == 'nightshift')
{
mysqli_query($connect,"insert into forprint (empid,lastname,firstname,department,section,timein,timeout,stat) values('Employee Number','Lastname','Firstname','Department','Section','Time in','Time out','Shift')");
echo "<div class='dayshift'> <table class='CSSTableGenerator'><tr><th>Emp#</th><th>LASTNAME</th><th>FIRSTNAME</th><th>DATE</th><th>DEPARTMENT</th><th>SECTION</th><th>IN</th><th>OUT</th></tr>";
for($x = 0; $x<$ncounter;$x++)
{
$dempid = $_SESSION['nightname'][$x];
$day = mysqli_query($connect,"select * from nightshiftlist where empid = '$dempid' and shift = 'nightshift' and datefrom = '$shiftdate' and datehired <= '$startdate'");
while($empinfo = mysqli_fetch_array($day))
{
$count++;
if($loop == '1')
{
echo "<td>NO OUT</td></tr>";
$loop=0;
}
$empid = $empinfo['empid'];
$empshift = $empinfo['shift'];
$name = $empinfo['lastname'];
$fname = $empinfo['firstname'];
$dept = $empinfo['department'];
$section = $empinfo['section'];
$checking = mysqli_query($con,"select * from wawart where Column_1='$empid' and (Column_2 between '$startdate' and '$enddate') order by Column_2 asc");
if($holder == $empinfo['empid'])
{
break;
}
echo"<tr><td>".$empinfo['empid']."</td><td>".$empinfo['lastname']."</td><td>".$empinfo['firstname']."</td><td>".$empinfo['department']."</td><td>".$empinfo['section']."</td>";
if(mysqli_num_rows($checking)>0)
{
while($row=mysqli_fetch_array($checking))
{
$time = $row['Column_3'];
$times = (int)$time;
if($holder == $empinfo['empid'])
{
break;
}
else
{
$inout = $row['Column_4'];
$time = $row['Column_3'];
$dates = $row['Column_2'];
if($loop ==0 && $inout == '1'&& $dates == $startdate)
{
$date = $row['Column_2'];
echo"<td>".$row['Column_2']."</td>";
}
if($loop ==0 && $dates == $startdate)
{
if($inout == '1')
{
$timein = $time;
echo "<td>".$time."</td>";
$loop = 1;
}
if($inout == '4')
{
$timein = 'NO IN';
$loop = 0;
}
}
else
{
if($loop =='1' && $inout == '4')
{
$timeout = $time;
echo "<td>".$time."</td></tr>";
}
if($loop =='1' && $inout == '1')
{
$timeout = 'NO OUT';
echo "<td><B>NO OUT</td></tr>";
}
$loop = 0;
$counter = 0;
$holder = $empinfo['empid'];
$checker = 2;
if($checker == 2)
{
mysqli_query($connect,"insert into forprint (empid,lastname,firstname,department,section,timein,timeout,stat) values('$dempid','$name','$fname','$dept','$section','$timein','$timeout','$empshift')");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
}
}
}
}
ini_set('max_execution_time', 999999);
}
}
echo"</table></div>";
/*absentees*/
if($wala == 1)
{
$count = 0;
mysqli_query($connect,"insert into absentforprint (empid,lastname,firstname,department,section) values ('Employee Number','Lastname','Firstname','Department','Section')");
echo "<div class='absentees'> <table class='CSSTableGenerator'><tr><th>Emp#</th><th>LASTNAME</th><th>FIRSTNAME</th><th>DEPARTMENT</th><th>SECTION</th></tr>";
$day = mysqli_query($connect,"select * from nightshiftlist where shift ='nightshift' and datefrom = '$shiftdate' and datehired <= '$startdate'");
while($empinfo = mysqli_fetch_array($day))
{
$id = $empinfo['empid'];
$shift = $empinfo['shift'];
$lname = $empinfo['lastname'];
$fname = $empinfo['firstname'];
$dept = $empinfo['department'];
$section = $empinfo['section'];
for($x = 0; $x<$ncounter;$x++)
{
$dempid = $_SESSION['nightname'][$x];
if($id == $dempid)
{
$present = 1;
break;
}
else
{
$present = 0;
}
ini_set('max_execution_time', 999999);
}
if($present == 0)
{
echo "<tr><td>".$id."</td><td>".$lname."</td><td>".$fname."</td><td>".$dept."</td><td>".$section."</td></tr>";
mysqli_query($connect,"insert into absentforprint (empid,lastname,firstname,department,section) values ('$id','$lname','$fname','$dept','$section')");
$count++;
}
ini_set('max_execution_time', 999999);
}
echo"</table></div>";
echo"<label class='totalabs'>Total Number of Absentees ".$count."</label>";
}
}/*end of absentees*/
}
?>
The first sql select query you are executing needs to be corrected.Your select sql query does not considering end date. Try the below query
$result = mysqli_query($con,"select * from wawart where Column_2 >= '$startdate' and Column_2 <= '$enddate' order by Column_2 asc");

Dynamic query php/ mysql

I have some issues with a dynamic query:
$cond = array();
if (!empty($type_contrat)) {
$cond[] = "job_offers.type_contrat = '$type_contrat'";
}
if (!empty($categorie_poste)) {
$cond[] = "job_offers.cat_poste = '$categorie_poste'";
}
if (!empty($niveau_etudes)) {
$cond[] = "job_offers.qualifications = '$niveau_etudes'";
}
if (!empty($experience)) {
$cond[] = "job_offers.experience >= '$experience'";
}
if (count($cond)) {
$query = $mysqli->query('SELECT
job_offers.ref_org,
job_offers.titre,
job_offers.qualifications,
job_offers.experience,
job_offers.cat_poste,
job_offers.type_contrat,
job_offers.taux_occupation,
job_offers.lieu_affectation,
job_offers.pays,
job_offers.url,
job_offers.date_entered,
job_offers.date_expire,
organisations.ref_org,
organisations.name_organisation
FROM job_offers,organisations
WHERE job_offers.ref_org = organisations.ref_org AND ');
$query .= implode(' AND ', $cond);
}
print_r($query);
--> result: prints only (linebreaks added for readability):
job_offers.type_contrat = '1' AND
job_offers.cat_poste = '3' AND
job_offers.qualifications = '2' AND
job_offers.experience >= '1'
and therefore no result.
You are trying to append a string to a mysqli-result object...
Check the returnvalue of the mysqli->result() function here.
Since someone is keen on removing this answer; here's your solution:
$cond = array();
if (!empty($type_contrat)) {
$cond[] = "job_offers.type_contrat = '$type_contrat'";
}
if (!empty($categorie_poste)) {
$cond[] = "job_offers.cat_poste = '$categorie_poste'";
}
if (!empty($niveau_etudes)) {
$cond[] = "job_offers.qualifications = '$niveau_etudes'";
}
if (!empty($experience)) {
$cond[] = "job_offers.experience >= '$experience'";
}
if (count($cond)) {
$query = $mysqli->query('SELECT
job_offers.ref_org,
job_offers.titre,
job_offers.qualifications,
job_offers.experience,
job_offers.cat_poste,
job_offers.type_contrat,
job_offers.taux_occupation,
job_offers.lieu_affectation,
job_offers.pays,
job_offers.url,
job_offers.date_entered,
job_offers.date_expire,
organisations.ref_org,
organisations.name_organisation
FROM job_offers,organisations
WHERE job_offers.ref_org = organisations.ref_org AND '.implode(' AND ', $cond));
}
print_r($query);

Can't debug random error

I have a web-based custom ticket sales I made for a friend and whenever I tried it (on any browser) it worked perfectly fine. However when it went live yesterday some people tried to book tickets and they would receive their email stating they had their seats booked (everything was ok) but the system would only record some of those seats.
Let's say that if they booked A1 - A10 they got an email saying they booked those but the system would only book A1 - A5 (or A6 or so, it seems random).
Also, this wouldn't happen with EVERY person it just happens randomly (at least I haven't found a proper reason for it to happen yet).
The code is here when I book the tickets:
$cantTotal=0;
$boletosF1 = $_POST['funcion1Hidden'];
if($boletosF1!=""){
$lugares = explode(" ", $boletosF1);
$cant = count($lugares);
$cantTotal += $cant;
$f1 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$func = explode(" ", $f1);
$cantUtilizados = count($func);
$repetidos = 0;
for ($int = 0; $int < $cant; $int++) {
for ($r = 0; $r < $cantUtilizados; $r++) {
if ($func[$r] == $lugares[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
$boletosF2 = $_POST['funcion2Hidden'];
if($boletosF2!=""){
$lugares2 = explode(" ", $boletosF2);
$cant2 = count($lugares2);
$cantTotal+=$cant2;
$f2 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$func2 = explode(" ", $f2);
$cantUtilizados = count($func2);
for ($int = 0; $int < $cant2; $int++) {
for ($r = 0; $r < $cantUtilizados; $r++) {
if ($func2[$r] == $lugares2[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
function redirect($url) {
echo "<script language=\"JavaScript\"> window.location='$url'; </script>";
}
$totalAPagar=120*$cantTotal;
and when I save them to the Database and send the email:
$boletosF1 = $_POST['boletosF1'];
$boletosF2 = $_POST['boletosF2'];
$nombre = $_POST['name'];
$correo = $_POST['mail'];
$cant1=0;
$cant2=0;
if($boletosF1!=""){
$lugares1 = explode(" ", $boletosF1);
echo $lugares1;
$cant1 = count($lugares1);
echo $cant1;
$f1 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$func1 = explode(" ", $f1);
$cantUtilizados1 = count($func1);
$repetidos = 0;
for ($int = 0; $int < $cant1; $int++) {
for ($r = 0; $r < $cantUtilizados1; $r++) {
if ($func1[$r] == $lugares1[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
if($boletosF2!=""){
$lugares2 = explode(" ", $boletosF2);
echo $lugares2;
$cant2 = count($lugares2);
echo $cant2;
$f2 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$func2 = explode(" ", $f2);
$cantUtilizados2 = count($func2);
$repetidos = 0;
for ($int = 0; $int < $cant2; $int++) {
for ($r = 0; $r < $cantUtilizados2; $r++) {
if ($func2[$r] == $lugares2[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
$rand = rand(0, 500);
$clave = sha1($rand . date("shd"));
$clave = substr($clave, 5, 5);
//insertar nuevo cliente
//mysql_query('BEGIN');
$sql = "INSERT INTO cliente(`idCliente`,`fecha`,`Nombre`,`correo`)VALUES('$clave',NOW(),'$nombre','$correo')";
$result = mysql_query($sql);
//crear arrays para guardar lugares
//insertar apartado F1
for ($i = 0; $i < $cant1; $i++) {
$sqlF1 = "INSERT INTO apartados(`lugar`,`idCliente`,`funcion`)VALUES('$lugares1[$i]','$clave','F1')";
$resultF1 = mysql_query($sqlF1);
}
for ($i = 0; $i < $cant2; $i++) {
$sqlF1 = "INSERT INTO apartados(`lugar`,`idCliente`,`funcion`)VALUES('$lugares2[$i]','$clave','F2')";
$resultF1 = mysql_query($sqlF1);
}
if (mysql_error ()) {
//echo mysql_error ();
// mysql_query('ROLLBACK');
redirect("apartadoBoletos.php?error=2");
} else {
$totalAPagar=($cant1+$cant2)*120;
// mysql_query('COMMIT');
$to = $correo;
$dia=date("d-m-Y");
//echo $dia;
//User info
$subject = "Boletos"; //The default subject. Will appear by default in all messages.
//The message to be received in the inbox
$msg .= "Estimad# $nombre: \n\n";
$msg .= "Clave: $clave " . "\r\n\n"; //the message itself
$msg .= "Boletos 28 de Junio: $boletosF1 " . "\r\n";
$msg .= "Boletos 27 de Junio: $boletosF2 " . "\r\n\n";
$msg .= "Total a pagar: $ $totalAPagar.00 " . "\r\n\n";
//$header .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$header .= "From: no-reply#booking.com" . "\r\n";
$header .= "Reply-To: no-reply#booking.com" . "\r\n";
$header .= "Return-Path: $email" . "\r\n";
mail($to, $subject, $msg, $header);
}
function redirect($url) {
echo "<script language=\"JavaScript\"> window.location='$url'; </script>";
}
So far I can't find the error and I've got to since this should have started working yesterday but everything had to be stopped =/ I really need help here please.
Also, something that might help, I think the error could be related to the amount of users at a given time however since it just happens to some of the persons that use this I really can't say that's the reason.
If you aren't sure where the error is occurring, you could add extensive logging for a while to see if you can figure it out.
For example, when the user clicks save, or buy tickets, or whatever, you could write to the log file the data that the user has input on the form.
Then, you could log again when you send the purchase information to the database. Record the SQL or stored procedure name and parameter values.
This kind of extensive logging tends to hurt performance, but when you are in a desperate situation, sometimes it's worthwhile.
As soon as you have an idea of the problem, or think you have logged enough data to analyze, you can turn the logging back off.
This is really a comment, but it's too code centric to fit in one.
Consider rewriting your code so it actually uses SQL.
This code
$f1 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
Looks silly, you're not using SQL at all.
Rewrite it into this:
$sqlAP = "SELECT group_concat(lugar SEPARATOR ' ') as lugar
, count(*) as count1
FROM apartados WHERE funcion = 'F1'";
if ($resultAP = mysql_query($sqlAP)) {
$rowAP = mysql_fetch_array($result_AP);
$count = $rowAP['count1'];
$lugar = $rowAP['lugar'];
}
Much faster and much cleaner.

Categories