lastInsertId example


            Shopware()->Db()->query($sql[
                $typID,
                $this->_order->userID,
                $this->_order->id,
                $amount,
                $bid,
                $hash,
            ]);
            $rowID = Shopware()->Db()->lastInsertId();

            // Add an entry in s_order_documents_attributes for the created document             // containing all values found in the 'attributes' element of '_config'             $createdDocument = Shopware()->Models()->getRepository(Document::class)->findOneById($rowID);
            // Create a new attribute entity for the document             $documentAttributes = new DocumentAttribute();
            $createdDocument->setAttribute($documentAttributes);
            if (!empty($this->_config['attributes'])) {
                if (!$createdDocument->getAttribute() instanceof DocumentAttribute) {
                    throw new RuntimeException('Document attributes are not set correctly');
                }
                
$last_insert_id = 0;
    $stmt = $this->connection->prepareStatement((string) $this$this->queryOptions);
    try {
      // Per https://en.wikipedia.org/wiki/Insert_%28SQL%29#Multirow_inserts,       // not all databases implement SQL-92's standard syntax for multi-row       // inserts. Therefore, in the degenerate case, execute a separate query       // for each row, all within a single transaction for atomicity and       // performance.       $transaction = $this->connection->startTransaction();
      foreach ($this->insertValues as $insert_values) {
        $stmt->execute($insert_values$this->queryOptions);
        $last_insert_id = $this->connection->lastInsertId();
      }
    }
    catch (\Exception $e) {
      if (isset($transaction)) {
        // One of the INSERTs failed, rollback the whole batch.         $transaction->rollBack();
      }
      // Rethrow the exception for the calling code.       throw $e;
    }

    

    public function lastInsertId($tableName = null, $primaryKey = null)
    {
        $this->_connect();
        return $this->_connection->lastInsertId();
    }

    /** * Special handling for PDO query(). * All bind parameter names must begin with ':' * * @param string|Zend_Db_Select $sql The SQL statement with placeholders. * @param array $bind An array of data to bind to the placeholders. * @return Zend_Db_Statement_Pdo * @throws Zend_Db_Statement_Exception To re-throw PDOException. */
    
foreach ($this->entries as $entry) {
                $this->connection->insert('s_mail_log', [
                    'type_id' => $entry->getType() ? $entry->getType()->getId() : null,
                    'order_id' => $entry->getOrder() ? $entry->getOrder()->getId() : null,
                    'shop_id' => $entry->getShop() ? $entry->getShop()->getId() : null,
                    'subject' => $entry->getSubject(),
                    'sender' => (string) $entry->getSender(),
                    'sent_at' => $entry->getSentAt()->format('Y-m-d H:i:s'),
                    'content_html' => $entry->getContentHtml(),
                    'content_text' => $entry->getContentText(),
                ]);
                $mailLogId = (int) $this->connection->lastInsertId();

                foreach ($entry->getDocuments() as $document) {
                    $this->connection->insert('s_mail_log_document', [
                        'log_id' => $mailLogId,
                        'document_id' => $document->getId(),
                    ]);
                }

                foreach ($entry->getRecipients() as $recipient) {
                    $mail = mb_strtolower(trim($recipient->getMailAddress()));

                    

                $db->executeQuery($sql[
                    $json_data['notifyOrdernumber'],
                    $json_data['sNotificationEmail'],
                    $json_data['sLanguage'],
                    $json_data['sShopPath'],
                ]);

                $insertId = $db->lastInsertId();

                $eventManager = $this->get('events');

                $params = [
                    'notificationID' => $insertId,
                ];

                $params = $eventManager->filter('Shopware_Notification_Notification_FilterParams', $params[
                    'subject' => $this,
                    'id' => $insertId,
                    'data' => $json_data,
                ]);
'referer' => (string) $this->getSession()->offsetGet('sReferer'),
            'language' => $shop->getId(),
            'dispatchID' => $dispatchId,
            'currency' => $this->sBasketData[CheckoutKey::CURRENCY_NAME],
            'currencyFactor' => $this->sBasketData[CheckoutKey::CURRENCY_FACTOR],
            'subshopID' => $mainShop->getId(),
            'deviceType' => $this->deviceType,
        ];

        try {
            $affectedRows = $this->db->insert('s_order', $data);
            $orderID = $this->db->lastInsertId();
        } catch (Exception $e) {
            throw new Enlight_Exception(sprintf('##sOrder-sTemporaryOrder-#01:%s', $e->getMessage()), 0, $e);
        }
        if (!$affectedRows || !$orderID) {
            throw new Enlight_Exception('##sOrder-sTemporaryOrder-#01: No rows affected or no order id saved', 0);
        }

        // Create order attributes         $this->attributePersister->persist($this->orderAttributes, 's_order_attributes', $orderID);

        foreach ($this->sBasketData[CartKey::POSITIONS] as $basketRow) {
            
'Shopware_Modules_Basket_InsertDiscount_FilterParams',
                $params,
                [
                    'subject' => $this,
                    'getDiscounts' => $getDiscounts,
                    'basketAmount' => $basketAmount,
                    'basketDiscount' => $basketDiscount,
                ]
            );

            $this->db->insert('s_order_basket', $params);
            $this->db->insert('s_order_basket_attributes', ['basketID' => $this->db->lastInsertId()]);
        }
    }

    /** * Check if any discount is in the cart * Used only internally in sBasket * * @return bool */
    public function sCheckForDiscount()
    {
        
return null;
    }

    private function storeUniqueIdInDb(string $uniqueId): void
    {
        $uniqueRowId = $this->connection->fetchOne("SELECT id FROM s_core_config_elements WHERE name LIKE 'trackingUniqueId' LIMIT 1");

        if ($uniqueRowId === false) {
            $this->connection->executeStatement("INSERT INTO s_core_config_elements (form_id, name, value, label, description, type, required, position, scope) VALUES ('0', 'trackingUniqueId', 's:0:\"\";', 'Unique identifier', '', 'text', '0', '0', '1')");
            $uniqueRowId = $this->connection->lastInsertId();
        }

        $sql = <<<'sql' INSERT INTO s_core_config_values (element_id, shop_id, value) VALUES ( :uniqueRowId, 1, :value ) sql;

        $this->connection->executeStatement(
            $sql,
            [
                
'ordernumber' => $orderNumber,
                    'quantity' => 1,
                    'price' => $price,
                    'netprice' => $netPrice,
                    'tax_rate' => $tax,
                    'datum' => date('Y-m-d H:i:s'),
                    'modus' => $mode,
                    'currencyFactor' => $currencyFactor,
                ]
            );

            $this->connection->insert('s_order_basket_attributes', ['basketID' => $this->connection->lastInsertId()]);
        }
    }
}
$this->configuration['queue_name'],
            $now,
            $availableAt,
        ][
            Types::STRING,
            Types::STRING,
            Types::STRING,
            Types::DATETIME_IMMUTABLE,
            Types::DATETIME_IMMUTABLE,
        ]);

        return $this->driverConnection->lastInsertId();
    }

    public function get(): ?array
    {
        if ($this->driverConnection->getDatabasePlatform() instanceof MySQLPlatform) {
            try {
                $this->driverConnection->delete($this->configuration['table_name']['delivered_at' => '9999-12-31 23:59:59']);
            } catch (DriverException $e) {
                // Ignore the exception             }
        }

        
$product = $this->get('models')->find(Product::class$productId);
        if ($product->getConfiguratorSet() !== null) {
            $isConfigurator = true;
            $mailDetailId = $product->getMainDetail()->getId();
        } else {
            $isConfigurator = false;
            $mailDetailId = null;
        }

        $this->duplicateArticleData($productId);
        $newProductId = (int) Shopware()->Db()->lastInsertId('s_articles');
        $this->duplicateArticleCategories($productId$newProductId);
        $this->duplicateArticleCustomerGroups($productId$newProductId);
        $this->duplicateArticleRelated($productId$newProductId);
        $this->duplicateArticleSimilar($productId$newProductId);
        $this->duplicateArticleTranslations($productId$newProductId);
        $this->duplicateArticleDetails($productId$newProductId$mailDetailId);
        $this->duplicateArticleLinks($productId$newProductId);
        $this->duplicateArticleImages($productId$newProductId);
        $this->duplicateArticleProperties($productId$newProductId);
        $this->duplicateArticleDownloads($productId$newProductId);
        $setId = $this->duplicateArticleConfigurator($productId);

        

        $this->validateFields($data);
        $data = $this->filterFields($data);
        $data = $this->quoteFields($data);

        $data['updated_at'] = date('Y-m-d H:i:s');
        if ($id) {
            $this->connection->update($this->type->getTableName()$data['id' => $id]);
        } else {
            $data['created_at'] = date('Y-m-d H:i:s');
            $this->connection->insert($this->type->getTableName()$data);
            $id = (int) $this->connection->lastInsertId();
        }

        return $id;
    }

    public function delete(int $id): bool
    {
        $this->connection->delete($this->type->getTableName()['id' => $id]);

        return true;
    }

    
':datum' => $date,
            ':active' => $active,
            ':email' => $sVoteMail,
            ':shopId' => $shopId,
        ]);

        $success = $query->execute();
        if (empty($success)) {
            throw new Enlight_Exception('sSaveComment #00: Could not save comment');
        }

        $insertId = $this->connection->lastInsertId();
        if (!isset($this->session['sArticleCommentInserts'])) {
            $this->session['sArticleCommentInserts'] = new ArrayObject();
        }

        $this->session['sArticleCommentInserts'][$article] = $insertId;
    }

    /** * @deprecated in 5.6, will be removed in 5.8 without replacement * * Get id from all products, that belongs to a specific supplier * * @param int $supplierID Supplier id (s_articles.supplierID) * * @return array */
return $stmt;

        // Database::RETURN_AFFECTED should not be used; enable row counting         // by passing the appropriate argument to the constructor instead.         // @see https://www.drupal.org/node/3186368         case Database::RETURN_AFFECTED:
          $stmt->allowRowCount = TRUE;
          return $stmt->rowCount();

        case Database::RETURN_INSERT_ID:
          $sequence_name = $options['sequence_name'] ?? NULL;
          return $this->lastInsertId($sequence_name);

        case Database::RETURN_NULL:
          return NULL;

        default:
          throw new \PDOException('Invalid return directive: ' . $options['return']);

      }
    }
    catch (\Exception $e) {
      $this->exceptionHandler()->handleExecutionException($e$stmt$args$options);
    }
$originalCategory['parent'] = $parentId;

        unset($originalCategory['id']$originalCategory['path']);

        $valuePlaceholders = array_fill(0, \count($originalCategory), '?');
        $insertStmt = $this->connection->prepare(
            'INSERT INTO s_categories (`' . implode('`, `', array_keys($originalCategory)) . '`) VALUES (' . implode(', ', $valuePlaceholders) . ')'
        );
        $insertStmt->execute(array_values($originalCategory));
        $newCategoryId = (int) $this->connection->lastInsertId();

        $this->rebuildPath($newCategoryId);

        $this->duplicateCategoryAttributes($originalCategoryId$newCategoryId);
        $this->duplicateCategoryRestrictions($originalCategoryId$newCategoryId);

        if ($copyArticleAssociations) {
            $this->duplicateCategoryArticleAssociations($originalCategoryId$newCategoryId);
        }

        return $newCategoryId;
    }
Home | Imprint | This part of the site doesn't use cookies.