Cakephp HABTM (Has and Belongs to Many)

1st Aug 2013 at 2:28 PM | Posted in CAKEPHP, PHP | Leave a comment

HABTM is toughest model association in Cakephp. Lets explore this:
There are many mobile phones and they have many features, this can be good example of HABTM.
A mobile may have many features and a feature may belongs to many mobiles.

Create Below tables:
CREATE TABLE IF NOT EXISTS `cake_mobiles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)


CREATE TABLE IF NOT EXISTS `cake_features` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)


CREATE TABLE IF NOT EXISTS `cake_features_mobiles` (
`mobile_id` int(11) NOT NULL,
`feature_id` int(11) NOT NULL
)



Create File: app\Controller\MobilesController.php

<?php
class MobilesController extends AppController {
	public $uses	= array('Feature', 'Mobile');
	
	function index() {
		$data	= $this->Mobile->find('all');
		$this->set('data',$data);
	}
	function add($id=null) {
		if ($this->data) {	
			if($this->Mobile->save($this->data)) {
				$this->Session->setFlash('Category has been saved.');
				$this->redirect(array('controller'=>'mobiles','action'=>'index'));
			}
        }
		if($id) {
			$this->Mobile->id = $id;
			$this->request->data = $this->Mobile->read();
			
		}
		$features	= $this->Feature->find('list');
		$this->set('features',$features);
	}
	function delete($id) {
		$this->Mobile->id = $id;
		$this->Mobile->delete();
		//$this->autoRender = false;
		$this->redirect(array('controller'=>'mobiles','action'=>'index'));
	}
}

Create model: app\Model\Mobile.php

<?php
Class Mobile extends AppModel {
	public $name	= 'Mobile';
	var $hasAndBelongsToMany = array('Feature'=>array('className'=>'Feature'));
	public $validate = array(
        'title'			=> array(
			'emptychk' 		=> array(
				'rule' 		=> 'notEmpty',
				'message' 	=> 'Title can not be left empty'
			),
			'duplicatechk' 	=> array(
				'rule' 		=> 'isUnique',
				'message' 	=> 'This Title is already Exists, Please enter different'
			)
		),
		'Feature' => array( 
            'multiple' => array( 
                'rule' => array('multiple',array('min' => 1)), 
                'message' => 'Please select at least 1 feature'), 
        ), 
	);
	
function beforeValidate() {
	foreach($this->hasAndBelongsToMany as $k=>$v) {
		if(isset($this->data[$k][$k]))
		{
			$this->data[$this->alias][$k] = $this->data[$k][$k];
		}
	}
}


}



View file: app\View\Mobiles\index.ctp

<?php echo $this->Html->link('Add',array('action'=>'add/'));?>
<table>
<tr>
	<th width="70%">Name</th>
	<th>Action</th>
</tr>

<?php foreach($data as $mobile) {?>
	<tr>
		<td><?php echo $mobile['Mobile']['title'];?></td>
		<td>
			<?php echo $this->Html->link('Edit',array('action'=>'add/'.$mobile['Mobile']['id']));?>
			<?php echo $this->Html->link('Delete',array('action'=>'delete/'.$mobile['Mobile']['id']),array('confirm' => 'Are you sure you want to delete this banner?'));?>
		</td>
	</tr>
<?php } ?>

</table>

View file: app\View\Mobiles\add.ctp

<?php 
echo $this->Session->flash();
echo $this->Form->create('Mobile');
echo $this->Form->input('title');

echo $this->Form->input('Feature', array(
                        'options' 	=> $features,
						'multiple'	=>'checkbox'
                        )
					);
echo $this->Form->input('id',array('type'=>'hidden'));
echo $this->Form->submit('Save',array('label'=>false));					
echo '<div class="actions">';
echo $this->Html->link('Cancel',array('action'=>'index'));
echo '</div>';

				
echo $this->Form->end();
?>

Now create files for features

File: app\Controller\FeaturesController.php

<?php
class FeaturesController extends AppController {
	public $uses	= array('Feature', 'Mobile');
	function index() {
		$data	= $this->Feature->find('all');
		$this->set('data',$data);
	}
	function add($id=null) {
		if ($this->data) {	
			if($this->Feature->save($this->data)) {
				$this->Session->setFlash('Feature has been saved.');
				$this->redirect(array('controller'=>'features','action'=>'index'));
			}
        }
		if($id) {
			$this->Feature->id = $id;
			$this->request->data = $this->Feature->read();
		}
		$mobiles	= $this->Mobile->find('list');
		$this->set('mobiles',$mobiles);
	}
	function delete($id) {
		$this->Feature->id = $id;
		$this->Feature->delete();
		$this->redirect(array('controller'=>'features','action'=>'index'));
	}
}

Model File : app\Model\Feature.php

<?php
Class Feature extends AppModel {
	public $name	= 'Feature';
	var $hasAndBelongsToMany = array('Mobile'=>array('className'=>'Mobile'));
	public $validate = array(
        'title'			=> array(
			'emptychk' 		=> array(
				'rule' 		=> 'notEmpty',
				'message' 	=> 'Title can not be left empty'
			),
			'duplicatechk' 	=> array(
				'rule' 		=> 'isUnique',
				'message' 	=> 'This Title is already Exists, Please enter different'
			)
		)
	);
}

View files: app\View\Features\index.ctp

<?php echo $this->Html->link('Add',array('action'=>'add'));?>
<table>
<tr>
	<th width="70%">Name</th>
	<th>Action</th>
</tr>

<?php foreach($data as $feature) {?>
	<tr>
		<td><?php echo $feature['Feature']['title'];?></td>
		<td>
			<?php echo $this->Html->link('Edit',array('action'=>'add/'.$feature['Feature']['id']));?>
			<?php echo $this->Html->link('Delete',array('action'=>'delete/'.$feature['Feature']['id']),array('confirm' => 'Are you sure you want to delete this banner?'));?>
		</td>
	</tr>
<?php } ?>

</table>

View files: app\View\Features\add.ctp

<?php 
echo $this->Session->flash();
echo $this->Form->create('Feature');
echo $this->Form->input('title');

echo $this->Form->input('id',array('type'=>'hidden'));

echo $this->Form->input('Mobile', array(
                        'options' 	=> $mobiles,
						'multiple'	=>'checkbox'
                        )
					);

					
					
echo $this->Form->submit('Save',array('label'=>false));					
echo '<div class="actions">';
echo $this->Html->link('Cancel',array('action'=>'index'));
echo '</div>';

				
echo $this->Form->end();
?>

Everything done. Have fun.

Jquery Selectors Quick Quide

9th Sep 2010 at 8:08 AM | Posted in Jquery | 1 Comment
$('select.foo option:selected').val();    // get the value from a dropdown select
$('select.foo').val();                    // get the value from a dropdown select even easier
$('input:checkbox:checked').val();        // get the value from a checked checkbox
$('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons

Radio Button:

jQuery('#radio_form input:radio:checked').val();
$("#myform input[type='radio']:checked").val();
$('input:radio[name=bar]:checked').val();
$("input[@name='rdio']:checked") . Val();

Checkbox:

$('input:checkbox:checked').val();
$('#checkBox').attr('checked');
$('#edit-checkbox-id').is(':checked');

$("input[@type=checkbox][@checked]").each(
function(){
// Insert code here
} );

$("input[@name='chkBox']").click(function(){
// your code here
});

$("input[type='checkbox']:checked").each(function(){
//Insert code here
});

Drop Down:

$("select option:selected").each(function () {
/Insert cod here
});

Get Selected value:
$('#selectId :selected').val()

Get Selected value Text:
$(<'#selectId :selected').text()

Get Selected Values:
$(document).ready(function() {
$("#a").click(function(){
$("select option:selected").each(function(){
alert($(this).val());//you can create an array here
});
});
});

WordPress Logiin failed redirects to admin login page

13th Jul 2012 at 8:18 AM | Posted in Wordpress | Leave a comment

In front end login for if you use action to wp-login.php and when user give invalid login details it redirects to admin login page.

To get rid of this add the below code to your plugin page of theme’s functions.php

add_filter('authenticate', 'check_login', 10, 3);
function check_login($user, $username, $password) {
$user = get_userdatabylogin($username);
if($_POST['redirect_to'] =='your-redirect-to' &amp; !$user)
wp_redirect($_POST['redirect_to']);
}

Codeigniter Image Manupulation Example

7th Oct 2011 at 9:31 AM | Posted in PHP | 49 Comments

Create a folder “uploaded” where your “application” folder is. (Not inside “application” folder”). Create a sub folder “thumbs” inside “uploaded”. Put a font in system/fonts/arial.ttf (copy the font from your windows).

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Imagetest extends CI_Controller {
	function __construct() {
		parent::__construct();
		$this->load->helper('url');
	}
	function index() {
		$path = realpath(APPPATH . '../uploaded');
		$file = "asd.jpg";

$path = str_replace('\\','/',$path);
		$config = array(
			'source_image' => $path.'/'.$file,
			'new_image' => $path.'/thumbs/'.$file,
			'maintain_ration' => true,
			'width' => 150,
			'height' => 100,
			'x_axis' => '100',
			'y_axis' => '40',
			'rotation_angle' => '180',
			'wm_text'		=> 'Test asdfsda sa dsa dsa dsa a',
			'wm_type'		=> 'text',
			'wm_font_path'		=> 'system/fonts/arial.ttf',
			'wm_font_size'		=> '30',
			'wm_font_color'		=> 'FF0000',
			'wm_vrt_alignment'		=> 'bottom',
			'wm_hor_alignment'		=> 'center',
			'wm_padding'		=> '10'

		);
		print "<pre>";
		print_r($config);
		$this->load->library('image_lib', $config);

		//$this->image_lib->crop();
		//$this->image_lib->clear();
		$this->image_lib->resize();
		/*$this->image_lib->rotate();
		$this->image_lib->clear();
		if(!$this->image_lib->watermark()) {
			echo $this->image_lib->display_errors();
		}	*/
		$this->load->view('imagetest');
	}
}

Add field to media edit form

24th Jun 2011 at 10:14 AM | Posted in Wordpress | 3 Comments
<?php
// hook media edit form
add_filter("attachment_fields_to_edit", "my_image_attachment_fields_to_edit", null, 2); add_filter("attachment_fields_to_save", "my_image_attachment_fields_to_save", null, 2); function my_image_attachment_fields_to_edit($form_fields, $post) { 	// $form_fields is a special array of fields to include in the attachment form 	// $post is the attachment record in the database 	//     $post--->post_type == 'attachment'
	// (attachments are treated as posts in WordPress)

	// add our custom field to the $form_fields array
	// input type="text" name/id="attachments[$attachment->ID][custom1]"
	$checked = get_post_meta($post->ID, "_is_photo_gallery", true);
	if($checked){
		$is_checked="checked";
	}else{
		$is_checked='';
	}
	$form_fields["is_photo_gallery"] = array(
		"label" => __("Show In Photo Gallery"),
		"input" => "html", // this is default if "input" is omitted
		"html" => "<input id="attachments[{$post->ID}][is_photo_gallery]" type="checkbox" name="attachments[{$post->ID}][is_photo_gallery]" value="1" />"
	);
	// if you will be adding error messages for your field,
	// then in order to not overwrite them, as they are pre-attached
	// to this array, you would need to set the field up like this:
	//$form_fields["custom1"]["label"] = __("Custom Text Field");
	//$form_fields["custom1"]["input"] = "text";
	//$form_fields["custom1"]["value"] = get_post_meta($post->ID, "_custom1", true);

	return $form_fields;
}
function my_image_attachment_fields_to_save($post, $attachment) {
	// $attachment part of the form $_POST ($_POST[attachments][postID])
	// $post attachments wp post array - will be saved after returned
	//     $post['post_type'] == 'attachment'
	if( isset($attachment['is_photo_gallery']) ){
		// update_post_meta(postID, meta_key, meta_value);
		update_post_meta($post['ID'], '_is_photo_gallery', $attachment['is_photo_gallery']);
	}
	return $post;
}
?>

Output:

Add field to post/page edit form

24th Jun 2011 at 10:12 AM | Posted in Wordpress | 6 Comments
<?php
//hook admin edit page
add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
//save data
add_action( 'save_post', 'myplugin_save_postdata' );

/* Adds a box to the main column on the Post and Page edit screens */
function myplugin_add_custom_box() {
    add_meta_box(
        'myplugin_sectionid',
        __( 'Custom Text for Post', 'myplugin_customtext' ),
        'myplugin_inner_custom_box',
        'post'
    );
    add_meta_box(
        'myplugin_sectionid',
        __( 'Custom Text for Page', 'myplugin_customtext' ),
        'myplugin_inner_custom_box',
        'page'
    );
}
/* Prints the box content */
function myplugin_inner_custom_box() {
  // Use nonce for verification
  wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );
	global $post;
	$myplugin_customtext = get_post_meta($post->ID,'myplugin_customtext',true);
	$myplugin_description = get_post_meta($post->ID,'myplugin_description',true);
  // The actual fields for data entry
  echo '<p><label for="myplugin_new_field">';
       _e("Title", 'myplugin_customtext' );
  echo '</label></p>';
  echo '<div><input type="text" id="myplugin_customtext" name="myplugin_customtext" value="'.$myplugin_customtext.'" size="25" style="width:100%;" /></div>';

  echo '<p><label for="myplugin_new_field">';
       _e("Description", 'myplugin_customtext' );
  echo '</label></p>';
  echo '<div style="border:1px solid #DFDFDF;"><textarea id="myplugin_description" name="myplugin_description">'.$myplugin_description.'</textarea></div>';
?>
  <script type="text/javascript">
    jQuery(document).ready(function() {
    jQuery("#myplugin_description").addClass("mceEditor");
    if ( typeof( tinyMCE ) == "object" && typeof( tinyMCE.execCommand ) == "function" ) {
    tinyMCE.execCommand("mceAddControl", true, "myplugin_description");
    }
    });
  </script>
<?php
}
function myplugin_save_postdata( $post_id ) {
  // verify if this is an auto save routine.
  // If it is our form has not been submitted, so we dont want to do anything
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
      return;

  // verify this came from the our screen and with proper authorization,
  // because save_post can be triggered at other times

  if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
      return;

  // Check permissions
  if ( 'page' == $_POST['post_type'] )
  {
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
  }
  else
  {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return;
  }

  // OK, we're authenticated: we need to find and save the data
	$myplugin_customtext = $_POST['myplugin_customtext'];
	$myplugin_description = $_POST['myplugin_description'];

	 update_post_meta($post_id, "myplugin_customtext", $myplugin_customtext);
	 update_post_meta($post_id, "myplugin_description", $myplugin_description);
  // Do something with $mydata
  // probably using add_post_meta(), update_post_meta(), or
  // a custom table (see Further Reading section below)
   return true;
}
?>

Output:

Custom Comment Form in WordPress

24th Jun 2011 at 10:08 AM | Posted in Wordpress | 6 Comments
<?php
// get defaults
add_filter('comment_form_defaults','mytheme_comments_form_defaults');
// get default fields
add_filter( 'comment_form_default_fields', 'comment_fields' );
// save extra fields in database
add_action( 'comment_post', 'save_comment' );

function mytheme_comments_form_defaults($default) {
	$default['comment_notes_after'] = 'You Can Add html code<br/><input type="checkbox" name="is_newsletter" id="is_newsletter" value="1"/>Subcsribe to our custom newsletter.<br/>';
	//unset($default['comment_notes_after']);
	return $default;
}
function comment_fields($fields)
{
	global $current_user;
	if(is_user_logged_in()){
		get_currentuserinfo();
		$phone = get_usermeta($current_user->ID,'business_phone');
		$address = get_usermeta($current_user->ID,'address');
	}
    $fields['url'] = '';
    $fields['location'] = '<p class="comment-form-location">' . '<label for="location">' . __( 'Location' ) . '</label> ' .
      '<input id="location" name="location" type="text" value="' . esc_attr( $address ) . '" size="30" /></p>';

    $fields['phone'] = '<p class="comment-form-phone">' . '<label for="phone">' . __( 'Phone' ) . '</label> ' .
      '<input id="phone" name="phone" type="text" value="' . esc_attr( $phone ) . '" size="20" /></p>';

    $fields = array( $fields['author'], $fields['location'], $fields['email'], $fields['phone'], $fields['url'] );
  return $fields;
}
function save_comment($comment_id)
{
	add_comment_meta( $comment_id, 'location', $_POST['location'], true );
	add_comment_meta( $comment_id, 'phone', $_POST['phone'], true );
	add_comment_meta( $comment_id, 'is_newsletter', $_POST['is_newsletter'], true );
}

?>

Output:

Front End:

Now Show the fields in admin section

<?php
//hook comment listing page
add_action('comment_text', 'show_commeta');
//hook edit comment
add_action( 'add_meta_boxes_comment', 'page_comments_status_meta_box' );
// save comment meta
add_action('edit_comment','save_markdown_after_edit');

if (is_admin()) {
   echo get_comment_text(), '<br/><span style="color:blue;">', get_comment_meta(get_comment_ID(), 'location',1).'</span>';
   }}

function page_comments_status_meta_box($post){

		$location = get_comment_meta($post->comment_ID,"location",true);
		$phone = get_comment_meta($post->comment_ID,"phone",true);
		$is_newsletter = get_comment_meta($post->comment_ID,"is_newsletter",true);

		if($post->user_id && ($location=='' && $phone=='')){
			$location = get_user_meta($post->user_id,"address",true);
			$phone = get_user_meta($post->user_id,"business_phone",true);
		}
?>
	<div class="stuffbox" id="namediv">
		<h3><label for="name">Other Details</label></h3>
			<div class="inside">
				<table class="form-table">
					<tr valign="top">
						<td class="first">Location:</td>
						<td><input type="text" id="location" tabindex="5" value="<?php echo $location; ?>" size="30" name="location"></td>
					</tr>
					<tr valign="top">
						<td class="first">
						Phone:</td>
						<td><input type="text" id="phone" tabindex="2" value="<?php echo $phone; ?>" size="20" name="phone"></td>
					</tr>
					<tr valign="top">
						<td class="first">
						Subscribe To Newsletter:</td>
						<td align="left" style="float:left;"><input type="checkbox" id="is_newsletter" tabindex="2" value="1" name="is_newsletter"<?php if($is_newsletter)echo "checked";?>></td>
					</tr>
				</table>
			<br>
		</div>
	</div>
<?php
}
function save_markdown_after_edit($comment_ID){
    if (isset($_POST['location'])){
        update_comment_meta($comment_ID,'location',$_POST['location']);
    }if (isset($_POST['phone'])){
        update_comment_meta($comment_ID,'phone',$_POST['phone']);
    }
}
?>

Output:

Admin End:

WordPress Create Custom Widget

16th Jun 2011 at 1:30 PM | Posted in Wordpress | Leave a comment

<?php

/**

 * Plugin Name: Connect With Us Widget

 * Description: A widget that serves as an example for developing more advanced widgets.

 * Version: 0.1

 *

 * This program is distributed in the hope that it will be useful,

 * but WITHOUT ANY WARRANTY; without even the implied warranty of

 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

 */

/**

 * Add function to widgets_init that'll load our widget.

 * @since 0.1

 */

add_action( 'widgets_init', 'connect_load_widgets' );

/**

 * Register our widget.

 * 'Example_Widget' is the widget class used below.

 *

 * @since 0.1

 */

function connect_load_widgets() {

	register_widget( 'Connect_Widget' );

}

/**

 * Example Widget class.

 * This class handles everything that needs to be handled with the widget:

 * the settings, form, display, and update.  Nice!

 *

 * @since 0.1

 */

class Connect_Widget extends WP_Widget {

	/**

	 * Widget setup.

	 */

	function Connect_Widget() {

		/* Widget settings. */

		$widget_ops = array( 'classname' => 'connect', 'description' => __('An socal medis widget.', 'connect') );

		/* Widget control settings. */

		$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'connect-widget' );

		/* Create the widget. */

		$this->WP_Widget( 'connect-widget', __('Connect Widget', 'connect'), $widget_ops, $control_ops );

	}

	/**

	 * How to display the widget on the screen.

	 */

	function widget( $args, $instance ) {

		extract( $args );

		global $post;

		$include = $instance['include'];

		$includeArr = array();

		if($include != ''){

			$includeArr = explode(",",$include);

		}

		if(is_page($includeArr)){

		/* Our variables from the widget settings. */

		$title = apply_filters('widget_title', $instance['title'] );

		$name = $instance['name'];

		$description = $instance['description'];

		/* Before widget (defined by themes). */

		echo $before_widget;

		echo '<div class="cntSocial">';

		/* Display the widget title if one was input (before and after defined by themes). */

		if ( $title )

			echo '<h3 class="widget-title">'. $title ."</h3>";

		/* Display name from widget settings if one was input. */

		if ( $description )

			echo $description;

		echo '<br class="clear" /></div>';

		/* After widget (defined by themes). */

		echo $after_widget;

		}

	}

	/**

	 * Update the widget settings.

	 */

	function update( $new_instance, $old_instance ) {

		$instance = $old_instance;

		/* Strip tags for title and name to remove HTML (important for text inputs). */

		$instance['title'] = $new_instance['title'];

		$instance['description'] = $new_instance['description'];

		$instance['include'] = $new_instance['include'];

		return $instance;

	}

	/**

	 * Displays the widget settings controls on the widget panel.

	 * Make use of the get_field_id() and get_field_name() function

	 * when creating your form elements. This handles the confusing stuff.

	 */

	function form( $instance ) {

		/* Set up some default widget settings. */

		$defaults = array( 'title' => __('Connect', 'connect'), 'name' => __('John Doe', 'connect'), 'sex' => 'male', 'show_sex' => true );

		$instance = wp_parse_args( (array) $instance, $defaults ); ?>

		<!-- Widget Title: Text Input -->

		<p>

			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'hybrid'); ?></label>

			<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" class="widefat" />

		</p>

		<!-- Your Name: Text Input -->

		<p>

			<textarea id="<?php echo $this->get_field_id( 'description' ); ?>" name="<?php echo $this->get_field_name( 'description' ); ?>" class="widefat" cols="20" rows="16"><?php echo $instance['description']; ?></textarea>

		</p>

		<p>

			<label for="<?php echo $this->get_field_id( 'include' ); ?>"><?php _e('Include Page Id:', 'hybrid'); ?></label>

			<input id="<?php echo $this->get_field_id( 'include' ); ?>" name="<?php echo $this->get_field_name( 'include' ); ?>" value="<?php echo $instance['include']; ?>" style="width:100%;" class="widefat" />

		</p>

	<?php

	}

}

?>

————————————————————-

Output:


PHP curl. Simple curl script

22nd Mar 2011 at 10:36 AM | Posted in PHP | Leave a comment

Using curl we can get the output content of a given url.

$URL = "http://google.com";
	$curl = curl_init();
	curl_setopt ($curl, CURLOPT_URL, $URL);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$result = curl_exec ($curl);
	curl_close ($curl);
echo $result;

PHP preg_match_all to remove a part of a text.

22nd Mar 2011 at 10:28 AM | Posted in PHP | Leave a comment
<?php
echo $text = "This test [CONFIRMLINK] is working fine [/CONFIRMLINK] for preg_match_all";

preg_match_all('|\[CONFIRMLINK\](.*)\[\/CONFIRMLINK\]|', $text, $text1);

$text1_val = $text1[1][0];
$text = str_replace($text1_val,'',$text);
$text = str_replace("[CONFIRMLINK]",'',$text);
$text = str_replace("[/CONFIRMLINK]",'',$text);

echo "<br/>";
echo $text;
?>

Mysql Trigger Update & Insert

18th Mar 2011 at 11:21 AM | Posted in Uncategorized | Leave a comment

SHOW TRIGGERS;

CREATE TABLE `employees` (  `employeeNumber` int(11) NOT NULL,  `lastName` varchar(50) NOT NULL,  `firstName` varchar(50) NOT NULL,  `extension` varchar(10) NOT NULL,  `email` varchar(100) NOT NULL,  `officeCode` varchar(10) NOT NULL,  `reportsTo` int(11) default NULL,  `jobTitle` varchar(50) NOT NULL,  PRIMARY KEY  (`employeeNumber`))

CREATE TABLE employees_audit ( id int(11) NOT NULL AUTO_INCREMENT, employeeNumber int(11) NOT NULL, lastname varchar(50) NOT NULL,
changedon datetime DEFAULT NULL, action varchar(50) DEFAULT NULL, PRIMARY KEY (id) )
Insert:

DROP TRIGGER before_employee_update;DELIMITER $$CREATE TRIGGER before_employee_update BEFORE UPDATE ON employeesFOR EACH ROW BEGININSERT INTO employees_auditSET action = ‘update’,lastname = OLD.lastname,changedon = NOW(); END$$DELIMITER ;
Update:

DROP TRIGGER before_employee_update;DELIMITER $$CREATE TRIGGER before_employee_update BEFORE UPDATE ON employeesFOR EACH ROW BEGINUPDATE employees_auditSET action = ‘update’,employeeNumber = NEW.employeeNumber,lastname = NEW.lastname,changedon = NOW() WHERE employeeNumber=NEW.employeeNumber; END$$DELIMITER ;

Next Page »

Blog at WordPress.com.
Entries and comments feeds.