使用for循环和PDO将一周(七个sparate天)和一些其他数据插入数据库

时间:2012-03-21 08:38:42

标签: php mysql for-loop

这是我的数据:

Day            From:     To:

Sunday         12PM      8PM

Monday         12PM      9PM

Tuesday        12PM      6PM

Wednesday      12PM      6PM

Thursday       12PM      6PM

Friday         12PM      5PM

Saturday       12PM      5PM

如何使用for循环将上述数据(从$ _POST)插入到我的MySQL数据库中,使用PHP' S PDO?我的输入字段名为SundayTimeFrom,SundayTimeTo,MondayTimeFrom,MondayTimeTo等。

我快速拼凑的伪代码:

$sql = 'Insert INTO tableName (day, from, to) Values (:day, :from, :to)';
for(i = Sunday; I < Saturday; i++) //what do I do here?
{
    $stmt = $this->_db->prepare($sql);
    $stmt->bindParam(":day", $i, PDO::PARAM_STR);
    $stmt->bindParam(":from", $_POST[$i + 'TimeFrom'], PDO::PARAM_STR);
    $stmt->bindParam(":to", $_POST[$i + 'TimeTo'], PDO::PARAM_STR);
}

3 个答案:

答案 0 :(得分:1)

你可以循环7次并使用日期('l',时间()+ 24小时(以秒为单位)来获取你的日期。

在这里查看日期('l')http://php.net/date

但最好的办法是将$ _POST更改为$_POST['days'][0][from] = '10PM';$_POST['days'][0][to] = '8PM';

如果我记得正确

,你可以写下:<input type="text" name="days[][from]" value="10PM" />来做到这一点

或只是<input type="text" name="days[Monday][from]" value="10PM" /><input type="text" name="days[Monday][to]" value="8PM" />并执行foreach($_POST['days'] as $value)

正如您所看到的,您有很多解决方案:)

答案 1 :(得分:0)

如果字段的名称为SundayTimeFromSundayTimeTo而不是schedule[sunday][from]schedule[sunday][to],则可以使用类似

的foreach循环
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":day", $day);
$stmt->bindParam(":from", $from);
$stmt->bindParam(":to", $to);

foreach( $_POST['schedule'] as $day=>$span ) {
  someDataValidationHere($day, $span);
  $from = $span['from'];
  $to = $span['to'];
  $stmt->execute();
}

(未测试的)

答案 2 :(得分:0)

说你的数组是

$schedule = array (sunday => array (from=>"12PM", to=> "8PM"),
                   monday => array (from=>"1PM", to=> "9PM"),
                    tuesday => array (from=>"2PM", to=> "10PM"),
                    wednesday => array (from=>"3PM", to=> "11PM"),
  );

使用_REQUEST [“schedule”]并在某些数组中保存$ schedule。

现在使用foreach将数组保存在数据库中。

  foreach ($schedule as $day=>$temp1) {
    foreach ($temp1 as $key=>$time) {
      if($key == "from")
        $from = $time;
      else if($key == "to")
        $to = $time;
    }
    $sth = $this->db->prepare("Insert INTO tableName (day, from, to) Values (:day, :from, :to)");
    $sth->execute(array(':day'=> $day, ':from'=> $from, ':to'=> $to));
  }