Django Anonymous
Django Anonymous

Reputation: 3025

More efficient way of inserting data into mysql using PDo

Ok so I execute the following code for inserting data into database:

$db_conn->beginTransaction();
$query = $db_conn->prepare('INSERT INTO mytable(name, user) VALUES(:name, :user)');
foreach($UploadData AS $DataValue)
{
    $query->execute(array(':name' => $DataValue['Name'],':user' =>$_SESSION['user']));
}
$db_conn->commit();

Now in this code block execute() runs 100s time if I have that much data. Like before I use to do with basic mysqli concatenation and executes the query only once.

Will that can be done here with PDO also?

Upvotes: 0

Views: 93

Answers (1)

Simone Nigro
Simone Nigro

Reputation: 4887

$SQL = 'INSERT INTO mytable (name, user) VALUES';

foreach( $UploadData AS $DataValue)
    $SQL .= sprintf(" ( '%s', '%s' ),", $DataValue['Name'], $DataValue['user'] );

$SQL = substr($SQL, -1);

$query = $db_conn->prepare($SQL);
$query->execute();

Result

INSERT INTO mytable (name, user) VALUES ('VAL', 'VAL'), ('VAL', 'VAL') ....

Upvotes: 1

Related Questions