Skip to content

Instantly share code, notes, and snippets.

@rikh42
Forked from anonymous/gist:4345327
Created December 20, 2012 13:43
Show Gist options
  • Save rikh42/4345392 to your computer and use it in GitHub Desktop.
Save rikh42/4345392 to your computer and use it in GitHub Desktop.
/*
Database gets in connection settings from the config file
eg. app/resources/config/config.yml
database:
read:
host: localhost
port: 3306
user: root
password: secret-shhh
database: dbName
It's actually possible to set up multiple connections (eg, one for reads and one for writes), but typically only read is needed.
*/
// Get the database service
$db = $this->get('database');
// Fetch a single value from the database
// All arguments should be named.
// Pass in an array with the named values, which will be bound to the query.
// You can also provide a type with the name in the array, to be extra clear.
// for example: array('id:int' => 42); notice the :int in the name.
// The array can contain extra values that are not used, which can be useful in some situations. The order is not important.
$value = $db->one("SELECT value FROM table WHERE id=:id", array('id'=>42));
// Fetch a single row from the database
$row = $db->row("SELECT * FROM table WHERE id=:id AND name=:username",
array('id' => 42, 'username'=>'Mr Test'));
echo $row->name;
echo $row->id;
// Fetch all the results
$all = $db->all("SELECT * FROM table");
if ($all)
{
foreach($all as $row)
{
echo $row->name;
}
}
// Finally, for any updates, inserts, or just any old query...
$db->query("INSERT INTO table (id, name) VALUES (NULL, :name)", array('name' => 'Mr Test'));
$newIdInt = $db->getLastInsertId();
$newIdString = $db->getLastInsertIdString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment