Inserting values: prepared statement or querying multiple values?

In your opinion and in terms of performance, what is the best solution to insert multiple values ​​into a table?

1 - with the expression Prepared:

$usersId = Users::getAllId($this->sql);
$prep = $this->sql->prepare('INSERT INTO notification_actualites (idUser,idNews) VALUES(:idU,:idN)');
foreach($usersId as $idU)
{
    $prep->execute(array(
        ':idU' => $idU,
        ':idN' => $idN
    ));
}

2 - Or with a request for multiple values:

$usersId = Users::getAllId();
$values='';
foreach($usersId as $id)
{
    $values.='(\''.$id.'\','.$idActu.'),';
}
$values = substr($values,0,strlen($values)-1);
$this->sql->query('INSERT INTO notification_actualites VALUES'.$values);

The security aspect is not a problem here, in both cases the code is adapted to prevent the implementation of sql.

A well-reasoned answer will be appreciated :)

thank

+3
source share
1 answer

I prefer the later method. Each database query must be sent to the database server and receive the results - this takes time, especially if the database server is running on a different machine.

time_to_prepare_query + time_sending_query + time_to_executing_query + time_receiving_results + time_processing_results

time_sending_query time_receiving_results n (n - , db).

, , (, ( ON DUPLICATE KEY ), ..).

, , .

+2

Source: https://habr.com/ru/post/1796039/


All Articles