In my last post someone helped me to show my explore posts and it was very helpful. But I wanna show it in a different way.
When I show my news feed or my profile posts and I reach the bottom, it loads more posts. With my previous code, it just loaded all of them and that's a problem because if there a thousand posts they'll all be loaded at once and I don't want that issue. So I wanna set it up in a way that will load more posts as I get to the bottom. It works for my news feed and profile posts but not the explore posts. It immediately gives me the else statement. it's kind of long but I'm guessing the problem is somewhere at the top of method.
public function loadExplorePosts($data, $limit) {
$page = $data['page'];
$userLoggedIn = $this->user_obj->getUsername();
if($page == 1)
$start = 0;
else
$start = ($page - 1) * $limit;
$str = ""; //String to return
$explore_image = $this->con->prepare('SELECT id, body, added_by, date_added, likes, image FROM posts ORDER BY RAND()');
$explore_image->execute();
// $explore_image->store_result();
//$explore_image->bind_result($id, $body, $added_by, $date_added, $likes, $image);
$explore_image_result = $explore_image->get_result();
if ($explore_image_result->num_rows > 0) {
$num_iterations = 0; //Number of results checked (not necasserily posted)
$count = 1;
while ($row = $explore_image_result->fetch_assoc()) {
$id = $row['id'];
$body = $row['body'];
$added_by = $row['added_by'];
$date_time = $row['date_added'];
$imagePath = $row['image'];
if ($userLoggedIn != $added_by) {
//Check if user who posted, has their account closed
$added_by_obj = new User($this->con, $added_by);
if($added_by_obj->isClosed()) {
continue;
}
$user_logged_obj = new User($this->con, $userLoggedIn);
if($user_logged_obj->isFriend($added_by)){
if($num_iterations++ < $start)
continue;
//Once 10 posts have been loaded, break
if($count > $limit) {
break;
}
else {
$count++;
}
if($userLoggedIn == $added_by)
$delete_button = "<button class='delete_button btn-danger' id='post$id'>X</button>";
else
$delete_button = "";
$user_details_query = $this->con->prepare('SELECT first_name, last_name, profile_pic FROM users WHERE username = ?');
$user_details_query->bind_param("s", $added_by);
$user_details_query->execute();
$user_details_query_result = $user_details_query->get_result();
while ($row = $user_details_query_result->fetch_assoc()) {
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$profile_pic = $row['profile_pic'];
}
?>
<script>
function toggle<?php echo $id; ?>(event){
var target = $(event.target);
if (!target.is('a') && !target.is('button')) {
var element = document.getElementById("toggleComment<?php echo $id; ?>");
if(element.style.display == "block")
element.style.display = "none";
else
element.style.display = "block";
}
}
</script>
<?php
$comments_check = $this->con->prepare('SELECT * FROM comments WHERE post_id = ?');
$comments_check->bind_param("i", $id);
$comments_check->execute();
$comments_check->store_result();
$comments_check_num = $comments_check->num_rows;
//Timeframe
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($date_time); //Time of post
$end_date = new DateTime($date_time_now); //Current time
$interval = $start_date->diff($end_date); //Difference between dates
if($interval->y >= 1) {
if($interval->y == 1)
$time_message = $interval->y . " yr"; //1 year ago
else
$time_message = $interval->y . " yrs"; //1+ year ago
}
else if ($interval->m >= 1) {
if($interval->d == 0) {
$days = " ago";
}
else if($interval->d == 1) {
$days = $interval->d . "d";
}
else {
$days = $interval->d . "ds";
}
if($interval->m == 1) {
$time_message = $interval->m . "m ". $days;
}
else {
$time_message = $interval->m . "m ". $days;
}
}
else if($interval->d >= 1) {
if($interval->d == 1) {
$time_message = "Yesterday";
}
else {
$time_message = $interval->d . " days ago";
}
}
else if($interval->h >= 1) {
if($interval->h == 1) {
$time_message = $interval->h . "hr";
}
else {
$time_message = $interval->h . "hrs";
}
}
else if($interval->i >= 1) {
if($interval->i == 1) {
$time_message = $interval->i . "min";
}
else {
$time_message = $interval->i . " mins";
}
}
else {
if($interval->s < 30) {
$time_message = "Just now";
}
else {
$time_message = $interval->s . "sec";
}
}
if($imagePath != "") {
$imageDiv = "<div class='postedImage'>
<img src='$imagePath'>
</div>";
}
else {
$imageDiv = "";
}
$str .= "<div class='status_post' onClick='javascript:toggle$id(event)'>
<div class='post_profile_pic'>
<img src='$profile_pic' width='50'>
</div>
<div class='posted_by' style='color:#ACACAC;'>
<a href='$added_by'> $first_name $last_name </a> $user_to $time_message
$delete_button
</div>
<div id='post_body'>
$body
<br>
$imageDiv
<br>
<br>
</div>
<div class='newsfeedPostOptions'>
Comments($comments_check_num)
<iframe src='like.php?post_id=$id' scrolling='no'></iframe>
</div>
</div>
<div class='post_comment' id='toggleComment$id' style='display:none;'>
<iframe src='comment_frame.php?post_id=$id' id='comment_iframe' frameborder='0'></iframe>
</div>
<hr>";
}
?>
<?php
}
} //End while loop
if($count > $limit)
$str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'>
<input type='hidden' class='noMorePosts' value='false'>";
else
$str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align: centre;' class='noMorePostsText'><center> No more posts to show! </center></p><br><br>";
}
echo $str;
}
EDIT -----------
I just tried this and the if echo showed up so maybe it's the way I'm trying to output the results:
if ($explore_image_result > 0) {
echo "Found";
} else {
echo "not";
}
Each 5,10,60,3600 minutes crons are runned,
When i check errorlog i see very much deadlocks exceptions, almost each 5 minutes cron send deadlock, timeout and serialization errors to log.
If i understand good deadlocks are happened when two or more queries using same table, what is very possible in my code.
I am using table MAP 2 times in each cron, because i need to map each team,
for example:
Chelsea after mapping returns Chelsea FC
Everton after mapping returns Everton FC
I am getting teams from large xml files, when i kill all processes cron5 is runned in 2 minutes what is ok, but when other processes are on, it takes so while...
When i check by SHOW OPEN TABLES WHERE in_use>0 i see
map table in_use mostly 2, sometimes 1.
function getMap($country,$data){
//echo $data . '<br>';
$fdata = $data;
$query = $this->PDO->prepare("CALL GetMap(:data)");
$query->bindParam(':data', $fdata);
$query->execute();
//echo 'DATA: ' . $data. ' RES: '.$res . '<br>';
$res = $query->fetchColumn();
if($res!=''){
$query->closeCursor();
$sql = "UPDATE map SET Country = :country WHERE Base = :base";
$q2 = $this->PDO->prepare($sql);
$q2->bindParam(':country', $country);
$q2->bindParam(':base', $res);
$q2->execute();
//echo $res;
return $res;
}
else
{
$query->closeCursor();
$this->fillMap($country,$fdata);
return $fdata;
}
}
and this is procedure for GetMap
DELIMITER //
CREATE PROCEDURE GetMap(p_team VARCHAR(100))
BEGIN
SELECT Base FROM map WHERE
map.Base = p_team OR
Ver1 = p_team OR
Ver2 = p_team OR
Ver3 = p_team OR
Ver4 = p_team OR
Ver5 = p_team OR
Ver6 = p_team OR
Ver7 = p_team OR
Ver8 = p_team OR
Ver9 = p_team OR
Ver10 = p_team OR
Ver11 = p_team OR
Ver12 = p_team;
end //
DELIMITER ;
Now my question is how to UNLOCK table map when that table is locked using php?
Also i need to say that i start transaction before xml reading, and commit when everything is completed, so transaction wait about 2 minutes when probably map is not locked. That is maybe reason why i get timeout errors, i can move it inside loop or change mysql timeout.
EDIT detailed code:
CHECK $this->getMap(); what is mostly used table.
function sendOddsToDb(){
try{
$this->conn->connect();
$this->PDO->beginTransaction();
$countries = $this->OddCountries;
$stmt = $this->PDO->prepare($this->insOdds);
//$dbempty = $this->countRows('odds');
//$this->clrLeagues();
foreach($countries as $country){
$path = "{$this->base}/feeds/odds/{$country}odds.xml";
$odds_feed = $this->parser->parseFile($path);
$fupddate = date('Y-m-d H:i:s',strtotime($odds_feed->attributes()->updated));
$newcountry = '';
if(isset($odds_feed->league)){
$newcountry = $odds_feed->league->attributes()->country;
$fcountries = $this->filterCountries($newcountry);
echo $fcountries . '<br>';
$sql = "select UpdatedDate from odds where Country = '{$fcountries}' order by UpdatedDate desc limit 1";
$res = $this->PDO->query($sql);
$dbupd = date('Y-m-d H:i:s',strtotime($res->fetchColumn()));
if(!$this->sameUpdated($fupddate,$dbupd)){
foreach($odds_feed->league as $league){ //za svaku ligu u fidu
$subid = $league->attributes()->sub_id;
$sportname = '';
$sportid = 0;
if($odds_feed->attributes()->sport == 'soccer' || $odds_feed->attributes()->sport == 'football'){
$sportname = 'football';
$sportid = 1;
}
else{
$sportname = NULL;
}
$lg2 = '';
$lg = $league->attributes()->name;
$ctr = $league->attributes()->country.':';
if(!contains(strtolower($lg),strtolower($ctr))){
$lg2 = ucfirst($ctr) . ' ' . ucfirst($lg);
}
else{
$lg2 = $league->attributes()->name;
}
$flg = $this->getMap2($lg2);
$this->sendLeaguesToDb($league->attributes()->id, $flg ,$fcountries,$sportid,$subid,'tipgin');
foreach($league->match as $match){
$dbdate = date('Y-m-d',strtotime($match->attributes()->date));
$updateddate = date('Y-m-d H:i:s',strtotime($odds_feed->attributes()->updated));
$dbtime = date('H:i:s', strtotime($match->attributes()->time));
$datetime = date('Y-m-d H:i:s',strtotime($dbdate . $dbtime));
$hteam = $this->getMap($fcountries,toShort($match->home->attributes()->name));
$ateam = $this->getMap($fcountries,toShort($match->away->attributes()->name));
//echo $hteam . ' ' . $ateam;
$fixid = 0;
if($match->attributes()->id == 0 || $match->attributes()->id == ''){
if($match->attributes()->alternate_id == 0 || $match->attributes()->id == ''){
$fixid = $match->attributes()->alternate_id_2;
}
else{
$fixid = $match->attributes()->alternate_id;
}
}
else{
$fixid = $match->attributes()->id;
}
//$m = $hteam . ' ' . $ateam;
//var_dump('MATCH: ' . $m . ' HTEAM: ' . mb_detect_encoding($hteam). ' ATEAM: ' . mb_detect_encoding($ateam));
if($match->odds != NULL or $match->odds != ''){
foreach ($match->odds as $odds) {
//var_dump($odd);
if($odds->type != NULL or $odds->type != ''){
foreach ($odds->type as $type) {
if($type->bookmaker != NULL or $type->bookmaker != ''){
foreach ($type->bookmaker as $bookmaker) {
//$oldbook = ;
if($bookmaker->attributes()->name != 'BetClick'){
if($bookmaker->attributes()->name != 'Bodog'){
if($bookmaker->attributes()->name != 'YouWin'){
$homeodds = NULL;
$drawodds = NULL;
$awayodds = NULL;
$numodds = NULL;
$dbhandicap = NULL;
$id2 = '0';
$typename = $this->getMap2($type->attributes()->name);
$fbooks = $this->filterBooks($bookmaker->attributes()->name);
if($typename == 'Over/Under' || $typename == 'Over/Under 1st Half' || $typename == 'Over/Under 2nd Half'){
foreach ($bookmaker->total as $total) { //daj kvote za svaki mec
$numodds = $total->attributes()->name;
foreach($total->odd as $odd){
switch ($odd->attributes()->name) {
case 'Over':
$homeodds = $odd->attributes()->value;
break;
case 'Under':
$awayodds = $odd->attributes()->value;
break;
}
$id2 = $numodds;
}
//echo "HOME TEAM: {$hteam} <BR>";
//echo "AWAY TEAM: {$ateam} <BR>";
/*
echo 'IF ID: ' . $match->attributes()->alternate_id_2 . $league->attributes()->country . " ODDS: {$homeodds} {$drawodds} {$awayodds} TYPE: {$typename} BOOK: {$fbooks} ID2: {$id2}" . "<br>";
*/
$this->execOdds($stmt, $fixid, $updateddate,
$typename, $fcountries,$league->attributes()->name,
$league->attributes()->id, $subid, $league->attributes()->cup,$sportname,
$hteam,$match->home->attributes()->id,
$ateam,$match->away->attributes()->id, $datetime, $dbdate,
$dbtime, $match->attributes()->status, $numodds,$homeodds,$drawodds,
$awayodds, $fbooks, $bookmaker->attributes()->id, $dbhandicap, $id2);
}
}
else if($typename == 'Handicap' || $typename == '3Way Handicap'){
$homeodds = array();
$drawodds = array();
$awayodds = array();
$arrhandicap = array();
$fhandicap = '';
foreach ($bookmaker->handicap as $handicap) { //daj kvote za svaki mec
if (strpos($handicap->attributes()->name,'+') !== false) {
$fhandicap = str_replace('+','',(string)$handicap->attributes()->name);
}else{
$fhandicap = (string)$handicap->attributes()->name;
}
$newhandi = '';
foreach($handicap->odd as $odd){
//$odd = $handicap->odd;
switch ($odd->attributes()->name) {
case '1':
$newhandi = (string)$fhandicap;
$homeodds[(string)$newhandi] =
(string)$odd->attributes()->value;
break;
case 'X':
$newhandi = $fhandicap;
$drawodds[(string)$newhandi] =
(string)$odd->attributes()->value;
break;
case '2':
if (strpos($fhandicap,'-') !== false) { //if negative
$newhandi = str_replace('-','',(string)$fhandicap); //to positive
//echo 'NEGATIVE - OLD: ' . $fhandicap . ' NEW: '.$newhandi . '<br>';
}
elseif($fhandicap=='0'){
$newhandi = '0';
}
else{ //if positive
$newhandi = '-' . (string)$fhandicap; //to negative
//echo 'POSITIVE - OLD: ' . $fhandicap . ' NEW: '.$newhandi . '<br>';
}
$awayodds[(string)$newhandi] = (string)$odd->attributes()->value;
break;
}
$arrhandicap[] = (string)$newhandi;
}
}
//print_r($arrhandicap);
//$arrhandicap[] = sort($dbhandicap);
$inhand = '';
$varhome = '';
$vardraw = '';
$varaway = '';
foreach($arrhandicap as $hand){
$inhand = (string)$hand;
if(isset($hand)){
//echo $typename. ': ' . $hand . '<br>';
if((array_key_exists($inhand,$homeodds)) && (isset($homeodds[$inhand]))){
$varhome = $homeodds[$inhand];
}
if((array_key_exists($inhand,$awayodds)) && (isset($awayodds[$inhand]))){
$varaway = $awayodds[$inhand];
}
if((array_key_exists($inhand,$drawodds)) && (isset($drawodds[$inhand]))){
$vardraw = $drawodds[$inhand];
}
$this->execOdds($stmt, $fixid, $updateddate,
$typename, $fcountries,$league->attributes()->name,
$league->attributes()->id, $subid, $league->attributes()->cup,$sportname,
$hteam,$match->home->attributes()->id,
$ateam,$match->away->attributes()->id, $datetime, $dbdate,
$dbtime, $match->attributes()->status, $numodds,$varhome,
$vardraw,$varaway, $fbooks,
$bookmaker->attributes()->id, $hand, $hand);
/*echo 'ELSEIF ID: ' . $match->attributes()->id . $league->attributes()->country . " HOMEODDS: {$varhome} DRAW: {$vardraw} AWAYODDS: {$varaway} TYPE: {$typename} BOOK: {$fbooks} ID2: {$inhand}" . "<br>";
*/}
}
}
else{
foreach ($bookmaker->odd as $odd) { //daj kvote za svaki mec
if($typename == 'Home/Away'){
$typename = 'Draw No Bet';
}
switch ($odd->attributes()->name) {
case '1':
case '1X':
case 'Yes':
$homeodds = $odd->attributes()->value;
break;
case 'X':
case 'X2':
$drawodds = $odd->attributes()->value;
break;
case '2':
case '12':
case 'No':
$awayodds = $odd->attributes()->value;
break;
}
$id2 = 0;
//echo 'ID: ' . $match->attributes()->alternate_id_2 . $league->attributes()->country . " ODDS: {$homeodds} {$drawodds} {$awayodds} TYPE: {$typename} BOOK: {$fbooks} ID2: {$id2}" . "<br>";
}
/*
echo "ELSE HOME TEAM: {$hteam} <BR>";
echo "ELSE AWAY TEAM: {$ateam} <BR>";
*/
$this->execOdds($stmt, $fixid, $updateddate,
$typename, $fcountries,$league->attributes()->name,
$league->attributes()->id, $subid, $league->attributes()->cup,$sportname,
$hteam,$match->home->attributes()->id,
$ateam,$match->away->attributes()->id, $datetime, $dbdate,
$dbtime, $match->attributes()->status, $numodds,$homeodds,$drawodds,
$awayodds, $fbooks, $bookmaker->attributes()->id, $dbhandicap, $id2);
}
}
}
}
}
}
}
}
}
}
}
}
}
//echo $country.'<br>';
}
}
$this->PDO->commit(); //SAVE
$this->conn->close();
}
catch(Exception $e){
//echo $e;
}
}
private function execOdds($stmt, $matchid, $upddate, $type, $country, $league, $leagueid, $subid, $cup, $sport, $hteam, $hteamid, $ateam, $ateamid, $datetime, $date, $time, $status, $numodds, $homeodds, $drawodds, $awayodds, $book, $bookid, $handicap, $id2){
$event = $hteam . ' - ' . $ateam;
$fcountry = $country;
$fleague = $league;
$stmt->bindParam(':fixturematchid', $matchid);$stmt->bindParam(':updateddate',$upddate);$stmt->bindParam(':type',$type);
$stmt->bindParam(':country',$fcountry);$stmt->bindParam(':league',$fleague);$stmt->bindParam(':leagueid',$leagueid);
$stmt->bindParam(':subid',$subid);
$stmt->bindParam(':cup',$cup);$stmt->bindParam(':eventname',$event);$stmt->bindParam(':sportname',$sport);
$stmt->bindParam(':hometeam', $hteam);$stmt->bindParam(':hometeamid', $hteamid);$stmt->bindParam(':awayteam', $ateam);
$stmt->bindParam(':awayteamid', $ateamid);$stmt->bindParam(':datetime',$datetime);$stmt->bindParam(':date',$date);
$stmt->bindParam(':time',$time);$stmt->bindParam(':status',$status);$stmt->bindParam(':numodds', $numodds);
$stmt->bindParam(':homeodds', $homeodds);$stmt->bindParam(':drawodds',$drawodds);$stmt->bindParam(':awayodds',$awayodds);
$stmt->bindParam(':bookmaker',$book);$stmt->bindParam(':bookmakerid',$bookid);$stmt->bindParam(':handicap', $handicap);
$stmt->bindParam(':id2', $id2);
$stmt->execute(); //EXEC*/
}
I would like to add a count == 0 which if it is the case, just outputs 'please contact us to find out the dates', but I can't seem to get it to work. Please can someone advise?
$count = 0;
$your_repeater = get_field('add_date');
if ($your_repeater) {
while (have_rows('add_date')):
the_row();
$count++;
$my_field = get_sub_field('course_date');
if ($count == 0) {
echo 'please contact us to find out dates';
} else {
echo '';
}
if ($count == 1) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
// echo $my_field .', ';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>1. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo 'Contact us to find out more';
} else {
echo '';
}
}
if ($count == 2) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b>2. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
//echo '<img src="' .bloginfo('url').'/wp-content/themes/derbyskillbuild site/images/hourglass.png" />';
} else {
echo '';
}
}
if ($count == 3) {
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($my_field);
if ($expiration_date > $today) {
//echo $my_field .' ,';
$date12 = new DateTime($my_field);
$date13 = new DateTime($todays_date);
$diff = date_diff($date12, $date13);
echo '<b> 3. Starts on:</b> '.$my_field;
echo '<div class="reddays"> in '.$diff->format("%R%a days.").'<a href="'.get_page_link(
'10'
).'"> Contact us now</a></div>';
} else {
echo '';
}
}
if ($count == 4) {
}
if ($count == 5) {
}
echo '</ul>';
endwhile;
}
It appears that you are checking the count way too soon in your code.
You start with a $count = 0;, but then in the while loop you first do $count++. So, at this point, the count is 1. Then a few lines later you check this:
if ($count == 0) {
echo 'please contact us to find out dates';
}
This will never return true, since you just did a $count++ from 0, so at this point it's always at least 1. It seems that this check should be outside of your while loop and you're currently closing the loop way too late.
I'm trying to generate colours based on output of a csv (originally formatted ping).
I can get the values no problem,but the if, ifelse, else doesn't seem to be working.
if($min > 0.499 && $min <= 1) {$tcolor = $yellow;} elseif($min >= 1.0) {$tcolor = $red; } else { $tcolor = $white;}
if($avg > 0.499 && $avg <= 1) {$tcolor = $yellow;} elseif($avg >= 1.0) {$tcolor = $red; } else { $tcolor = $white;}
if($max > 0.499 && $max <= 1) {$tcolor = $yellow;} elseif($max >= 1.0) {$tcolor = $red; } else { $tcolor = $white;}
if($mdev > 0.499 && $mdev <= 1) {$tcolor = $yellow;} elseif($mdev >= 1) {$tcolor = $red; } else { $tcolor = $white;}
echo "<tr><td>$ip</td><td bgcolor=\"$tcolor\">$min<br>$tcolor</td><td bgcolor=\"$tcolor\">$avg<br>$tcolor</td><td bgcolor=\"$tcolor\">$max<br>$tcolor</td><td bgcolor=\"$tcolor\">$mdev</td></tr>";
Edit: As many asked about the colour code already, I have it above the code listed as
$yellow = "#FFFF66";
$red = "#FF0000";
$white = "#FFFFFF";
And the number I see the overlap, but I've also tried with 0.999 with the same result.
It sounds like you got it solved, but you should look at using functions like so, so you don't have to repeat if statements like you did.
<?php
function setCellColor($value){
$color = '#FFFFFF';
if($value >= 0.5 && $value <= 1){
$color = '#FFFF00';
} else if($value > 1) {
$color = '#FF0000';
}
return ' style="background: ' . $color . '" ';
}
echo '<tr><td>' . $ip . '</td><td ' . setCellColor($min) . '>' . $min . '</td><td ' . setCellColor($avg) . '>' . $avg . '</td><td ' . setCellColor($max) . '>' . $max . '</td><td ' . setCellColor($mdev) . '>' . $mdev . '</td></tr>';
?>
Check this out:
function build_td_with_style($value) {
switch (true) {
case $value > 0.5 && $value <= 1 :
$class = 'yellow';
break;
case $value > 1 :
$class = 'red';
break;
default :
$class = 'white';
}
return "<td class='{$class}'>{$value}</td>";
}
$tds = implode('', array_map("build_td_with_style", [$min, $avg, $max, $mdev]));
echo "<tr><td>{$ip}</td>{$tds}</tr>";
style.css :
.yellow {
background-color: yellow;
}
.red {
background-color: red;
}
.white {
background-color: white;
}
Here is my code,
if ($_SESSION["crossfit"]=="Y") { if ($_SESSION["tr_duration1"]==1) { $dr1="1 Month"; } else {
if ($_SESSION["tr_duration1"]==12) { $dr1="1 Year"; } else
{ $dr1=$_SESSION["tr_duration1"] . ' Months'; }} $c1='Crossfit - ' . $dr1;}
if ($_SESSION["muaythai"]=="Y") { if ($_SESSION["tr_duration2"]==1) { $dr2="1 Month"; } else {
if ($_SESSION["tr_duration2"]==12) { $dr2="1 Year"; } else
{ $dr2=$_SESSION["tr_duration2"] . ' Months'; }} $c2=', Muaythai - ' . $dr2;}
if ($_SESSION["mma"]=="Y") { if ($_SESSION["tr_duration3"]==1) { $dr3="1 Month"; } else {
if ($_SESSION["tr_duration1"]==12) { $dr3="1 Year"; } else
{ $dr3=$_SESSION["tr_duration3"] . ' Months'; }} $c3=', MMA - ' . $dr3;}
if ($_SESSION["gymnastics"]=="Y") { if ($_SESSION["tr_duration4"]==1) { $dr4="1 Month"; } else {
if ($_SESSION["tr_duration4"]==12) { $dr4="1 Year"; } else
{ $dr4=$_SESSION["tr_duration4"] . ' Months'; }} $c4=', Gymnastics - ' . $dr4;}
$for = $c1 . $c2 . $c3 . $c4 . '.';
At least one of the programs will be 'Y' or all of them.
What I want is that $c1 $c2 $c3 $c4 come out separated by ',' and ends with '.' so it becomes readable.
My problem is if I put
$for = $c1 . $c2 . $c3 . $c4 . '.'; and the ',' with $c1 and select programs 2 and 3
I get
$for = , Muaythai - 3 Months, MMA - 12 Months.
of course I want,
$for = Muaythai - 3 Months, MMA - 12 Months.
If I put ',' in the $for directly and remove from $c1 if 2nd and 3rd programs are selected
$for = $c1 . ',' . $c2 . ',' . $c3 . ',' . $c4 . '.'
I get
$for = ,Muaythai - 3 Months, MMA - 12 Months,.
I want
$for = Muaythai - 3 Months, MMA - 12 Months.
I have also tried putting nesting so many isset's but haven't succeeded.
I have also tried by making a 'for' loop but ended up with more syntax errors than output errors
It works fine only if I select only the first program or all the 4 programs.
Try something like this:
$tmp = array($c1,$c2,$c3,$c4);
$filtered = array_filter($tmp);
$for = implode(",", $filtered).".";
This will strip out any $c_ variables that aren't populated, and separate them with commas.
EDIT: I have reivewed your code, and would like to suggest this optimised version:
$keys = array("Crossfit","Muaythai","MMA","Gymnastics");
$result = array();
foreach($keys as $i=>$name) {
if( $_SESSION[strtolower($name)] == "Y") {
$duration = $_SESSION['tr_duration'.($i+1)];
switch($duration) {
case 1: $dur = "1 Month"; break;
case 12: $dur = "1 Year"; break;
default: $dur = $duration." Months";
}
$result[] = $name." - ".$dur;
}
}
if( !$result) $for = "Nothing selected!";
else $for = implode(", ",$result).".";
If you need help understand what's going on here, feel free to ask!
you can do it using single variable and concate values to it.
try like this:
for = "";
if ($_SESSION["crossfit"] == "Y") {
if ($_SESSION["tr_duration1"] == 1) {
$dr1 = "1 Month";
} else {
if ($_SESSION["tr_duration1"] == 12) {
$dr1 = "1 Year";
} else {
$dr1 = $_SESSION["tr_duration1"] . ' Months';
}
}
$for .= 'Crossfit - ' . $dr1;
}
if ($_SESSION["muaythai"] == "Y") {
if ($_SESSION["tr_duration2"] == 1) {
$dr2 = "1 Month";
} else {
if ($_SESSION["tr_duration2"] == 12) {
$dr2 = "1 Year";
} else {
$dr2 = $_SESSION["tr_duration2"] . ' Months';
}
}
$for .= empty($for) ? 'Muaythai - ' . $dr2 : ', Muaythai - ' . $dr2;
}
if ($_SESSION["mma"] == "Y") {
if ($_SESSION["tr_duration3"] == 1) {
$dr3 = "1 Month";
} else {
if ($_SESSION["tr_duration1"] == 12) {
$dr3 = "1 Year";
} else {
$dr3 = $_SESSION["tr_duration3"] . ' Months';
}
}
$for .= empty($for) ? 'MMA - ' . $dr3 : ', MMA - ' . $dr3;
}
if ($_SESSION["gymnastics"] == "Y") {
if ($_SESSION["tr_duration4"] == 1) {
$dr4 = "1 Month";
} else {
if ($_SESSION["tr_duration4"] == 12) {
$dr4 = "1 Year";
} else {
$dr4 = $_SESSION["tr_duration4"] . ' Months';
}
}
$for .= empty($for) ? 'Gymnastics - ' . $dr4 : ', Gymnastics - ' . $dr4;
$c4 = ', Gymnastics - ' . $dr4;
}
you should use switch case instead of many if else.