Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Fetch database connection

$connection = sfContext::getInstance()->getDatabaseConnection('propel');
by Dustin Whittle on 2006-05-22, tagged creole  database  propel 

Comments on this snippet

gravatar icon
#1 Fabien Potencier on 2006-05-22 at 08:09

If you want the Propel connection from a model class, always use the following to allow your model classes to be used outside a symfony context:

$connection = Propel::getConnection();
gravatar icon
#2 pookey on 2006-05-30 at 03:09

A full example of custom SQL taken from the askeet tutorial

public function executeAutocomplete()
{
  $tags = array();
 
  $con = sfContext::getInstance()->getDatabaseConnection('propel');
  $query = '
    SELECT DISTINCT %s AS tag
    FROM %s
    WHERE %s = ? AND %s LIKE ?
    ORDER BY %s
  ';
 
  $query = sprintf($query,
    QuestionTagPeer::TAG,
    QuestionTagPeer::TABLE_NAME,
    QuestionTagPeer::USER_ID,
    QuestionTagPeer::TAG,
    QuestionTagPeer::TAG
  );
 
  $stmt = $con->prepareStatement($query);
  $stmt->setInt(1, $this->getUser()->getSubscriberId());
  $stmt->setString(2, $this->getRequestParameter('tag').'%');
  $stmt->setLimit(10);
  $rs = $stmt->executeQuery();
  while ($rs->next())
  {
    $tags[] = $rs->getString('tag');
  }
 
  $this->tags = $tags;
You need to create an account or log in to post a comment or rate this snippet.