
Test Test - 2010-02-20 18:20:51 -
In reply to message 1 from Gianluca Zanferrari
Hi,
As an example, here is how I used it in a former project.
First, I declare a global object that will manage my databases accesses.
global $db;
$db = new DatabaseConnection('someMysqlServer', 'user', 'pass', 'database');
Then, I do everything with that object.
For instance, reading a structure and the contents of a table.
$result = $db->exec($db->filterForSql('SELECT * FROM '.$tableName.';'));
$tabulated = false;
while ($row = $db->fetchAssoc($result))
{
if (!$tabulated) // If this is the first pass, display a header
{
?>
<p><?=$tableName?> (<?=$db->numRows($result)?> entries in this table)</p>
<table border="1">
<tr>
<?php
foreach (array_keys($row) as $key)
{
?>
<th><?=$key?></th>
<?php
}
?>
</tr>
<?php
$tabulated = true;
}
?>
<tr>
<?php
foreach ($row as $val)
{
?>
<td><?=($val != null ? $val : "<i>NULL</i>")?></td>
<?php
}
?>
</tr>
<?php
} // End foreach
The main feature this class provides is the hability to switch to different backends. The preferred one is PDO, which can virtually be used to query any database kind (I only tested agaisnt mysql).
If PDO isn't available (which is the case in PHP 5.0 without the pear extension, or with some kind of obnoxious server configs), this class will use a mysqli backend and offer the same set of features.
One last backend remains which uses mysql_* functions. It is disabled by default because it doesn't supports transactions, but can be enabled back if the server doesn't has mysqli extention (just set attribute legacyBackendMysqli to false in the class source).
The provided features are prepared statements (natively handled by PDO, emulated for mysqli and mysql_*), transactions (except for mysql_*).
You can do a prepared query using something like that (with the ? form)
$db->prepareStatement("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND ENGINE = ? AND ROW_FORMAT = ?");
$db->bindValue(2, "InnoDB");
$db->bindValue(3, "Compact");
$db->bindValue(1, "databaseName");
$tableResult = $db->executeStatement();
Or with the :paramName form :
$db->prepareStatement("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = :database AND ENGINE = :engine AND ROW_FORMAT = :format");
$db->bindValue(':engine', "InnoDB");
$db->bindValue(':format', "Compact");
$db->bindValue(':database', "base08");
$tableResult = $db->executeStatement();
An example of a transaction could be :
$db->beginTransaction();
$db->exec($call);
$clientId = $db->lastInsertId();
// Do something with $clientId.
$db->commit(); // or $db->rollback();
Regards
Octave
PS : Sorry for the inconvenience, this forum just killed the indentation.