简体   繁体   中英

How do I post data in php and mysql to insert multiple times (rows) using a for loop

How would I go about creating a script that post data multiple times depending on how many times the user wants. I was thinking I could do it using a for loop but not sure where to start. The goal is to post this data row 1, 3, or maybe 5 times into the mySQL table. Anybody got any means on where to start?

Below is what I'm working with...

   // 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>";
  }
<?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>";
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM