Wednesday, December 29, 2010

array in php

array_combine: php 5.x

This function takes two arrays and puts them together, though not in the way you might think at first. This function takes the first array and uses it as the keys for your new array. It then takes the second array and uses it as the values for your new array. It is important to ensure that both of your input arrays have the same number of elements. If they don’t, the function will return boolean FALSE rather than returning your new array.

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>
The above example will output:

Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)


array_flip — Exchanges all keys with their associated values in an array

$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>
now $trans is:

Array
(
[1] => b
[2] => c
)

array_product — Calculate the product of values in an array


$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";

?>
The above example will output:

product(a) = 384

array_merge — Merge one or more arrays
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
The above example will output:

Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)

Zend for beginners

The Bootstrap
Your Bootstrap class defines what resources and components to initialize. By default, Zend Framework's Front Controller is initialized, and it uses the application/controllers/ as the default directory in which to look for action controllers (more on that later). The class looks like the following:

1.// application/Bootstrap.php
2. 
3.class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
4.{
5.}

Your application's action controllers contain your application workflow, and do the work of mapping your requests to the appropriate models and views.
An action controller should have one or more methods ending in "Action"; these methods may then be requested via the web. By default, Zend Framework URLs follow the schema /controller/action, where "controller" maps to the action controller name (minus the "Controller" suffix) and "action" maps to an action method (minus the "Action" suffix).
1.// application/controllers/IndexController.php
2. 
3.class IndexController extends Zend_Controller_Action
4.{
5. 
6.    public function init()
7.    {
8.        /* Initialize action controller here */
9.    }
10. 
11.    public function indexAction()
12.    {
13.        // action body
14.    }
15.}

Views in Zend Framework are written in plain old PHP. View scripts are placed in application/views/scripts/, where they are further categorized using the controller names.

[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.view[] =
resources.db.adapter = "PDO_SQLITE"
resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook.db"
 
[staging : production]
 
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.db.adapter = "PDO_SQLITE"
resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-testing.db"
 
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.db.adapter = "PDO_SQLITE"
resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-dev.db"

layout()->content ?>

We grab our application content using the layout() view helper, and accessing the "content" key.

1.// application/models/DbTable/Guestbook.php
2. 
3./**
4.* This is the DbTable class for the guestbook table.
5.*/
6.class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract
{
2.    /** Table name */
3.    protected $_name    = 'guestbook';
4.}

Zend_Loader::loadClass() to load classes.


To connect database:
1.$config = new Zend_Config(
2.    array(
3.        'database' => array(
4.            'adapter' => 'Mysqli',
5.            'params'  => array(
6.                'host'     => '127.0.0.1',
7.                'dbname'   => 'test',
8.                'username' => 'webuser',
9.                'password' => 'secret',
10.            )
11.        )
12.    )
13.);
14. 
15.$db = Zend_Db::factory($config->database);
OR
$pdoParams = array(
    PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
);
 
$params = array(
    'host'           => '127.0.0.1',
    'username'       => 'webuser',
    'password'       => 'xxxxxxxx',
    'dbname'         => 'test',
    'driver_options' => $pdoParams
);
 
$db = Zend_Db::factory('Pdo_Mysql', $params);

The second argument to fetchAll() is an array of values to substitute for parameter placeholders in the SQL statement.

The fetchAssoc() method returns data in an array of associative arrays, regardless of what value you have set for the fetch mode, using the first column as the array index.

1.$db->setFetchMode(Zend_Db::FETCH_OBJ);
2. 
3.$result = $db->fetchAssoc(
4.    'SELECT bug_id, bug_description, bug_status FROM bugs'
5.);
6. 
7.// $result is an array of associative arrays, in spite of the fetch mode
8.echo $result[2]['bug_description']; // Description of Bug #2
9.echo $result[1]['bug_description']; // Description of Bug #1

The fetchOne() method is like a combination of fetchRow() with fetchCol(), in that it returns data only for the first row fetched from the result set, and it returns only the value of the first column in that row.

You can add new rows to a table in your database using the insert() method. The first argument is a string that names the table, and the second argument is an associative array, mapping column names to data values.
1.$data = array(
2.    'created_on'      => '2007-03-22',
3.    'bug_description' => 'Something wrong',
4.    'bug_status'      => 'NEW'
5.);
6. 
7.$db->insert('bugs', $data);
The return value of the insert() method is not the last inserted ID, because the table might not have an auto-incremented column. Instead, the return value is the number of rows affected (usually 1).
If your table is defined with an auto-incrementing primary key, you can call the lastInsertId() method after the insert. This method returns the last value generated in the scope of the current database connection.
Example #19 Using lastInsertId() for an Auto-Increment Key
1.$db->insert('bugs', $data);
2. 
3.// return the last value generated by an auto-increment column
4.$id = $db->lastInsertId();
1.$data = array(
2.    'updated_on'      => '2007-03-23',
3.    'bug_status'      => 'FIXED'
4.);
5. 
6.$where[] = "reported_by = 'goofy'";
7.$where[] = "bug_status = 'OPEN'";
8. 
9.$n = $db->update('bugs', $data, $where);
10. 
11.// Resulting SQL is:
12.//  UPDATE "bugs" SET "update_on" = '2007-03-23', "bug_status" = 'FIXED'
13.//  WHERE ("reported_by" = 'goofy') AND ("bug_status" = 'OPEN')
Deleting Rows
1.$n = $db->delete('bugs', 'bug_id = 3');
Using quote()
1.$name = $db->quote("O'Reilly");
2.echo $name;
3.// 'O\'Reilly'
4. 
5.$sql = "SELECT * FROM bugs WHERE reported_by = $name";
6. 
7.echo $sql;
8.// SELECT * FROM bugs WHERE reported_by = 'O\'Reilly'
Closing a Database Connection
1.$db->closeConnection();
server version before running a query
1.$version = $db->getServerVersion();

zend_Acl:

Zend_Acl provides a lightweight and flexible access control list (ACL) implementation for privileges management. In general, an application may utilize such ACL's to control access to certain protected objects by other requesting objects.
For the purposes of this documentation:
a resource is an object to which access is controlled.
a role is an object that may request access to a Resource.
Put simply, roles request access to resources. For example, if a parking attendant requests access to a car, then the parking attendant is the requesting role, and the car is the resource

$acl = new Zend_Acl();
1. 
2.$acl->addRole(new Zend_Acl_Role('guest'))
3.    ->addRole(new Zend_Acl_Role('member'))
4.    ->addRole(new Zend_Acl_Role('admin'));
5. 
6.$parents = array('guest', 'member', 'admin');
7.$acl->addRole(new Zend_Acl_Role('someUser'), $parents);
8. 
9.$acl->add(new Zend_Acl_Resource('someResource'));
10. 
11.$acl->deny('guest', 'someResource');
12.$acl->allow('member', 'someResource');
13. 
14.echo $acl->isAllowed('someUser', 'someResource') ? 'allowed' : 'denied';
the example code would print "allowed".

$acl = new Zend_Acl();
1. 
2.$roleGuest = new Zend_Acl_Role('guest');
3.$acl->addRole($roleGuest);
4.$acl->addRole(new Zend_Acl_Role('staff'), $roleGuest);
5.$acl->addRole(new Zend_Acl_Role('editor'), 'staff');
6.$acl->addRole(new Zend_Acl_Role('administrator'));
7. 
8.// Guest may only view content
9.$acl->allow($roleGuest, null, 'view');
10. 
11./*
12.Alternatively, the above could be written:
13.$acl->allow('guest', null, 'view');
14.//*/
15. 
16.// Staff inherits view privilege from guest, but also needs additional
17.// privileges
18.$acl->allow('staff', null, array('edit', 'submit', 'revise'));
19. 
20.// Editor inherits view, edit, submit, and revise privileges from
21.// staff, but also needs additional privileges
22.$acl->allow('editor', null, array('publish', 'archive', 'delete'));
23. 
24.// Administrator inherits nothing, but is allowed all privileges
25.$acl->allow('administrator');
echo $acl->isAllowed('guest', null, 'view') ?
     "allowed" : "denied";
// allowed
 
echo $acl->isAllowed('staff', null, 'publish') ?
     "allowed" : "denied";
// denied
 
echo $acl->isAllowed('staff', null, 'revise') ?
     "allowed" : "denied";
// allowed
 
echo $acl->isAllowed('editor', null, 'view') ?
     "allowed" : "denied";
// allowed because of inheritance from guest
 
echo $acl->isAllowed('editor', null, 'update') ?
     "allowed" : "denied";
// denied because no allow rule for 'update'
 
echo $acl->isAllowed('administrator', null, 'view') ?
     "allowed" : "denied";
// allowed because administrator is allowed all privileges
 
echo $acl->isAllowed('administrator') ?
     "allowed" : "denied";
// allowed because administrator is allowed all privileges
 
echo $acl->isAllowed('administrator', null, 'update') ?
     "allowed" : "denied";
// The new marketing group inherits permissions from staff
1.$acl->addRole(new Zend_Acl_Role('marketing'), 'staff');
// newsletter
$acl->addResource(new Zend_Acl_Resource('newsletter'));
 
// news
$acl->addResource(new Zend_Acl_Resource('news'));
 
// latest news
$acl->addResource(new Zend_Acl_Resource('latest'), 'news');
 
// announcement news
$acl->addResource(new Zend_Acl_Resource('announcement'), 'news');
// Marketing must be able to publish and archive newsletters and the
1.// latest news
2.$acl->allow('marketing',
3.            array('newsletter', 'latest'),
4.            array('publish', 'archive'));
5. 
6.// Staff (and marketing, by inheritance), are denied permission to
7.// revise the latest news
8.$acl->deny('staff', 'latest', 'revise');
9. 
10.// Everyone (including administrators) are denied permission to
11.// archive news announcements
12.$acl->deny(null, 'announcement', 'archive');
echo $acl->isAllowed('staff', 'newsletter', 'publish') ?
1.     "allowed" : "denied";
2.// denied 
3.echo $acl->isAllowed('marketing', 'newsletter', 'publish') ?
4.     "allowed" : "denied";
5.// allowed 
6.echo $acl->isAllowed('staff', 'latest', 'publish') ?
7.     "allowed" : "denied";
8.// denied 
9.echo $acl->isAllowed('marketing', 'latest', 'publish') ?
10.     "allowed" : "denied";
11.// allowed 
12.echo $acl->isAllowed('marketing', 'latest', 'archive') ?
13.     "allowed" : "denied";
14.// allowed 
15.echo $acl->isAllowed('marketing', 'latest', 'revise') ?
16.     "allowed" : "denied";
17.// denied 
18.echo $acl->isAllowed('editor', 'announcement', 'archive') ?
19.     "allowed" : "denied";
20.// denied 
21.echo $acl->isAllowed('administrator', 'announcement', 'archive') ?
22.     "allowed" : "denied";
23.// denied
Zend_Form
$form = new Zend_Form();
1.$form->setAction('/user/login')
2.     ->setMethod('post');
3. 
4.// Create and configure username element:
5.$username = $form->createElement('text', 'username');
6.$username->addValidator('alnum')
7.         ->addValidator('regex', false, array('/^[a-z]+/'))
8.         ->addValidator('stringLength', false, array(6, 20))
9.         ->setRequired(true)
10.         ->addFilter('StringToLower');
11. 
12.// Create and configure password element:
13.$password = $form->createElement('password', 'password');
14.$password->addValidator('StringLength', false, array(6))
15.         ->setRequired(true);
16. 
17.// Add elements to form:
18.$form->addElement($username)
19.     ->addElement($password)
20.     // use addElement() as a factory to create 'Login' button:
21.     ->addElement('submit', 'login', array('label' => 'Login'));

The Registry

A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. This mechanism is an alternative to using global storage.
The typical method to use registries with Zend Framework is through static methods in the Zend_Registry class.

Thursday, April 29, 2010

To disable right click:
Note1:The following script works for IE6 and Netscape.

Note2:Right click cannot be disabled for Opera browsers!


<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;

if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);

function mischandler(){
return false;
}

function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;

Tuesday, February 2, 2010

Mysql Help

Get database size:
SELECT table_schema "Data Base Name", sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB"
FROM information_schema.TABLES GROUP BY table_schema ; 

 
use REPLACE in mysql:
UPDATE table_name SET column_name = REPLACE(column_name,”original_string”,”replace_string”)

concate & replace extra space if any field is missing
SELECT CONCAT(COALESCE(CONCAT(salutation,' '),''),COALESCE(CONCAT(first_name,' '),''),COALESCE(surname,'')) DriverName

//to check mysql version from query
select version();

Sort in ENUM fields :
To sort in ENUM fields using ORDER BY clause on  use one of these techniques:
  • Specify the ENUM list in alphabetic order.:
    like : ORDER BY FIELD(alert_type,'For Sale','For Rent','Sale Agreed') desc
  • Make sure that the column is sorted alphabetically rather than by index number by coding ORDER BY CAST(col AS CHAR) or ORDER BY CONCAT(col)
Create Wordcase in mysql :
update survey_event_question_langs set response1= CONCAT(LEFT(`response1`, 1),lower(
SUBSTRING(`response1`, 2)))