„Powerful database abstraction layer with many features for database schema introspection, schema management and PDO abstraction.“
The following will get you started, these offer the Doctrine\Common and Doctrine\DBAL namespaces.
BASIC SETUP
In the end your structure should look something like that:
includes/
includes/doctrine
includes/doctrine/lib
includes/doctrine/lib/Doctrine
includes/doctrine/lib/Doctrine/Common
includes/doctrine/lib/Doctrine/DBAL
The following will add a class loader, so that all the other classes will be autoloaded.
1 2 3 4 5 6 |
use Doctrine\Common\ClassLoader; require dirname(__FILE__).'/includes/doctrine/lib/Doctrine/Common/ClassLoader.php'; $classLoader = new ClassLoader('Doctrine',dirname(__FILE__).'/includes/doctrine/lib'); $classLoader->register(); |
FIRST CONNECTION
This will setup your first connection to a MySQL database.
1 2 3 4 5 6 7 8 9 10 |
$config = new \Doctrine\DBAL\Configuration(); $connectionParams = array( 'dbname' => 'my_db', 'user' => 'my_user', 'password' => 'my_pass', 'host' => 'localhost', 'driver' => 'pdo_mysql', ); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); |
FIRST QUERY
This will do a simple first query
1 2 3 4 5 6 |
$sql = "SELECT * FROM some_data"; $stmt = $conn->query($sql); while ($row = $stmt->fetch()) { echo $row['some_field']; } |
DYNAMIC & PREPARED
DBAL gives us some nice options to prepare queries.
1 2 3 4 |
$sql = "SELECT * FROM some_data WHERE id = ?"; $stmt = $conn->prepare($sql); $stmt->bindValue(1, $id); $stmt->execute(); |
By using the bindValue the placeholder „?“ is replaced. You can also use named parameters :)
1 2 3 4 |
$sql = "SELECT * FROM some_data WHERE name = :name OR username = :name"; $stmt = $conn->prepare($sql); $stmt->bindValue("name", $name); $stmt->execute(); |
More about this in the official documentation.
That was not too difficult ;)