简体   繁体   English

如何确保所有字段都填写了php?

[英]How to make sure all fields are filled in php?

Hi. 你好。 I am trying to write some php to export input to csv format. 我试图写一些php将输入导出为csv格式。 It works really well, except it doesn't check to make sure all fields are filled. 它确实工作得很好,除了它不检查以确保所有字段都已填充。 How can I make sure they are all filled. 我如何确保它们都已满。

<?php
$txt = "report.csv";
$fh = fopen($txt, 'a+');
if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['version']) && isset($_POST['description'])) { // check if both fields are set
   $first = $_POST['firstname'];
   $last =  $_POST['lastname'];
   $version = $_POST['version'];
   $description = $_POST['description'];
   $q = "\"";
   $c = ",";
   $check=$first.$last.$version.$descrption;
   $txt=$q.$first.$q.$c.$q.$last.$q.$c.$q.$version.$q.$c.$q.$description.$q;
   if (strpos($check, '"') !== false){
   echo file_get_contents("/quotes.html");
   } else {
   file_put_contents('report.csv',$txt."\n",FILE_APPEND); // log to data.txt
   echo file_get_contents("yay.html");
   exit();
   }
} else {
echo file_get_contents("notfilled.html");
}

?>

HTML HTML

  <form action="problem.php" method="POST">
    <label for="fname"><h3>First Name</h3></label>
    <input type="text" id="fname" name="firstname">

    <label for="lname"><h3>Last Name</h3></label>
    <input type="text" id="lname" name="lastname">
    <label for="version"><h3>Version</h3></label>
    <select id="version" name="version">
      <option value="0.1">0.1</option>
      <option value="0.2">0.2</option>
      <option value="Other">Other</option>
    </select>
    <label for="description"><h3>Description</h3></br><p1>Please describe your problem with details. Explain what the problem is how to reproduce it.</label>
    <textarea id="description" name="description" style="height:100px"></textarea>

    <input type="submit" value="Submit">
  </form>

You need to add !empty to check the values are empty or not. 您需要添加!empty以检查值是否为空。 if you want to check for other case too such as name should not be number the you should use regex too. 如果您也想检查其他情况,例如名称不应该是数字,那么您也应该使用regex

if (!empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['version']) && !empty($_POST['description'])) {

For you comment Whats the difference from !empty and isset ? 对您发表评论Whats the difference from !empty and isset

Suppose you have a variable 假设你有一个变量

$test= "";

if(empty($test)) // it return true because "" is empty

if(isset($test)) // return true because $test is defined 

while

if(empty($anotherTest)) // return true because its null

if(isset($anotherTest)) // return false because is not defined

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

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