Make my div disappear if variable is empty? - php

Im making a form using PHP/HTML.
I have divided all my fields into divs, and i get all my values from a table from SQL server.
I want to make some divs disappear if the value im getting from the table is empty.
I know how to do it, but it just does not work if the variable is empty.
For example;
<div <?php if (empty($trabalhoSemCarteira)){?>style="display:none"<?php }?>>
<h2>Trabalho sem registro em carteira:</h2>
<div>
<label><?php echo $trabalhoSemCarteira;?></label>
</div>
</div>
This does not work,and i have no idea why.
On the other hand;
<div <?php if ($numeroFilhos<3){?>style="display:none"<?php }?>>
<label>Nome do Filho: <?php echo $nomeFilho3;?></label>
<label>Idade: <?php echo $idadeFilho3;?></label><br>
</div>
This one works like a charm. I'm doing exactly the same thing in both of them. I think the problem is with the ''empty'' function, I don't know, but that is literally the only difference.
EDIT:I have tried using ==null,is_null() instead of empty and nothing works.

I'm not super well versed with your database collection code, so I can't say with absolute certainty what the problem is. First off, as CBroe mentioned, use var_dump($trabalhoSemCarteira) to find what your variable actually is when you get nothing back. Then just key it into the if statement. Example:
<?php if($trabalhoSemCarteira === $a){?>style="display:none;"<?php }?>
Of course, $a is meant to be whatever var_dump($trabalhoSemCarteira) outputs.
Note: Please make you code cleaner. I actually couldn't really tell at first if the format would even work. Unless you're using the empty blocks for something else(such as displaying the blocks later with JS, in which case your approach makes absolute sense), to prevent you rendering unnecessary blocks of useless code, only render the block if the variable does exist. Example:
<?php if($trabalhoSemCarteira !== $a): ?>
<div>
<h2>Trabalho sem registro em carteira:</h2>
<div>
<label><?php echo $trabalhoSemCarteira;?></label>
</div>
</div>
<?php endif; ?>
Obviously, again, $a is whatever your var_dump($trabalhoSemCarteira) output.
Edit: I just read the notes and you say that it gives you an empty space. Replace $a in the examples with .

Make my div disappear if variable is empty?
You can approach this a different way and instead of using a conditional in PHP, you can use the
:empty
pseudo-class in CSS which applies styles to HTML elements which don't contain anything.
Working Example:
.outer-div {
display: inline-block;
margin-right: 12px;
width: 120px;
height: 120px;
background-color: rgb(255, 0, 0);
vertical-align: top;
}
.inner-div {
display: flex;
justify-content: center;
align-items: center;
width: 96px;
height: 96px;
margin: 12px;
text-align: center;
background-color: rgb(255, 255, 0);
}
.inner-div:empty {
opacity: 0;
}
<div class="outer-div">
<div class="inner-div">PHP String Variable Echoed Here</div>
</div>
<div class="outer-div">
<div class="inner-div">A</div>
</div>
<div class="outer-div">
<div class="inner-div"></div>
</div>
Further Reading:
https://developer.mozilla.org/en-US/docs/Web/CSS/:empty

Your value is not empty it contains a single blank space, the easiest way to check is by trimming the value before checking
<?php $trabalhoSemCarteira=" "; ?>
<div <?php if (empty(trim($trabalhoSemCarteira))){?>style="display:none"<?php }?>>
<h2>Trabalho sem registro em carteira:</h2>
<div>
<label><?php echo $trabalhoSemCarteira;?></label>
</div>
</div>
BTW, TIP: indeed, as Ruvee mentioned syntax you're using for generating your HTML with PHP is just messy and it is error-pron, use something cleaner pls:
<?php
$trabalhoSemCarteira=" ";
$clazz = (empty(trim($trabalhoSemCarteira))) ? 'none' : 'block';
?>
<div style="display: <?php echo $clazz ?>">
<h2>Trabalho sem registro em carteira:</h2>
<div>
<label><?php echo $trabalhoSemCarteira;?></label>
</div>
</div>
or even cleaner
<?php
$trabalhoSemCarteira=" ";
$clazz = (empty(trim($trabalhoSemCarteira))) ? 'none' : 'block';
echo "<div style='display: {$clazz}'>
<h2>Trabalho sem registro em carteira:</h2>
<div>
<label>{$trabalhoSemCarteira}</label>
</div>
</div>"
TIP2: If you're gonna build some larger project in the feature consider using some MVC framework and/or some template engine like i.e. Twig, Smarty or others.

Related

How to use echo and substr in one line? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
I need help. Basically I am trying to make a blog and I want to display some posts on main page but I dont know how to limit number of characters from content.
Here is my code:
<?php foreach($query as $q){ ?>
<div class="card" style="margin: 5px; width: 18rem;">
<div class="card-body">
<h5 class="card-title"><?php echo $q['title'];?></h5>
<p class="card-text"><?php echo $q['content'];?></p>
Read more...
</div>
</div>
<?php }?>
I tried this:
<?php foreach($query as $q){ ?>
<div class="card" style="margin: 5px; width: 18rem;">
<div class="card-body">
<h5 class="card-title"><?php echo $q['title'];?></h5>
<p class="card-text"><?php substr(echo $q['content'];,0, 50)?></p>
Čítaj ďalej...
</div>
</div>
<?php }?>
and much more solutions but it did not help.
Some help please?
I believe you want to set a max number of characters for some some text.
Change the style to select the number of lines you want to show. The -webkit-line-clamp: 4; will be responsible to tell the max number of lines you want to have:
<style>
.card-text{
width:100px;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
}
</style>
If you want the content in only one line:
<style>
.card-text{
display: inline-block;
max-width: 100px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
But if the goal is really to hide 100% the content from the user using your backend, the previous methods shown by the others using php substrig is enough.
You can do this:
$string = "Oi, eu sou o matheus. Texto adicional";
echo substr($string, 0, 2); // outputs Oi
echo substr($string, 4, 16); // eu sou o matheus
substr(echo $q['content'];,0, 50); is not going to output the data you want . (substr is a PHP function to get a part of a string say from position x and length y with the syntax substr($string, x, y))
Please change
<?php substr(echo $q['content'];,0, 50)?>
to
<?php echo substr($q['content'],0,50); ?>
Errors
The syntactic error when you added ; inside of the function.
Putting echo which returns void where substr expects a string.
Correction
<?= substr($q['content'],0, 50) ?>
Recommendation
You can shorten you PHP echo inside of the HTML templates using the short echo tag
<?= $a ?>
Which is equivelent to
<?php echo $a; ?>
Example
<?php
$content = "
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and Ipsum.
";
?>
<?= substr($content,0, 50) ?>
Test https://3v4l.org/HHbZQ
Here you go and if var not exists echo something random with ??
<?php
echo substr(($q['title'] ?? 'sometext'), 0, 30);
?>
And with a function to check or something else
<?php
echo substr(MYFUNCTION($q['title'] ?? 'sometext'), 0, 50);
?>

Loop echo CSS class by PHP

CSS
.number{
float:none;
background-color:white;
cursor:ponter;
}
#panel{
background-color:red;
height:200px;
width:100px;
overflow-y:scroll;
}
I want to make a list of number in a panel. I've tried with HTML
HTML
<div id="panel>
<span class="number">1</span>
<span class="number">2</span>
<span class="number">3</span>
<span class="number">4</span>
.....
<span class="number">50</span>
</div>
When <span> is clicked, something will appear by jQuery, but I have no problem with jQuery.
Because I thought that looping the number manually doesn't efficient, I tried to use PHP.
PHP
<?php
for($number=0;$number<=50;$number++){
echo "<span class='number'>".$number."</span>";
}
?>
But the number made by PHP doesnt do the same like HTML does.
This is what I want and done by HTML.
This is done with PHP and the numbers are made horizontally until 50
You need to make sure the same whitespace is present when looping through it in PHP:
<?php
for($number=0;$number<=50;$number++){
echo "<span class='number'>".$number."</span>\n";
}
?>
Remember, your original code is just outputting one long string:
<span class='number'>1</span><span class='number'>2</span>...
In this case, whitespace (A newline) is important which may alter how your CSS looks. Forcing a new line each time you echo out a <span> by adding \n should fix this.
.number{ display : inline-block; }

Styling PHP with CSS

Sorry if this is a bit dumb but I have never dabbled with PHP before.
Basically I am using a premium wordpress theme called Kingsize, which is beautiful but does not have the author displayed on a post. I have managed to get it in there, on the individual post (by editing single.php) and the post list (loop.php).
I guess I did that sort of right because it is appearing in there. Problem is in both instances it is on the line beneath the date and I want it on same line:
http://bathastronomers.co.uk/category/bath-astronomers/
I thought I could figure it out if I found "post_date" in the style.css but it doesn't appear to be there!
Also, I want rid of the little icons before date and author.
Any ideas?
Here's the relevant code in single.php:
<?php
if( $data['wm_date_enabled'] == '1' ) { //data is enabled
?>
<div class="metadata">
<p class="post_date"><?php the_time(get_option('date_format'));?></p>
<p class="post_author"><?php the_author(); ?></p>
</div>
<?php}
?>
Change it to:
<div class="metadata">
<p>
<span class="post_date"><?php the_time(get_option('date_format'));?></span>
<span class="post_author"><?php the_author(); ?></span>
</p>
</div>
If you want the author to appear on the same line as the Date, add this to your style.css :
.post .metadata p.post_date {
float:left;
}
If you want to hide the small icon on the left, modify the following :
.post .metadata p {
padding: 0px 0px 0px 25px;
background: url("images/calendar.png") no-repeat scroll left -1px transparent;
}
For the following :
.post .metadata p {
padding: 0px;
}
Note that you don't "style PHP". You style HTML. To put it simply, PHP is a HTML generator.

Facebook like button ignore URL parameters

I'm trying to like my page but the url parameters are ignored
Here is my code:
<style type="text/css">
.float-all {
float: left;
width: 82px;
height: 30px;
overflow: hidden;
margin: 2px;
padding: 4px 2px;
}
.post-btn-share {
width: 100%;
overflow: auto;
}
<link rel="canonical" href="http://mypage.com/view_photo.php" />
</head>
<div class="post-btn-share">
<div class="addthis_toolbox addthis_default_style">
<div class="float-all">
<iframe src="http://www.facebook.com/plugins/like.php?href=http://mypage.com/view_photo.php? img=32&user=1&xx=&send=true&layout=standard&width=300&show_faces=true&action=like&colorscheme=light&font&height=80" frameborder="0" style="border:none;" scrolling="no" width="320" height="240"></iframe>
<div class="float-all">
</div>
<div class="float-all">
</div>
</div>
And view_photo code
<?php
session_start();
?>
<div class="dev-ajuste">
<?php
require_once('script/require_raiz.php');
$login = new login();
$login->log_isset();
//$login->info_user();
$janela = new Janelas('script/system/config.ini','perfil');
$janela->info_visualiza_foto($_GET['img'],$_GET['user']);
?>
</div>
<!--=======Cabeçalho e chamadas de scripts do documento=======-->
<?php include_once("head.php"); ?>
<!--=======Barra de navegação=======-->
<?php include_once("navbar.php"); ?>
<div id="janela" class="perfil"></div>
<div id="info" class="<?php echo $_GET['user'];?>"></div>
<!--=======Header=======-->
<?php include_once('box_foto.php'); ?>
<!--=======Propaganda=======-->
<?php include('addsense.php');?>
<!--=======Área dos posts=======-->
<?php include('post_area.php');?>
<!--=======Rodapé do documento=======-->
<?php include_once("footer.php"); ?>
<!--=======Seguranca de Login=======-->
(Turning a comment chain into a potential answer)
I really don't think you've understood. Look at the URL being used in the iframe:
http://www.facebook.com/plugins/like.php?href=http://mysite.com/view_photo.php?img=34&user=1&xx=&;send=true&;layout=standard&;width=300&;show_faces=true&;action=like&;colorscheme=light&;font&;height=80
In a URL, parameters being sent to the resource start at the ? character. But you have two ? characters. Do the parameters start at the first one or the second one? A parser has no way to know. When a & is encountered, is that separating a parameter for the outer URL (the first ?), or one being enclosed with the inner URL (the second ?)? A parser has no way to know.
The format needs to be like this:
http://someresource?parameter1&parameter2&etc
If one of those parameters is also a URL with its own parameters, that entire parameter needs to be URL-encoded so it doesn't confuse the rest of the URL for which it's being used as a parameter. Any parser has to be able to clearly identify what goes with the inner-URL and what goes with the outer-URL. It will URL-decode the inner one for you when it needs to use it.
PHP provides a function to do this. So does JavaScript. You can use whichever you'd like. All you do is pass it the string to be encoded (which would be your inner URL with whatever parameters need to go to that URL) and it will return the encoded string (which would be the parameter to send to your outer URL).
(Also, why do you have all those semi-colons? You don't separate URL parameters with semi-colons. I'm not sure where you got that idea.)
Go to this page and check the link of the like button which is show in the picture below:
You right click and inspect it. You see:
You see that it is urlencode'd. And the reasoning is very well explained by David :)

how to generate html with php to return after ajax call

I generate all my html on my page with ajax calls and never refresh my page. My setup is something like
HTML: <a id="user_click_here">test link</a>
JQUERY:
$("#user_click_here").live("click", function(event){
console.log("click on test link");
ajax_function("action=return_some_html");
});
The ajax function calls php, where I create the html. What I struggle with is to generate html with php. I try to use this:
PHP:
$html = <<<HTML
<div class="box">
<h2>
$text[0]
</h2>
<div class="block">
<div style="float:left; width: 35%; margin:5px; padding: 1em; background: white;">
HTML;
$html .= '<p>Username: <a id="username">' . $_SESSION['username'] . '</a></p>';
$html .= <<<HTML
<div style="float:left; width: 30%; margin:5px;">
<p>
Level:<br />
Weapon:<br />
Power:<br />
Bullets:<br />
</p>
</div>
<div style="float:right; width: 60%; margin:5px;">
<p>
HTML;
$html .= '<b id="level">empty</b><br/>';
$html .= <<<HTML <---ERROR HERE unexpected '<<'
Weapon blabla<br />
2 - 5<br />
3/6<br />
</p>
</div>
</div>
I tend to just try and fail until it works with this <<<WHATEVER (dont remember what it's called). Like now where I get an unexpected '<<' error for some reason.
Do I have to use this method:
$html = '<div class="box">
<h2>
' . $text[0] . '
</h2>
<div class="block">
<div style="float:left; width: 35%; margin:5px; padding: 1em; background: white;">';
?
What is the best way to save html in php and send it back to jquery.
I send the html like this now:
PHP:
$data = array("html" => $html);
return json_encode( $data );
Off course I want it compressed as much as possible, preferably without any stuff like this: \n\t\t\t\t to take up space.
EDIT:
Ok. I don't think everybody noticed the fact that this is an ajax call and I have to return a json element. I cannot do the common <?php php code ?> html code <?php more php ?> some html
It looks like your last HEREDOC (that's what the <<< syntax is called) is unclosed, missing it's
HTML;
And don't forget that the final HTML; cannot have any whitespace on the same line before or after it.
However, you're going about it all wrong. The great thing about the HEREDOC syntax is that you can embed all your variables into it without requiring any concatenation. Just create the whole thing in one HEREDOC and echo it out to jQuery. There's no need to make it JSON if you are just going to use it as HTML when received by the AJAX call.
All your code above belongs inside one $html = <<<HTML block. Enclose all your complex variables like $_SESSION['whatever'] in {} {$_SESSION['whatever']}.
$html = <<<HTML
<div class="box">
<h2>
{$text[0]}
</h2>
<div class="block">
<div style="float:left; width: 35%; margin:5px; padding: 1em; background: white;">
<p>Username: <a id="username"> {$_SESSION['username']}</a></p>
<div style="float:left; width: 30%; margin:5px;">
<p>
Level:<br />
Weapon:<br />
Power:<br />
Bullets:<br />
</p>
</div>
<div style="float:right; width: 60%; margin:5px;">
<p>
<b id="level">empty</b><br/>
<!--etc -->
<!--etc -->
HTML;
// Now just echo it back to the AJAX caller as HTML
echo $html;
exit();
Don't use HEREDOC. It's messy, and should only be used when you need to store long strings in a variable.
Try writing out the HTML page you expect to be returned as if it was a normal HTML page. Where you need PHP output (a variable, array value, etc.), begin a PHP tag, echo the value, and then end the PHP tag. This is much easier than trying to use heredoc.
<div class="box">
<h2><?php echo $text[0]; ?> </h2>
<div class="block">
<div style="float:left; width: 35%; margin:5px; padding: 1em; background: white;">
<p>Username: <a id="username"><?php echo $_SESSION['username']; ?></a></p>
<div style="float:left; width: 30%; margin:5px;">
<p>Level:<br />Weapon:<br />Power:<br />Bullets:<br /></p>
</div>
<div style="float:right; width: 60%; margin:5px;">
<p><strong id="level">empty</b><br />Weapon blabla<br />2 - 5<br />3/6<br /></p>
</div>
</div>
If you're worried about line breaks (you shouldn't be), you can add an output handler that removes them.
ob_start("clean_linebreaks");
function clean_linebreaks($input) {
return str_replace("\n", "", str_replace("\r", "", $input));
}
Also, may I suggest using tables instead of floated divs. The level, weapon, and power will be easier to line up with their values if you use a table.

Categories