0

我将如何根据用户想要的次数创建一个多次发布数据的脚本。我在想我可以使用 for 循环来做到这一点,但不知道从哪里开始。目标是将此数据行 1、3 或 5 次发布到 mySQL 表中。有人知道从哪里开始吗?

下面是我正在使用的...

   // check if the form was submitted
if( isset($_POST['save_stuff']) ) {

  // create the website object
  $stuff = new stuff($_POST['stuff']);

  // prepare an SQL query
  $stmt = $dbh->prepare("INSERT INTO `".$example."` (`title`, `stuf`, `due`, `details`, `category`, `user`) VALUES (:title, :stuff, :due, :details, :category, :user)");

$id = mysql_real_escape_string($_GET['id']);


  // run the SQL query
  if(  $stmt->execute(array(
        'title' => $stuff->title,
        'stuff' => $id,
        'due' => $stuff->due,
        'details' => $stuff->details,
        'category' => $stuff->category,
        'user' => $stuff->user
      ))
  ) {

    // if successful then go back to home page
    header("Location: ../stuff/?id=".$id."");
  } else {

    // display an error if it failed
    echo "<p>failed to add stuff</p>";
  }
4

1 回答 1

1
<?php 
// check if the form was submitted
if( isset($_POST['save_stuff']) ) {

    // create the website object
    $stuff = new stuff($_POST['stuff']);

    // prepare an SQL query
    $stmt = $dbh->prepare("INSERT INTO `".$example."` (`title`, `stuf`, `due`, `details`, `category`, `user`) VALUES (:title, :stuff, :due, :details, :category, :user)");

    // Unnecesary since PDO takes care of it anyway trough execute
    //$id = mysql_real_escape_string($_GET['id']);

    // number of times to run
    $timestorun = 10;
    for($i = 1; $i <= $timestorun; $i++){
        // Notice it will insert the same stuff multiple times! 
        // run the SQL query
        if(  $stmt->execute(array(
        'title' => $stuff->title,
        'stuff' => $id,
        'due' => $stuff->due,
        'details' => $stuff->details,
        'category' => $stuff->category,
        'user' => $stuff->user
        ))
        ) {
            $insertworkedArr[] = 1;
            $allIds .= $id . ",";
        } else {
            $insertworkedArr[] = 0;
        }
    }
    if(min($insertworkedArr) == 1){
        // if successful then go back to home page
        // $allIds contains all IDs that are inserted, accessible 
        // as an array trough an explode($allIds,",") at the next page
        header("Location: ../stuff/?id=".$id."&wasTheLastOneButAlso".$allIDs."");
    } else {
        // display an error if it failed
        echo "<p>failed to add stuff</p>";
    }
}
?>
于 2013-05-31T15:15:41.763 回答