0

I've got an array called $changedcompanies and I want to insert the contents into my mySQL table.

Currently I'm using a for loop in php which must be an inefficent way of going about it:

for ($x=0;$x<count($changedcompanies);$x++){
    try {
        $sql = "INSERT INTO ecampaign_historyamend SET historyid = '".$lastid."', 
        companyid = '".$changedcompanies[$x]['id']."', 
        newcontactid = '".$changedcompanies[$x]['contactid']."'";
        $s   = $pdo->prepare($sql);
        $s->execute();
    }
    catch (PDOException $e) {
        $error = 'Error inserting history amend: ' . $e->getMessage();
        showerror($error);
        exit();
    }
} 

Is there a way to design a mySQL query that will insert the whole array in one go?

8
  • 1
    You're using prepared statements incorrectly. You need to use placeholders instead of adding the variables each time - prepare the statement outside the for loop, and just execute it inside the loop, passing the different variables each time. Commented Jan 17, 2015 at 15:38
  • 1
    I think this is already explained here: stackoverflow.com/questions/10054633/… Commented Jan 17, 2015 at 15:39
  • 1
    @IndraKumarS - it's an alternative version of the INSERT syntax: dev.mysql.com/doc/refman/4.1/en/insert.html Commented Jan 17, 2015 at 15:40
  • 1
    @IndraKumarS, this is perfectly correct Commented Jan 17, 2015 at 15:42
  • 1
    possible duplicate of Inserting multiple rows in mysql Commented Jan 17, 2015 at 15:43

1 Answer 1

1

Connect them all, then run them. Do not forget the semicolon between commands:

$sql="";
for ($x=0;$x<count($changedcompanies);$x++){
        $sql.= "INSERT INTO ecampaign_historyamend SET historyid = '".$lastid."', 
        companyid = '".$changedcompanies[$x]['id']."', 
        newcontactid = '".$changedcompanies[$x]['contactid']."';";
}

try {
$s = $pdo->prepare($sql);
$s->execute();
}
catch (PDOException $e) {
$error = 'Error inserting history amend: ' . $e->getMessage();
showerror($error);
exit();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.