Wednesday, May 1, 2013

Rollback or Commit with PDO transaction using php and mysql

A transaction should end with either a rollback() or a commit(), (only one of them).
In case you are using MySQL, make sure you are not using MyISAM engine for tables, as it doesn't support transactions. It usually support InnoDB.
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.


$dbh = null;
try {
    $dbh = new PDO("mysql:host=HOST_NAME;dbname=DB_NAME", "DB_USER_NAME", "DB_USER_PASSWORD");

    /*** Set the PDO error mode to exception (will throw exception if any error occurred) ***/
    /*** Follow the link for more info: http://php.net/manual/en/pdo.setattribute.php ***/
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);

    /*** Creating a test table if not exists ***/
    $table = "CREATE TABLE IF NOT EXISTS test_transaction ( " .
        "id MEDIUMINT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY, ".
        "name VARCHAR(25) NOT NULL, designation VARCHAR(25) NULL )";
    $dbh->exec($table);

    /*** Transaction block starting here ***/
    $dbh->beginTransaction();

    /*** Inserting some data ***/
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #1', '')");
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #2', '')");

    /*** The following query result 2 outputs ***/
    $result = $dbh->query("SELECT * FROM test_transaction");
    echo "<pre>";
    print_r($result->fetchAll());
    echo "</pre>";

    /*** Again inserting some more data ***/
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #1', 'Designation #1')");
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #2', 'Designation #2')");
    $dbh->exec("INSERT INTO test_transaction VALUES(NULL, 'Pritom #3', 'Designation #3')");

    /*** The following query result 5 outputs ***/
    $result = $dbh->query("SELECT * FROM test_transaction");
    echo "<pre>";
    print_r($result->fetchAll());
    echo "</pre>";

    /*** Throwing an exception to test if transaction really works ***/
    throw new Exception("All data will be erased during this transaction");
}
catch(Exception $ex) {
    $dbh->rollback();

    /*** The following query result 0 outputs as transaction failed ***/
    $result = $dbh->query("SELECT * FROM test_transaction");
    echo "<pre>";
    print_r($result->fetchAll());
    echo "</pre>";

    echo "Exception: ".$ex->getMessage();
    die();
}


Output be as follows:

Array
(
    [0] => Array
        (
            [id] => 29
            [0] => 29
            [name] => Pritom #1
            [1] => Pritom #1
            [designation] => 
            [2] => 
        )

    [1] => Array
        (
            [id] => 30
            [0] => 30
            [name] => Pritom #2
            [1] => Pritom #2
            [designation] => 
            [2] => 
        )

)

Array
(
    [0] => Array
        (
            [id] => 29
            [0] => 29
            [name] => Pritom #1
            [1] => Pritom #1
            [designation] => 
            [2] => 
        )

    [1] => Array
        (
            [id] => 30
            [0] => 30
            [name] => Pritom #2
            [1] => Pritom #2
            [designation] => 
            [2] => 
        )

    [2] => Array
        (
            [id] => 31
            [0] => 31
            [name] => Pritom #1
            [1] => Pritom #1
            [designation] => Designation #1
            [2] => Designation #1
        )

    [3] => Array
        (
            [id] => 32
            [0] => 32
            [name] => Pritom #2
            [1] => Pritom #2
            [designation] => Designation #2
            [2] => Designation #2
        )

    [4] => Array
        (
            [id] => 33
            [0] => 33
            [name] => Pritom #3
            [1] => Pritom #3
            [designation] => Designation #3
            [2] => Designation #3
        )

)

Array
(
)

Exception: All data will be erased during this transaction

Tuesday, April 30, 2013

Get document root path using yii application

dirname(Yii::app()->request->scriptFile)

CGridView a CLinkColumn with sortable header using yii

I have it working with the latest yii (non-stable but might work with the current stable release). (could do with some improvement but it does what I need)

Try this; create a new component under components/SCLinkColumnWithSort.php

<?php
class SCLinkColumnWithSort extends CLinkColumn
{

  public $name;
  public $sortable = true;
  public $filter;

  protected function renderFilterCellContent()
  {
    $this->linkHtmlOptions['class'] = $this->name;
    if($this->filter!==false && $this->grid->filter!==null && strpos($this->name,'.')===false)
    {
      if(is_array($this->filter))
        echo CHtml::activeDropDownList($this->grid->filter, $this->name, $this->filter, array('id'=>false,'prompt'=>''));
      else if($this->filter===null)
        echo CHtml::activeTextField($this->grid->filter, $this->name, array('id'=>false));
      else
        echo $this->filter;
    }
    else
      parent::renderFilterCellContent();
  }

  protected function renderHeaderCellContent()
  {
    if($this->grid->enableSorting && $this->sortable && $this->name!==null)
      echo $this->grid->dataProvider->getSort()->link($this->name,$this->header);
    else
      parent::renderHeaderCellContent();
  }

}
?> 
Use this as following: 

<?php
$this->widget('zii.widgets.grid.CGridView', array(
  'dataProvider' => $dataProvider,
  'columns' => array(
    array(
      'class' => 'SCLinkColumnWithSort',
      'name' => 'column_name_to_sort',
     )
  )
))
?> 
 
Or you can directly use, but upper one used for more customization:
array(
  'name' => 'mobile_number',
  'type' => 'raw',
  'value' => 'CHtml::link($data->mobile_number,$data->contact_id)'
) 
Where mobile_number is filed value in name, in value, mobile_number is for sorting
and contact_id is for making link.

Monday, April 29, 2013

Create and download csv file from array using php


Create and download csv file from array using php.
<?php
function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $outputString = "";
    foreach($fields as $tempFields) {
        $output = array();
        foreach ( $tempFields as $field ) {
            if ($field === null && $nullToMysqlNull) {
                $output[] = "NULL";
                continue;
            }

            // Enclose fields containing $delimiter, $enclosure or whitespace
            if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
                $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
            }
            else {
                $output[] = $field;
            }
        }
        $outputString .= implode( $delimiter, $output )."\n";
    }
    return $outputString;
}
?>
Use:
<?php
$dataArray = array();
array_push($dataArray, array(
    "First Name",
    "Last Name",
    "Number",
    "Group"
));
foreach($dataList as $index => $data) {
    array_push($dataArray, array(
        "".$data["first_name"],
        "".$data["last_name"],
        "".$data["mobile_number"],
        "".$data["group_name"]
    ));
}
$csvString = arrayToCsv($dataArray);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=list.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $csvString;
?>

Php check a value exists in multi level array and return path

Search in array using php by value if the array is any depth data.
<?php
function array_value_exists($search = "", $searchArray = array(), $returnKey = false, &$returnKeyArray = array(), $level = 0) {
    $returnValue = false;
    $search = trim(strval($search));
    if(strlen($search) == 0) {
        return false;
    }
    if(is_null($searchArray)) {
        return false;
    }
    if(!is_array($searchArray)) {
        return false;
    }
    foreach($searchArray as $key => $value) {
        array_push($returnKeyArray, $key);
        if(is_string($value)) {
            if($search == trim($value)) {
                $returnValue = true;
                break;
            }
        } else if(is_array($value)) {
            $returnValue = array_value_exists($search, $value, false, $returnKeyArray);
            if($returnValue == true) {
                break;
            }
        }
    }
    if($returnKey == true) {
        return $returnKeyArray;
    }
    return $returnValue;
}
?>

Use:<?php
$ary = array(
            "bm" => array(
                "dev" => array(
                    "pritom" => array(
                        "email" => "pritomkucse@yahoo.com"
                    ),
                    "touhid" => array(
                        "email" => "touhid@yahoo.com"
                    )
                ),
                "designer" => array(
                    "dipu" => array(
                        "email" => "dipu@yahoo.com"
                    )
                )
            ),
            "gpit" => array(
                "dev" => array(
                    "sanat" => array(
                        "email" => "sanat@gpit.com"
                    )
                )
            )
        );
        $has = array_value_exists("pritomkucse@yahoo.com", $ary);
        echo $has == true ? "True" : "False";
        print_r(array_value_exists("pritomkucse@yahoo.com", $ary, true));
?>

Output:
1. True (Find or not)
2. Path to this value.
Array
(
    [0] => bm
    [1] => dev
    [2] => pritom
    [3] => email
)

Read and parse csv file using php code

Details http://code.google.com/p/parsecsv-for-php/
Or download from here

Use:

require_once('../parsecsv.lib.php');
# create new parseCSV object.
$csv = new parseCSV();
# Parse '_books.csv' using automatic delimiter detection...

$csv->conditions = 'author does not contain dan brown';
$csv->conditions = 'rating < 4 OR author is John Twelve Hawks';
$csv->conditions = 'rating > 4 AND author is Dan Brown';

$csv->sort_by = 'title';

# offset from the beginning of the file,
# ignoring the first X number of rows.
$csv->offset = 2;

# limit the number of returned rows.
$csv->limit = 3;

$csv->auto('_books.csv');

foreach ($csv->titles as $value);
foreach ($csv->data as $key => $row);

Saturday, April 27, 2013

Android custom dialog example

In this tutorial, we show you how to create a custom dialog in Android. See following steps :
  1. Create a custom dialog layout (XML file).
  2. Attach the layout to Dialog.
  3. Display the Dialog.
  4. Done.

1 Android Layout Files

Two XML files, one for main screen, one for custom dialog.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login Dialog" />
 
</LinearLayout>
File : res/layout/login.xml

<?xml version="1.0" encoding="UTF-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tableLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/sldjfsjdflsdf"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:src="@drawable/user" />

            <EditText
                android:id="@+id/editText1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <requestFocus />
            </EditText>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:src="@drawable/password" />

            <EditText
                android:id="@+id/editText2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:inputType="textPassword" />

        </LinearLayout>

        <Button
            android:id="@+id/btnLoginPrompt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login" />

    </TableLayout>
    
Read the comment and demo in next step, it should be self-explorary.

Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {   
 public void onClick(View arg0) {
  final Dialog dialog = new Dialog(ContactspaceandroidActivity.this);
  dialog.setContentView(R.layout.login);
  dialog.setTitle("Title...");
  
  dialog.show();
  
  Button azxc = (Button) dialog.findViewById(R.id.btnLoginPrompt);
  azxc.setOnClickListener(new OnClickListener() {    
   @Override
      public void onClick(View arg0) {
       System.out.println("BTN LOGIN CLICKED.");
       EditText txtUserName = (EditText) dialog.findViewById(R.id.txtUserName);
       EditText txtPassword = (EditText) dialog.findViewById(R.id.txtPassword);
       if(txtUserName.getText().length() <= 0) {
        Toast.makeText(ContactspaceandroidActivity.this, "Enter username.", Toast.LENGTH_LONG).show();
        return;
       }
       if(txtPassword.getText().length() <= 0) {
        Toast.makeText(ContactspaceandroidActivity.this, "Enter password.", Toast.LENGTH_LONG).show();
        return;
       }
      }
  });    
 }
});