require_once 'vendor/autoload.php'; use \PDO; use \MyApp\User; $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password"); $user = new User(); $user->setName("John Doe"); $user->setEmail("john.doe@example.com"); $user->setPassword("mypassword"); $sql = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)"; $stmt = $pdo->prepare($sql); $stmt->bindParam(':name', $user->getName()); $stmt->bindParam(':email', $user->getEmail()); $stmt->bindParam(':password', $user->getPassword()); $stmt->execute(); echo "New user created successfully!";
require_once 'vendor/autoload.php'; use \PDO; use \MyApp\Product; $pdo = new PDO("pgsql:host=localhost;dbname=mydatabase", "username", "password"); $products = [ new Product("Product 1", 10.00), new Product("Product 2", 20.00), new Product("Product 3", 30.00) ]; $sql = "INSERT INTO products (name, price) VALUES (:name, :price)"; $stmt = $pdo->prepare($sql); foreach ($products as $product) { $stmt->bindParam(':name', $product->getName()); $stmt->bindParam(':price', $product->getPrice()); $stmt->execute(); } echo "Products added successfully!";In this example, we use the PDO library and our own custom Product class to insert multiple products into a PostgreSQL database. We create an array of products, set their name and price using a constructor and prepare an SQL statement. We then loop through the array and bind parameters to the statement and execute it for each product. The package/library used in both examples is PDO, which is a flexible and lightweight database abstraction layer in PHP.