You can install it via Composer:
composer require byjg/anydataset-db
First, set up a database connection. ByJG AnyDatasetDB supports multiple databases like MySQL, PostgreSQL, SQL Server, and SQLite.
Here is an example of how to connect to a MySQL database:
<?php
require 'vendor/autoload.php';
use ByJG\AnyDataset\Db\Factory;
// Create a connection string
$connectionString = 'mysql://user:password@localhost/databasename';
// Create a DbDriver
$dbDriver = Factory::createDbDriver($connectionString);
Once you have your database connection set up, you can perform queries using the DbDriver object. Here's an example of a simple SELECT query:
<?php
use ByJG\AnyDataset\Core\Row;
use ByJG\AnyDataset\Core\IteratorInterface;
// Define your SQL query
$sql = "SELECT * FROM your_table WHERE id = :id";
// Execute the query with parameters
$iterator = $dbDriver->getIterator($sql, [':id' => 1]);
// Fetch results
foreach ($iterator as $row) {
/** @var Row $row */
$data = $row->toArray();
print_r($data);
}
Here is an example of how to insert, update, or delete data using execute:
Insert data:
<?php
$sql = "INSERT INTO your_table (name, age) VALUES (:name, :age)";
$dbDriver->execute($sql, [':name' => 'John', ':age' => 30]);
Update data:
<?php
$sql = "UPDATE your_table SET age = :age WHERE name = :name";
$dbDriver->execute($sql, [':age' => 31, ':name' => 'John']);
Delete data:
<?php
$sql = "DELETE FROM your_table WHERE name = :name";
$dbDriver->execute($sql, [':name' => 'John']);
You can explicitly close the connection when you're done:
<?php
$dbDriver->disconnect();
Here’s an example of querying data from a MySQL database using ByJG AnyDatasetDB:
<?php
require 'vendor/autoload.php';
use ByJG\AnyDataset\Db\Factory;
use ByJG\AnyDataset\Core\Row;
// Create a connection to the database
$connectionString = 'mysql://user:password@localhost/databasename';
$dbDriver = Factory::createDbDriver($connectionString);
// Define and execute the query
$sql = "SELECT * FROM your_table WHERE age > :age";
$iterator = $dbDriver->getIterator($sql, [':age' => 25]);
// Loop through the results
foreach ($iterator as $row) {
/** @var Row $row */
$data = $row->toArray();
print_r($data);
}
// Disconnect from the database
$dbDriver->disconnect();
With ByJG AnyDatasetDB, querying a database is straightforward. The main steps involve connecting to the database, preparing SQL queries, and using getIterator() for SELECT queries or execute() for INSERT, UPDATE, or DELETE operations.