0

我有一个 html 表单并使用 get 方法

如果用户选择鞋子选项值,我想将数据输入到 shoes_sales.txt,并将其余所有输入到衣服_sales.txt。

我正在使用以下 if 语句

<?php
header("Location: thankforsumbitting.html");

if($_GET['variable1'] == "shoes" || $_GET['variable1'] == "shoes"){
  $handle = fopen("shoes_sales.txt", "a");
  foreach($_GET as $variable => $value) {
    fwrite($handle, $variable);
    fwrite($handle, "=");
    fwrite($handle, $value);
    fwrite($handle, "\r\n");
  }
  else {
    $handle = fopen("clothes_sales.txt", "a");
    foreach($_GET as $variable => $value) {
      fwrite($handle, $variable);
      fwrite($handle, "=");
      fwrite($handle, $value);
      fwrite($handle, "\r\n");
      fclose($handle);
      exit;
?> 
4

3 回答 3

0

丢失括号和逻辑问题

尝试这个

<?php
  header("Location: thankforsumbitting.html");

  if ($_GET['variable1'] == "shoes") {
    $handle = fopen("shoes_sales.txt", "a");
  }
  else {
    $handle = fopen("clothes_sales.txt", "a");
  }
  foreach($_GET as $variable => $value) {
    fwrite($handle, $variable."=".$value."\r\n");
  }
  fclose($handle);
  exit;
?> 
于 2013-08-22T17:31:05.987 回答
0

您忘记了}andif子句else和第二个foreach.

<?php
header("Location: thankforsumbitting.html");

if($_GET['variable1'] == "shoes" || $_GET['variable1'] == "shoes"){
    $handle = fopen("shoes_sales.txt", "a");
    foreach($_GET as $variable => $value) {
        fwrite($handle, $variable);
        fwrite($handle, "=");
        fwrite($handle, $value);
        fwrite($handle, "\r\n");
    }
    fclose($handle);
}
else {
    $handle = fopen("clothes_sales.txt", "a");
    foreach($_GET as $variable => $value) {
        fwrite($handle, $variable);
        fwrite($handle, "=");
        fwrite($handle, $value);
        fwrite($handle, "\r\n");
    }
    fclose($handle);
}
exit;
?> 
于 2013-08-22T17:25:05.003 回答
0

与其重复调用,不如构建格式化文本,然后使用file_put_contents()fwrite()只写一次到 txt 文件的末尾?这样可以减少函数调用。

代码:

$data = '';
foreach ($array as $key => $value) {
    $data .= "{$key}={$value}" . PHP_EOL;
}

file_put_contents(
    $_GET['variable1'] == "shoes" ? 'shoes_sales.txt' : 'clothes_sales.txt',
    $data,
    FILE_APPEND | LOCK_EX
);
于 2021-04-07T03:33:33.090 回答