I'm using multiple if statements to check a containing div, and output an image based on the container name. The code was working fine until I add a final "else" or change the if's out to elseif and I can't figure out why that's happening. When I try to add the else or elseif, the entire page fails to load. Any idea why this is happening?
<?php
if($viewMore['container_type'] == 'Large IMG' || $viewMore['container_type'] == 'Gallery') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'large_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$large = 0; foreach ($photoArray as $photo => $upload): if (++$large == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach ?>
<?php } ?>
<?php
elseif($viewMore['container_type'] == 'Medium IMG') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'small_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$medium = 0; foreach ($photoArray as $photo => $upload): if (++$medium == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach; ?>
<?php } ?>
<?php else { ?> SOMETHING HERE <?php } ?>
EDIT:
Other notes
I've tried wrapping the break; in brackets because I thought that piece following the count might be messing with something. Also removing the counter altogether or adding a semi colon after the endforeach didn't help.
Whenever you close your PHP block, think about all the text/HTML outside it being put into PHP's echo function.
What gave me alarm bells was this part:
<?php } ?>
<?php else { ?> ...
What that translates into is:
if (...) {
} echo "[whitespace]"; else {
}
which clearly makes your else block unexpected.
You should not close the PHP block between your closing if and opening else, i.e. do this instead:
...
} else {
...
Related
I am having a problem in adding the product as a variable with variations. I am trying to add accessories on every product page but its working for simple product and is creating the problem in a variable or with variations
i tried to solve this
//this variable code is not working//
<?php if($currentProduct->get_type() == "variable"){ ?>
var varRules = $(".variations_form").data('product_variations');
<?php foreach($currentProduct->get_attributes() as $k=>$v){ ?>
var attribute_<?= getVar($k) ?> = $("select[name=attribute_<?= $k ?>]").val();
<?php } ?>
$.each(varRules,function(){
<?php
$cond = [];
foreach($currentProduct->get_attributes() as $k=>$v){
$cond[] = '(this.attributes["attribute_'.$k. '"]=='. 'attribute_'.getVar($k).' || this.attributes["attribute_'.$k. '"]=="")';
} ?>
if(<?=implode(" && ", $cond)?>){
total = this.display_price;
}
});
//not even this grouped one//
<?php } else if($currentProduct->get_type() == "grouped"){ ?>
var total = 0;
<?php foreach($currentProduct->get_children() as $k=>$id){ ?>
total += $("[name='quantity[<?= $id ?>]']").val() * <?= getPrice(wc_get_product($id)); ?>;
<?php } ?>
<?php } else { ?>
total = parseFloat(<?= getPrice($currentProduct) ?>);
<?php } ?>
i want it to work for variable products
As it seems that you are using php inside some jQuery code, there are some errors like:
Your php opening tags should all be always like <?php but not like <?=
When you want to display something like a variable from php in jQuery, dont forget echo
Dont forget missing ; before your closing php tags.
I have revisited your code, but nobody can test it as it's an extract with missing things and the context is also missing from your question.
<?php if($currentProduct->get_type() == "variable"){ ?>
var varRules = $(".variations_form").data('product_variations');
<?php foreach($currentProduct->get_attributes() as $k => $v){ ?>
var attribute_<?php echo getVar($k); ?> = $("select[name=attribute_<?php echo $k; ?>]").val();
<?php } ?>
$.each(varRules,function(){
<?php
$cond = [];
foreach($currentProduct->get_attributes() as $k=>$v){
$cond[] = '(this.attributes["attribute_'.$k.'"]=='. 'attribute_'.getVar($k).' || this.attributes["attribute_'.$k.'"]=="")';
} ?>
if(<?php echo implode(" && ", $cond) ?>){
total = this.display_price;
}
});
//not even this grouped one//
<?php } else if($currentProduct->get_type() == "grouped"){ ?>
var total = 0;
<?php foreach($currentProduct->get_children() as $k=>$id){ ?>
total += $("[name='quantity[<?php echo $id; ?>]']").val() * <?php echo getPrice(wc_get_product($id)); ?>;
<?php } ?>
<?php } else { ?>
total = parseFloat(<?php echo getPrice($currentProduct); ?>);
<?php } ?>
On my custom search results page I have a line that displays what category and price. The code I'm using is
Displaying results for <?php echo $_POST['category_name']; ?>
The output for this code is "Displaying results for 18120".
I'm looking to display the word "Audio" rather than "18120", as well as about 10 other categories.
My current attempt, shown below, is not working properly.
<?php $cat = $_POST['category_name']; ?>
<?php if ($cat == 18120) echo 'Audio';
elseif ($cat == 18121) echo 'Television';
?>
In the else/if, store the new name, rather than echoing it. Then use that variable in your display:
<?php $cat = $_POST['category_name']; ?>
<?php if ($cat == 18120) $cat = 'Audio';
elseif ($cat == 18121) $cat = 'Television';
?>
Displaying results for <?php echo $cat; ?>
To save aload of else and if why not use the good old switch and case?
switch ($_POST['Category_name']){
case 18120:
$Cat = "Audio";
break;
case 18121:
$Cat = "Television";
break;
case 18122:
$Cat = "Something Else";
break;
}
echo $Cat;
Use get_category() wordpress function:
<?php
$catCode = $_POST['category_name'];
if(is_numeric($catCode)) {
$cat = get_category($catCode);
echo $cat->name;
} else {
echo $catCode;
}
?>
Enjoy your code!
I having issues getting a function to echo, where $lightbox_link1 = get_custom_field('lightbox_link1'). I'm fairly new to PHP.
Below is the defining function:
// Check for a lightbox link, if it exists, use that as the value.
// If it doesn't, use the featured image URL from above.
if(get_custom_field('lightbox_link1')) {
$lightbox_link1 = get_custom_field('lightbox_link1');
} else {
$lightbox_link1 = $image_full[0];
}
Echo Function:
<?php if ($lightbox_link1 = get_custom_field('lightbox_link1')) {
echo '';
} ?>
<?php if ($lightbox_link1 = get_custom_field('lightbox_link1')) {
should be
<?php if ($lightbox_link1 == get_custom_field('lightbox_link1')) {
= is used for assignment
== is used for comparison
=== is used for typesafe comparison
also you can't declare <?php ... ?> inside another <?php ... ?>
to get something like <?php ... <?php ... ?> ... ?>
take a look at what you did up to here:
<?php if ($lightbox_link1 = get_custom_field('lightbox_link1')) {
echo '<a href="<?php
Instead, using doublequotes in your echo statement will allow for the php variables inside to be parsed, so you could just do
echo "<a href='{$lightbox_link1}' data-rel='prettyPhoto[{$post_slug}]'></a>";
to get
<?php if ($lightbox_link1 == get_custom_field('lightbox_link1')) {
echo "<a href='{$lightbox_link1}' data-rel='prettyPhoto[{$post_slug}]'></a>";
} ?>
Im attempting to create a simple list out of some elements I stole from a more complex list of rows etc., I just need list out the values in single row separated by commas.
<?php foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
;} ?>
;} ?>
<?php } ?>
The Result I get follows "3 ;} ?> 3 ;} ?> 4 ;} ?> 3 ;} ?> "
Thanks in advance
Micah
try this
<?php
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
}
}
?>
Fore more detail PHP Tags
Change the #9, #10, remove #11 line. What you're doing is printing characters: ;} ?>
and are syntactically wrong. This is proper:
<?php foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
} // here
} // here
?>
Also for the "comma separated" part, put required values in a variable and echo it at the end.
Could be like this:
<?php
$string = '';
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
$string .= nbf_common::nb_strlen($document_item->product_code).',';
}
}
}
echo rtrim($string, ','); // remove the last comma
?>
or use a temp array to glue them at the end:
<?php
$lines = array();
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
$lines[] = nbf_common::nb_strlen($document_item->product_code);
}
}
}
echo implode(',', $lines); // bind them with comma
?>
I'm not sure why you have all those extra ?>. The pattern is:
<?php
// PHP code goes here
?>
i.e. every <?php has a matching ?>; no more, no less.1
1. Other than the case that #Mihai points out in the comment below...
To understand the php tags you might want to think that you are in an HTML file and you are intrerrupting the HTML flow with
When writing PHP only files (classes, interfaces, traits lists of functions and similar grouping of application code with no templating) it is advisable to open at the very first character in the file and not end it at all.
When writing template files however it is advisable to use php's alternate syntax:
<?php if($x): ?>
<?php elseif($y): ?>
<?php else: ?>
<?php endif; ?>
Instead of the standard:
<?php if($x) { ?>
<?php } else if($y) { ?>
<?php } else { ?>
<?php } ?>
How can I write the following statement in PHP:
If body ID = "home" then insert some html, e.g.
<h1>I am home!</h1>
Otherwise, insert this html:
<p>I'm not home.</p>
Doing it with native PHP templating:
<?php if ($bodyID==='home') { ?>
<h1>I am home!</h1>
<?php } else { ?>
<p>I'm not home!</p>
<?php } ?>
You can try using this :
$html = '';
if ( $body_id === 'home' )
{
$html .= '<h1>I am home!</h1>';
}
else
{
$html .= '<p>I\'m not home.</p>';
}
echo $html;
This will echo the html code depending on the $body_id variable and what it contains.
You can use a switch command like so:
switch($body)
{
case 'home': //$body == 'home' ?
echo '<h1>I am home!</h1>';
break;
case 'not_home':
default:
echo '<p>I'm not home.</p>';
break;
}
The default means that if $body does not match any case values, then that will be used, the default is optional.
Another way is as you say, if/else statements, but if within template / view pages you should try and use like so:
<?php if ($body == 'home'):?>
<h1>I am home!</h1>
<?php else:?>
<p>I'm not home!</p>
<?php endif; ?>
Assuming $bodyID is a variable:
<?php
if ($bodyID==='home') {
echo "<h1>I am home!</h1>";}
else {
echo "<p>I'm not home!</p>";}
?>
Personally I think that the best way to do that without refreshing and without having to set a variable (like $body or something like that) is to use a javascript code, this because "communications" between JS & PHP is a one-way communication.
<script language="javascript">
<!--
if( document.body.id === "home" ){
window.document.write("<h1>I am home!</h1>") ;
}
else{
window.document.write("<p>I'm not home!</p>") ;
}
-->
</script>
otherwise you can build a form and then take the body.id value using $_GET function... It always depends on what you've to do after you now body.id value.
Hope this will be usefull & clear.
you can try in the following way:
$body_id = "home";
if ($body_id == "home") {
echo "I am home!";
} else {
echo "I am not home!";
}
or
$body_id = "home";
if (strcmp($body_id, "home") !== 0) {
echo 'I am not home!';
}
else {
echo 'I am home!';
}
Reference:
https://www.geeksforgeeks.org/string-comparison-using-vs-strcmp-in-php/