Wednesday, January 30, 2013

PDO MySQL

    try {
      $this->_handle = new PDO('mysql:host=localhost;dbname='.$db, self::$username, self::$password);
      $this->_handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $this->_handle->query('SET NAMES UTF8');
    } catch(Exception $e) {
      echo $e->getMessage();
    }
set error mode another way
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
set 'set names utf8' another way:
  $db = new PDO('mysql:host=localhost;dbname=something', 'username', 'password', array(
      PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
      PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
  );
closing the connection, if you want, not needed
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here

// and now we're done; close it
$dbh = null;
prepared statement, binding with bindParam
    $stmt = $this->db->prepare('SELECT * FROM '.$this->table.' WHERE '.$this->primary_key.' = :id AND domain IN '.$domains);
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if(count($row) == 1) {
binding with execute:
            $pre = $this->db->prepare('INSERT INTO '.$this->table.' ('.implode(', ', array_keys($fields)).') VALUES ('.$question_marks.')');
            $pre->execute(array_values($fields));
key-pair fetch:
$items = $this->db->query('SELECT '.$this->primary_key.', '.$this->name_field.' FROM '.$this->table.' WHERE domain IN '.$domains.' ORDER BY '.$this->name_field)->fetchAll(PDO::FETCH_KEY_PAIR);
fetch with query and fetch:
  $packages = $db->query('SELECT * FROM package_translation');
  foreach($packages as $package) {
    echo $package['name'].'
'; } $stmt = $db->query('SELECT * FROM package_translation'); $result = $stmt->setFetchMode(PDO::FETCH_NUM); while ($row = $stmt->fetch()) { print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n"; }
affected rows (insert, update, delete):
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();

/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
count rows:
  $sql = "SELECT COUNT(*) FROM package_translation";
  if ($res = $db->query($sql)) {
  
      /* Check the number of rows that match the SELECT statement */
    if ($res->fetchColumn() > 0) {
  
          /* Issue the real SELECT statement and work with the results */
           $sql = "SELECT * FROM package_translation";
         foreach ($db->query($sql) as $row) {
             print "Name: " .  $row['name'] . "\n";
           }
      }
      /* No rows matched -- do something else */
    else {
        print "No rows matched the query.";
      }
  }
  
  $res = null;
  $conn = null;

SPL Autoloader

class Autoloader {

  public static function autoload($classname) {

    if(file_exists('../lib/'.$classname . '.class.php')) {
      include_once($classname . '.class.php');
    } else {
      include_once('../lib/model/'.$classname . '.class.php');
    }

    if (!class_exists($classname)) {
      throw new MyException("Class '$classname' not found", 7);
    }

  }

}

spl_autoload_register(array('Autoloader', 'autoload'));

Thursday, January 17, 2013

Copy MySQL Database to Another Database

mysqldump -h [server] -u [user] -p[password] db1 | mysql -h [server] -u [user] -p[password] db2

Monday, December 10, 2012

Reload Cached CSS / JS Files in Symfony

An elegant way to force browsers to reload cached CSS / JS files in Symfony 1.4

settings.yml
Add Asset, CSSCache, JSCache to the standard_helpers row:
standard_helpers: [ Partial, Cache, I18N, Date, Asset, CSSCache, JSCache ]
lib/helper/CSSCacheHelper.php
function include_versioned_stylesheets()
{
  $response = sfContext::getInstance()->getResponse();
  sfConfig::set('symfony.asset.stylesheets_included', true);
  $html = '';
  foreach ($response->getStylesheets() as $file => $options) {
    $filepath = sfConfig::get('sf_web_dir') . '/' .  stylesheet_path($file);
    if(file_exists($filepath)) {
      $file .= '?v=' . filectime($filepath);
    }
    $html .= stylesheet_tag($file, $options);
  }
  echo $html;
}
lib/helper/JSCacheHelper.php
function include_versioned_javascripts()
{
  $response = sfContext::getInstance()->getResponse();
  sfConfig::set('symfony.asset.javascripts_included', true);
  $html = '';
  foreach ($response->getJavascripts() as $file => $options) {
    $filepath = sfConfig::get('sf_web_dir') . '/' .  javascript_path($file);
    if(file_exists($filepath)) {
      $file .= '?v=' . filectime($filepath);
    }
    $html .= javascript_include_tag($file, $options);
  }
  echo $html;
}
apps/xxx/templates/layout.php
Use the include_versioned_stylesheets() and include_versioned_javascripts() functions to load css and js files, instead of the default include_stylesheets() and include_javascripts() functions.

Tuesday, December 4, 2012

Display Image with Original Size in TCPDF

$pdf->setImageScale(1.53); makes an ability to display pictures in original dimensions, with no blur. Also beware to call setImageScale() before AddPage:
$pdf->setImageScale(1.53);
$pdf->AddPage();
Source: http://sourceforge.net/p/tcpdf/discussion/435311/thread/404343d4

Monday, December 3, 2012

Enable CKFinder in CKEditor

     

Wednesday, November 28, 2012

Format Date in Admin Generator in Symfony

For example, on the index/list page...
    config:
      actions: ~
      fields:  ~
      list:    
        display: [_id, Partner, name, valid_from, valid_to]
        fields: 
          valid_from: { date_format: yyyy-MM-dd }
          valid_to: { date_format: yyyy-MM-dd }

Friday, November 16, 2012

Add AJAX Request to Google Analytics

If you use jQuery you can bind to the global AjaxComplete event to fire a Pageview everytime an Ajax call completes:
jQuery(document).ajaxComplete(function(e, xhr, settings){
  var d = document.location.pathname + document.location.search + document.location.hash;
  _gaq.push(['_trackPageview', d]);
});
Source: http://stackoverflow.com/questions/7737549/google-analytics-and-loading-a-page-using-ajax-get-request

Sunday, October 28, 2012

FreeTDS Output Parameter Not Return to PHP

I had a stored procedure that returned with the output parameter (I found it in the FreeTDS log file) but the variable of the output parameter was blank in PHP. I checked the stored procedure and I found a stupid 'select @foo' selection in the procedure, before the initialization of the output parameter (set @output='bar'). I commented the selection (--select @foo) and now it works like a charm, the value of ouput parameter is available in the output PHP variable. I hope this helps you.

Tuesday, October 16, 2012

Native SQL Query in Doctrine

Examples...
// get Doctrine_Connection object
$con = Doctrine_Manager::getInstance()->connection();
// execute SQL query, receive Doctrine_Connection_Statement
$st = $con->execute("...............");
// fetch query result
$result = $st->fetchAll();
Or with parameter...
$db = Doctrine_Manager::getInstance()->connection();
$query = $db->prepare("INSERT INTO search_term (term, counter) VALUES (:term, '1') ON DUPLICATE KEY UPDATE counter=counter+1;");
$query->execute(array('term' => $search));

mb_ucfirst

function mb_ucfirst($string, $encoding)
{
    $strlen = mb_strlen($string, $encoding);
    $firstChar = mb_substr($string, 0, 1, $encoding);
    $then = mb_substr($string, 1, $strlen - 1, $encoding);
    return mb_strtoupper($firstChar, $encoding) . $then;
}

Tuesday, September 25, 2012

Do Not Save Null Values in Embedded Form in Symfony

Think there is a Product object with many ProductPrice objects. The Product form contains some ProductPrice forms as embed forms. Prices are not mandatory fields. Now if you save the form, there will be null price rows in the ProductPrice table. Do the following in the ProductPrice model(!) class!
  public function save(Doctrine_Connection $conn = null)
  {
    if($this->price > 0)
    {
      return parent::save();
    }
    else
    {
      $this->delete();
      return null;
    }
  }
This will check the price (there is a price field in the ProductPrice table) is greater than 0 or not. If greater, it will save to the database. If not, it will delete the row in the table (if presents) and stop the saving process for this price object.

Doctrine: SQLSTATE[23000]: Integrity constraint violation duplicate entry

If you are using a table where some fields are I18N and ex. the title field is sluggable, you will realize that you cannot update(!) the object with the same title. See an example:

The page is multilingual (Hungarian and English). You create a product with TEFAL XY Hungarian and TEFAL XY English tilte (the same title used in each language). You can saved the form / object, it created successfully. Now you change the Hungarian title to TEFAL X. Save. Then change the English title to TEFAL X, too. You will get an error:

Doctrine: SQLSTATE[23000]: Integrity constraint violation duplicate entry

This is a bug in doctrine 1.2.x.

Solution
  1. Copy lib / vendor / symfony / lib / plugins / sfDoctrinePlugin / lib / vendor / doctrine / Doctrine / Template / Listener / Sluggable.php inside your own lib directory.
  2. In the getUniqueSlug method, change this line:
    $whereString .= ' AND r.' . implode(' != ? AND r.', $table->getIdentifierColumnNames()) . ' != ?';
    to this:
    $whereString .= ' AND (r.' . implode(' != ? OR r.', $table->getIdentifierColumnNames()) . ' != ?)';
  3. Save. Clear cache. Be happy.

Monday, September 24, 2012

Hide Errors at Top of the Embed Form in Symfony

If you use embed forms, you will realise that the validatation errors appear twice, once near the input fields (in the embed form) and once at top of the embed form. To solve this....

I'm using the jroller plugin to generate auto admin:

plugins / sfAdminThemejRoller / data / generator / sfDoctrineModule / jroller / template / templates / _form_field.php

Use this (my solution):


    [?php if ($form[$name]->hasError() && get_class($form[$name]) != 'sfFormFieldSchema'): ?]
        [?php echo $form[$name]->renderError() ?]
    [?php endif; ?]

Thursday, September 20, 2012

MySQL Tuning

  1. Optimize tables (to correct overheads)
  2. Set query cache size bigger if Qcache_lowmem_prunes (on the runtime information page) is red.
Useful commands:

  • Show all query cache settings:
    SHOW VARIABLES LIKE  '%query_cache%';
  • Set a bigger query cache size (256 MB) ON RUNTIME:
    SET GLOBAL query_cache_size = 256000000;
  • Set a bigger query cache size in config (will work after mysql restart):
    /etc/mysql/my.cnf
    Search for "query_cache_size" then change...
    query_cache_size = 256M

Saturday, September 15, 2012

Install Symfony 2 on Debian

  1. Download the Standard version and put the Symfony folder to the root.
  2. Open /Symfony/web/config.php with browser to check the configuration. If needed, remove the ip address check from the begining of the file. I had to install things and do some changes:

    apt-get update
    apt-get install php-pear php5-dev apache2-threaded-dev build-essential libicu-dev
    pecl install apc
    pecl install intl

    php.ini:
    short_open_tag = Off
    date.timezone = Europe/Budapest (for me)
    extension = apc.so
    extension = intl.so


    Save then restart apache.

Friday, September 14, 2012

Filter Data On Frontend with Symfony Form Filter

Source: http://stackoverflow.com/questions/3765495/symfony-how-to-filter-data-on-the-frontend-like-in-the-backend

If you want to do it exactly like it is done on the backend, you can use the admin generator on frontend applications. A more general and customizable way would be to simply create list and filter actions and use Symfony's form filters. Here's a basic example for a model class "Article":

In an actions class:
class articleActions extends sfActions
{
  public function executeList(sfWebRequest $request)
  {
    $this->form = new ArticleFormFilter();
    $this->pager = new sfDoctrinePager('Article');
  }

  public function executeFilter(sfWebRequest $request)
  {
    $this->form = new ArticleFormFilter();
    $this->form->bind($request[$this->form->getName()]);
    if ($this->form->isValid())
    {
      $this->pager = new sfDoctrinePager('Article');
      $this->pager->setQuery($this->form->getQuery());
      $this->setTemplate('list');
    }
    //handle invalid form here
  }
}
In view, iterate throw pager like this:
foreach($pager->getResults() as $article)
Doctrine FormFilter's are fairly similar to Doctrine forms. Get started by configuring the form inside of FormFilter::configure();

ob_start: PHP Output To Variable / String

<?php ob_start(); ?>
Hello world, <?php echo "My Website"; ?>
<?php include('something.php') ?>
Thank you.
<?php $var = ob_get_clean(); ?>

Friday, September 7, 2012

The user specified as a definer ('root'@'%') does not exist

Solution:
mysql -u root -p
grant all privileges on *.* to `root`@`%` identified by 'password';
flush privileges;

Install Apache 2, PHP 5, MySQL 5 on Debian

apt-get update

apt-get install apache2
apt-get install php5
apt-get install libapache2-mod-php5
apt-get install mysql-server mysql-client mysql-common php5-mysql
apt-get install php5-xsl php5-gd php5-curl

Install the Latest APC on Debian
Install PHPMYADMIN on Debian