简体   繁体   English

如果值为空,则不显示任何内容

[英]if value is empty display nothing

On one file I have this code: 在一个文件中,我有以下代码:

if (theForm.lqd_9.value == "")
{
    alert("You have forgotten to specify - Description!");
    theForm.lqd_9.focus();
    return (false);      
    <tr>
       <td class="theadingt" align="center" height="14" width="180">
             <b>Description:<span lang="en-us"><font color="#ff0000">*</font></span></b></td>
        <td class="theading" align="left" height="14" width="545">
    <textarea cols='48' rows='6' name="lqd_9"></textarea></td>
   </tr>

and on the receiving file I have this: 在接收文件上我有这个:

<?php echo $_POST["lqd_9"]; ?>

How can I make the code to not display anything if it's left empty? 如果留空,如何使代码不显示任何内容?

You could use methods like isset or empty 您可以使用issetempty这样的方法

<?php 
if(isset($_POST["lqd_9"])){
 echo $_POST["lqd_9"];
} 
?>

OR 要么

<?php 
if(!empty($_POST["lqd_9"])){
 echo $_POST["lqd_9"];
} 
?>

update 更新

It's better to use both as below. 最好同时使用以下两种方法。

<?php 
if(isset($_POST["lqd_9"]) && !empty($_POST["lqd_9"])){
 echo $_POST["lqd_9"];
} 
?>

PHP isset() vs empty() vs is_null() PHP isset()vs empty()vs is_null()

Its a best practice to use isset and to escape characters like: 最佳做法是使用isset并转义以下字符:

<?php
    if(isset($_POST["lqd_9"]) && trim($_POST["lqd_9"]) !== ""){
        echo htmlspecialchars($_POST["lqd_9"], ENT_COMPAT | ENT_HTML401, 'UTF-8');
    }
?>
if(isset($_POST["lqd_9"]) && $_POST["lqd_9"]){
     ###ALL CODE
}

This simple check will guarantee that there is post data lqd_9 :) 这个简单的检查将确保有发布数据lqd_9 :)

ISSET checks if its set at first time else if you are using it without its set it may throw error. ISSET会在第一次检查它的设置,否则,如果您使用的是它没有设置的设置,则可能会抛出错误。 And the second check is checking if lqd_9 is different from FALSE (if its empty its false else its true) 第二个检查是检查lqd_9是否与FALSE不同(如果为空则为false,否则为true)

<?= isset(($_POST['lqd_9']) ? $_POST['lqd_9'] : ''; ?>

That said, it's a bad practice to display user provided data without saniting it. 就是说,在不清理用户提供的数据的情况下,这是一个错误的做法。 You could create a small convenience function that returns sanitized data /ex: 您可以创建一个小的便利函数,该函数返回已清理的数据/ ex:

<?php
function sanitize($str) {
    return filter_var($str, FILTER_SANITIZE_STRING);
}
?>

<?= isset($_POST['lqd_9']) ? sanitize($_POST['lqd_9']) : '' ?>
<?php 
   if(isset($_POST['lqd_9']){
       echo $_POST['lqd_9'];
   }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM