你好。 我试图写一些PHP导出输入到csv格式。它工作得很好,除了它不检查以确保所有字段都被填充。我怎样才能确保它们都被填满。
<?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
<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>
答案 0 :(得分:2)
您需要添加!empty
以检查值是否为空。
如果你想检查其他情况,例如名称不应该是数字,你也应该使用regex
。
if (!empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['version']) && !empty($_POST['description'])) {
您评论Whats the difference from !empty and isset
?
假设您有一个变量
$test= "";
if(empty($test)) // it return true because "" is empty
if(isset($test)) // return true because $test is defined
<强> 而 强>
if(empty($anotherTest)) // return true because its null
if(isset($anotherTest)) // return false because is not defined