0

我有一个包含很多课程的数据库,例如早餐麦片、早餐吐司、午餐沙拉、午餐主菜等

我用它把他们输入的数据放入一个包含结果的变量中,例如:

breakfast_toast = Wholemeal;Brown;50/50;
and
breakfast_hotdrinks = Tea;Coffee;Milk;

这是我用来收集该信息的脚本:

 if(!empty($_POST['toast_selection'])) {
    foreach($_POST['toast_selection'] as $toast) {
    $toast = trim($toast);
    if(!empty($toast)) {
      $toastchoices .= "$toast;";
    }
   }
 }

这工作得很好,但我有很多条目要收集,如果他们向数据库添加更多条目,我希望它们自动收集。

我试图想办法,但我就是想不通,这就是我尝试过的:

所有输入的名称与 $course_menuname 相同,例如 Breakfast_cereal[]

$query = "SELECT * FROM course";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{

$course_menuname = $row['course_menuname']; #E.G breakfast_cereal, breakfast_toast, lunch_main
$course_item = $row['course_jsname']; #E.G cereal, toast, jacketpotato
$postResults = $_POST[''.$course_menuname .''];

  if(!empty($postResults)) {
    echo $postResults."<br />";
      foreach($postResults as $course_item) {
        $course_item = trim($course_item);
        if(!empty($course_item)) {
          $course_item1 .= "$course_item;";   
        }
      }
  }
echo $course_item1."<br />";
}

这就是最终结果应该寻找的

 if(!empty($_POST['toast'])) {
   foreach($_POST['toast'] as $toast) {
    $toast = trim($toast);
    if(!empty($toast)) {
      $toastchoices .= "$toast;";
    }
   }
 }
 if(!empty($_POST['toastextra_selection'])) {
   #Gather Toast EXTRAs Choices
   foreach($_POST['toastextra_selection'] as $toastextra) {
    $toastextra = trim($toastextra);
    if(!empty($toastextra)) {
      $toastextrachoices .= "$toastextra;";
   }
  }
 }
 if(!empty($_POST['toastextra_selection'])) {
   #Gather Cold Drinks Choices
   foreach($_POST['colddrinks_selection'] as $colddrinks) {
    $colddrinks = trim($colddrinks);
    if(!empty($colddrinks)) {
      $colddrinkschoices .= "$colddrinks;";
    }
   }
 }
 if(!empty($_POST['hotdrinks_selection'])) {
   #Gather Hot Drinks Choices
   foreach($_POST['hotdrinks_selection'] as $hotdrinks) {
    $hotdrinks = trim($hotdrinks);
    if(!empty($hotdrinks)) {
      $hotdrinkschoices .= "$hotdrinks;";
    }
   }
  }
4

1 回答 1

0

首先,您不应再使用 mysql_* 函数。这些功能被标记为已弃用。或者,您可以使用 PDO 或 mysqli_* 函数。

我想团体变化是你所需要的。让我们从一个简单的例子开始。

try {
    $data = array();
    $pdo = new PDO(...);
    foreach ($pdo->query("SELECT * FROM course") as $row) {
        if (!isset($data[$row['course_menuname'])) {
            $data[$row['course_menuname']] = array();
        }

        if (!empty($row['course_item'] && in_array($row['course_item'], $_POST[$row['course_menuname'])) {
            $data[$row['course_menuname'][] = $row['course_item'];
        }
    }
} catch (PDOException $e) {
    // error handling
}

// Output all choices by menuname
foreach ($data as $key => $value) {
    echo "Choices for " . $key . "\n";
    echo implode(";", $value) . "\n";
}
于 2013-10-29T17:30:59.343 回答