change value of variable based on conditions php - php

I have a class name that should change based on certain conditions but either my syntax or my logic seems to be incorrect as it doesn't work:
if ( $hometeam && ($homescore > $awayscore) || $awayteam && ($awayscore > $homescore)){
$status= 'win';
}
if ( $hometeam && ($homescore < $awayscore) || $awayteam && ($awayscore < $homescore)) {
$status= 'lose';
}
if ($homescore == $awayscore) {
$status= 'draw';
}
My elements each have a class="<?php echo $status; ?>" and I want them to be styled differently depending on the value of $status. I didn't use else if because I didn't want it to apply the value and stop but it looks like that is what is happening.
Edit: Some clarification:
<ul class="match group">
<li>
<ul class="team1 <?php echo $status; ?>">
<li class="teamname"><h2><?php echo $homename; ?></h2></li>
<li class="teamscore"><?php echo $homescore; ?></li>
</ul>
</li>
<li>
<ul class="team2 <?php echo $status; ?>">
<li class="teamname"><h2><?php echo $awayname?></h2></li>
<li class="teamscore"><?php echo $awayscore?></li>
</ul>
</li>
<li><ul class="matchinfo">
<li><button>Get Report</button></li>
</ul>
</li>
</ul>

By your logic, there are only two possible outcomes for the value of $status: 'lose' or 'draw'.
Why is this? Basic logic says that unless there is a tie, a game will always have a winner. Your if statement lines up with this. Either $homescore > $awayscore or $homescore < $awayscore (or there is a tie). So in the event of a non-tie, one of the sides of your first if will evaluate to true, and therefore the entire condition will be true since || needs only one truthy. So unless there is a tie, $status will be set to 'win'.
Moving on, basic logic will also tell us that a game always has a loser unless there is a tie. Again, your code conforms to this. In the event of a non-tie, one of the score will be less than the other and therefore your second if will evaluate to true like the first did. Now $status = 'lose'.
Now if there is a tie, $status would equal 'draw', but otherwise $status will always be 'lose' because if the game has a winner, it also has a loser and $status is set to 'lose' after it is set to 'win'.
What you need here is a variable for the winner, loser, and for a draw. Like so:
$winner = '';
$loser = '';
$draw = false;
if($homescore > $awayscore) {
$winner = 'home';
$loser = 'away';
} else if($homescore < $awayscore) {
$winner = 'away';
$loser = 'home';
} else if($homescore === $awayscore) {
$draw = true;
}
(Codepad Demo)
This code also makes use of else if, because you don't need to evaluate the other conditions if you've determined who won and lost.

You need to group your conditions better.
if ( ($hometeam && ($homescore > $awayscore)) || ($awayteam && ($awayscore > $homescore)))
{
$status= 'win';
}
else if ( ($hometeam && ($homescore < $awayscore)) || ($awayteam && ($awayscore < $homescore)))
{
$status= 'lose';
}
else
{
$status= 'draw';
}

if ($homescore > $awayscore) {
$homestatus = 'win';
$awaystatus = 'lose';
} else if ($homescore < $awayscore) {
$homestatus = 'lose';
$awaystatus = 'win';
} else {
$homestatus = 'draw';
$awaystatus = 'draw';
}
<ul class="match group">
<li>
<ul class="team1 <?php echo $homestatus; ?>">
<li class="teamname"><h2><?php echo $homename; ?></h2></li>
<li class="teamscore"><?php echo $homescore; ?></li>
</ul>
</li>
<li>
<ul class="team2 <?php echo $awaystatus; ?>">
<li class="teamname"><h2><?php echo $awayname?></h2></li>
<li class="teamscore"><?php echo $awayscore?></li>
</ul>
</li>
<li><ul class="matchinfo">
<li><button>Get Report</button></li>
</ul>
</li>
</ul>

Related

reducing number of php pagination links to 10

Ive been building a data driven website displaying general info about countries in the world. Its been made so that 1 country is displayed per page and you can move the next country by clicking a pagination link. Only problem that I am having is I cannot limit the amount of visible links. I did try this for loop with the first line as this: for ($i = $Page; $i <= min($Page + 9, $TotalRecords); $i++) { which does reduce it to the 10 records however this does result in the website breaking when I test the web address by entering index.php?page=aa.
<nav class="mt-5">
<ul class="pagination pagination-lg justify-content-center">
<?php
if( isset($Page) ) {
if ($Page > 1 ) {
?>
<li class="page-item">
«
</li>
<?php
}
}
?>
<?php
global $ConnectingDB;
$sql = "SELECT COUNT(*) FROM countriesinfo";
$stmt = $ConnectingDB->query($sql);
$RowPagination = $stmt->fetch();
$TotalRecords = array_shift($RowPagination);
$RecordPagination = $TotalRecords / 1;
$RecordPagination = ceil($RecordPagination);
for ($i = $Page; $i <= $RecordPagination; $i++) {
if( isset($Page) ) {
if ($i == $Page)
{
?>
<li class="page-item active">
<?php echo $i; ?>
</li>
<?php
} else {
?>
<li class="page-item">
<?php echo $i; ?>
</li>
<?php
}
}
}
?>
<?php if (isset($Page) && !empty($Page) ) {
if ($Page+1 <= $RecordPagination) {
?>
<li class="page-item">
»
</li>
<?php
}
}
?>
</ul>
</nav>
I test the web address by entering index.php?page=aa.
You can check to make sure the get variable is a number by using php is_numeric() bulit in function
and if it isn't force it to number 1.
This will stop the website from breaking when someone manipulate the page varible.
Here is a code to help you out, put at the beginning of the page.
if(is_numeric($page)){
$page = $page; // if $page is a number do nothing
}else{
$page = 1; //else set $page to 1 which will fetch data from beginning
}

Explode and Set if condition php

Array ( [0] => 1 [1] => 2 )
I'm trying to set an if condition based on user permission, the idea is to show menu based on given values, if it is 1, one menu will be displayed and 2 second menu will be displayed, if its both then all values will be displayed. So far for single values i have gotten it right but how to do it for array of values
This is my code
<?php
$userid = $this->phpsession->get("user_id");
$userrole = $this->phpsession->get("user_type");
$query = $this->db->select("role_empid,role_permissions")->from('hw_role')->where('role_empid', $userid)->get()->result();
$data = $query[0]->role_permissions;
if($data == 1){
?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }else if($data == 2){ ?>
<li>Request For Proposal</li>
<?php } ?>
</ul>
if role_permission contain json object that first convert it into the array like
$data = $query[0]->role_permissions;
$data=json_decode($data);
otherwise direct check the condition for
$data = $query[0]->role_permissions;
if(in_array(1,$data) && in_array(2,$data))
{
}
else if(in_array(1,$data))
{
}
else if(in_array(2,$data))
{
}
If $query[0]->role_permissions is an array that has distinct value, then you can try :
<ul>
<?php for($i = 0; $i<count($data);$i++) {
if($data[$i] == 1){ ?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }
if($data[$i] == 2){ ?>
<li>Request For Proposal</li>
<?php }} ?>
</ul>
Try This
<?php
if(in_array(1,$data)){
?>
<li>Add Enquiry</li>
<li>Enquiry List</li>
<?php }
if(in_array(2,$data)){
?>
<li>Request For Proposal</li>
<?php } ?>

For loop is making 3600 database requests to load Products. PHP

Problem: One piece (That we can identify currently) is causing a clients product list to call the database over and over again (3600 times) at points when loading a longer list of products.
Code:
<?php foreach ($cats as $cat) :
if (in_array($cat->getId(), [68, 28, 27, 59, 79, 80, 119])) :
$cat_show = Mage::getModel('catalog/category')->load($cat->getId());
$children = $cat_show->getChildrenCategories($cat->getId());
$url1 = $cat_show->getURL();
$showAnyways = in_array(strtolower($cat_show->getName()), ["hats", "juniors", "accessories"]);
if ($cat_show->getShowSidebar() == 1 || $showAnyways) : ?>
<li class="current<?php if ($cat->getId() == $current_cat) { ?> active <?php } ?>">
<?php echo $cat->getName() ?>
<ul>
<?php if ($cat_show->getID() != 68 && $cat_show->getID() != 59) { ?>
<li class="current<?php if ($cat->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>"><a class="view_all" href="<?php echo $url1 ?>"><?php echo $this->__("View All"); ?></a></li>
<?php } ?>
<?php foreach ($children as $subcat) {
$subcat_show = Mage::getModel('catalog/category')->load($subcat->getId());
if ($subcat_show->getShowSidebar() == 1 || in_array($subcat_show->getID(), [84])) {
$grand_children = Mage::getModel('catalog/category')->getCategories($subcat->getId());
if ($grand_children) {
$cats_displayed = 0;
foreach ($grand_children as $grand_child) {
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$url = Mage::getModel('catalog/category')->load($grand_child_show->getId())->getURL();
?>
<li class="current<?php if ($grand_child->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>">
<?php echo $grand_child_show->getName() ?>
</li>
<?php $cats_displayed++;
}
}
}
if ($cats_displayed == 0 || !$grand_children) {
$url = Mage::getModel('catalog/category')->load($subcat->getId())->getURL();
?>
<li class="current<?php if ($subcat->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>">
<?php echo $subcat->getName() ?>
</li>
<?php }
}
} ?>
</ul>
</li>
<?php endif;?>
<?php endif;?>
<?php endforeach; ?>
Can anyone provide me with some pointers on how to make this FAR more efficient and not make so many DB calls.
Should note, I am not an amazing php developer by trade. Main language is python so I am trying to get some advice on the best way to go about fixing this given my less that great knowledge of php itself.
You should never have a database query call inside a for loop. You need to build a query at the start that will get all the data required before the for loop.
Some instant pointers I can see are:
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$url = Mage::getModel('catalog/category')->load($grand_child_show->getId())->getURL();
This is calling the database twice for no reason, you should be able to do this:
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$grand_child_show->getURL();
You should be able to drop all these 'GetModel' functions if at the start of the script you call something like:
$all_grand_children = Mage::getModel('catalog/category')->getAllCategories();
This would return a hash array which you would be able to access relevant items by doing the following inside the for loop:
$grand_children = $all_grand_children[$subcat->getId()];
This would replace
$grand_children = Mage::getModel('catalog/category')->getCategories($subcat->getId());
You should also do a initial call for all of the grand_child and cat_show objects. If you are skilled at SQL you can call just the relevant information by joining the tables in one SQL query.

how to apply class according to the filename?

i have created an application where i want to apply active class on active page. Like if fike name starts with me_ then how can i apply class "active" to it.
here is my code:
$pageAttr = basename($_SERVER['REQUEST_URI']);
$files = array("me_dashboard.php","me_my_team.php","me_others.php","me_inbox.php","me_outbox.php");
<li class="<?php echo($pageAttr == $files[0] || $pageAttr == $files[1] || $pageAttr == $files[2] || $pageAttr == $files[3] || $pageAttr == $files[4]) ? "active":"" ?>"><i class="icon-user icon-large"></i> Me</li>
this is not correct code to use. Please suggest me some other ways to achieve the solution in PHP.
If you have array of files like this
$files = array("me_dashboard.php",
"me_my_team.php",
"me_others.php",
"me_inbox.php",
"me_outbox.php"
);
Than you can use in_array() like
<li class="<?php echo (in_array(basename($_SERVER['PHP_SELF']), $files) ? 'active' : '')?>">
It will be even better if you port the class= attribute in the if condition as well, so that you do not get an empty class="" markup.
If you want to refactor your code more, consider porting entire code in a function, and then return the value if condition goes true.
As commented, you wanted to fetch the prefix of the file than you can use substr()
<?php
$page_name = 'me_dashboard.php';
$fetch_prefix = substr($page_name, 0, 3);
echo $fetch_prefix;
?>
<li class="<?php echo (($fetch_prefix == 'me_') ? 'active' : '')?>">A</li>
Demo - Code
you can try this one
<?php
$pageAttr = basename($_SERVER['REQUEST_URI']);
$files = array("me_dashboard.php","me_my_team.php","me_others.php","me_inbox.php","me_outbox.php");
foreach($files as $file)
{
$class_text = "";
if($file==$pageAttr)
{
$class_text = ' class="active" ';
}
?>
<li <?php echo $class_text;?> ><i class="icon-user icon-large"></i> Me</li>
<?php
}
?>

foreach() executing same line again and again

I have a sql field wehre values are like
1,2,3,4,5,6
if fetch those values and explode them below
$amenities = 1,2,3,4,5,6
$amenities_check = explode( "," , $amenities );
Then I run a foreach loop
<?php
$i = 1;
foreach($amenities_check as $amenities_conf)
{
if( $amenities_conf != "" && $amenities_conf == 6)
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
if ($i++ == 1) break;
}
?>
Now the problem is that this loop is display the same line 6 times and display the correct class of li when it meets the 6 digit in the data if i apply $i++ it only check the first data in the dataset.
Any help that foreach look for the desired values like 1 2 3 and do the function according to it ..
Thanks
Is this what you are looking for?
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else {
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
}
?>
EDIT:
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
}
?>
<li class="not_amen">Smoking Allowed</li>
or like the guys above said, use in_array().
<?php
if (in_array("6", $amenities_check)) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
?>
<li class="not_amen">Smoking Allowed</li>
From the comments, what you actually want to know is if there is a 6 anywhere in the array, so you don't want to be outputting anything at all in the loop. The simplest approach is to use the fairly self-explanatory in_array function; as simple as this:
if( in_array('6', $amenities_conf) )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
Alternatively, break apart your logic from your display by looping through the database result once and preparing structured data based on it. The below is probably over-kill for this example, but shows a general approach:
// While retrieving data from the DB
$amenity_names = array(
1 => 'pets',
// ...
6 => 'smoking'
);
$included_amenities = array();
$amenities_check = explode( "," , $amenities );
foreach ( $amenities_check as $amenity )
{
$name = $amenity_names[$amenity];
$included_amenities[$name] = true;
}
// In the View / template code
if( $included_amenities[['smoking'] )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}

Categories