Что изменить, чтобы несколько вставок делались одновременно и быстрее - PullRequest
0 голосов
/ 01 января 2019

Проблема в том, что я хочу сделать один запрос, чтобы вставить все содержимое корзины одновременно в таблицу базы данных ordersdetail, чтобы повысить скорость.

В моем коде ниже вставки теперь находятся в цикле for с использованием подготовленных операторов.Сценарий ниже работает, но вставка происходит сейчас на каждой итерации.

Я думал, что было бы быстрее, если бы я поместил всю тележку в массив, но я застрял.Я не могу решить проблему.Любая помощь приветствуется.

ПИСЬМО

include_once '../../includes/db_connect.php'; 

class Item{
    var $productid;
    var $productnaam;
    var $productomschrijving;
    var $productprijs_excl;
    var $productprijs_incl;
    var $product_btw_tarief;
    var $quantity;
    var $lesuren;
}

session_start();

$order_id = $_SESSION["order_id"];
$klantid = $_SESSION["klantid"];

$insert_stmt = $mysqli->prepare('INSERT INTO ordersdetail (order_id, productid, productnaam, productomschrijving, productprijs_incl, product_btw_tarief, aantal, subtotaalexcl, subtotaal, klantid, lesuren) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$insert_stmt->bind_param('iissddiddid', $order_id, $productid, $productnaam, $productomschrijving, $productprijs_incl, $product_btw_tarief, $aantal, $subtotaalexcl, $subtotaal, $klantid, $lesuren);                   

$cart = $_SESSION ['cart'];

    for($i = 0; $i < count($cart); $i++){

        $productid = $cart[$i]->productid;
        $productnaam = $cart[$i]->productnaam;
        $productomschrijving = $cart[$i]->productomschrijving;
        $productprijs_incl = $cart[$i]->productprijs_incl;
        $product_btw_tarief = $cart[$i]->product_btw_tarief;
        $subtotaalexcl = $cart[$i]->productprijs_excl * $cart[$i]->quantity;
        $subtotaal = $cart[$i]->productprijs_incl * $cart[$i]->quantity;
        $aantal = $cart[$i]->quantity;
        $lesuren = $cart [$i]->lesuren * $cart[$i]->quantity;

        $insert_stmt->execute();
    }// End for loop
 $insert_stmt->close();

РЕДАКТИРОВАТЬ

$cart = unserialize (serialize ($_SESSION ['cart'])); 

отредактировано в:

$cart = $_SESSION ['cart'];

@ Ник.Привязка перемещается за пределы цикла сразу после оператора prepare.

1 Ответ

0 голосов
/ 02 января 2019

После быстрой проверки, и кажется, что получить подготовленный оператор без запроса не так просто, поэтому альтернативой является экранирование данных без подготовленного оператора, вот быстрая реализация:

$order_id = $_SESSION["order_id"];
$klantid = $_SESSION["klantid"];


$cart = unserialize (serialize ($_SESSION ['cart']));
$insert_values = '';
for($i = 0; $i < count($cart); $i++){

    $productid = $cart[$i]->productid;
    $productnaam = $cart[$i]->productnaam;
    $productomschrijving = $cart[$i]->productomschrijving;
    $productprijs_incl = $cart[$i]->productprijs_incl;
    $product_btw_tarief = $cart[$i]->product_btw_tarief;
    $subtotaalexcl = $cart[$i]->productprijs_excl * $cart[$i]->quantity;
    $subtotaal = $cart[$i]->productprijs_incl * $cart[$i]->quantity;
    $aantal = $cart[$i]->quantity;
    $lesuren = $cart [$i]->lesuren * $cart[$i]->quantity;

    //You can escape them during assigning, I did it here to easily see the data types
    //i
    $order_id = (int)$order_id;
    //i
    $productid = (int)$productid;
    //s
    $productnaam = mysqli_real_escape_string($mysqli, $productnaam);
    //s
    $productomschrijving = mysqli_real_escape_string($mysqli, $productomschrijving);
    //d
    $productprijs_incl = (double) $productprijs_incl;
    //d
    $product_btw_tarief = (double) $product_btw_tarief;
    //i
    $aantal = (int)$aantal;
    //d
    $subtotaalexcl = (double)$subtotaalexcl;
    //d
    $subtotaal = (double)$subtotaal;
    //i
    $klantid = (int) $klantid;
    //d
    $lesuren = (double) $lesuren;

    $insert_values .= "($order_id, $productid, $productnaam, $productomschrijving, $productprijs_incl, $product_btw_tarief, $aantal, $subtotaalexcl, $subtotaal, $klantid, $lesuren),";

}// End for loop

//trim trailing ,
rtrim($insert_values, ",");

$sql = "INSERT INTO ordersdetail (order_id, productid, productnaam, productomschrijving, productprijs_incl, product_btw_tarief, aantal, subtotaalexcl, subtotaal, klantid, lesuren) VALUES " . $insert_values;

$mysqli->query($sql);

Предупреждение Вы должны добавить больше проверок относительно данных, которые вы хотите вставить

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...