Pacecode Blog Tips, Scripts and More…

3Dec/110

Simple steps to set Master / Slave replication in MySQL Database

Why i have to do master-slave replication using MySQL?

1. One of the biggest advantages to have master-slave set up in MySQL is to be able to use master for all of the inserts, update and delete queries and slave for select queries. This will most probably speed up your application without having to diving into optimizing all the queries or buying more hardware.

2. Do backups from slave: One of the advantages people overlook is that you can use MySQL slave to do backups from. That way site is not affected at all when doing backups.

Goal: Master DB - Use db only for insert,delete and updated queries
Slave DB - Use db only for select queries

There are several Master-Slave replication available in MySQL. Below is the one of the best Master-Slave replication.

Note:

1. Below configuration is only for a single database replication.
2. Do the step 1 and step 2 in your master server and step 3 and step 4 slave servers.
3. Before doing all steps, you must create database and repective tables in your master and slave server.

Step 1: (Activate binary(bin) log in MySQL)

vi /etc/my.cnf
===============
log-bin = mysql-bin
binlog-do-db = databasename // give your database name
server-id = 1 // unique id depend upon your servers

Step 2: (Creating a new user in Master)

In mysql... login as root user.

30Oct/110

Execute php codes in your WordPress Page without Plug-ins!

Below are the simple steps to create a WordPress Page with capability to execute php code without any wordpress plug-ins!

Step1 :  Goto your theme directory and create a page  template as follows in the screen shot!

Step 2:  Save this file in your current theme directory.

1Sep/110

Cross-domain communications with JSONP using JavaScript and jQuery!

Asynchronous JavaScript and XML (Ajax) is the key technology driving the new generation of Web sites, popularly termed as Web 2.0 sites.Ajax allows for data retrieval in the background without interfering with the display and behavior of the Web application. Data is retrieved using the XMLHttpRequest function, which is an API that lets client-side JavaScript make HTTP connections to remote servers.

This approach, however, does not allow cross-domain communication because of restrictions imposed by the browser. If you try to request data from a different domain, you will get a security error.

The same-origin policy limitations:

The same-origin policy prevents a script loaded from one domain from getting or manipulating properties of a document from another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page.

How to resolve?

Technique 1:

One relatively simple way to overcome this limitation is to have the Web page request data from the Web server it originates from, and to have the Web server behave as a proxy relaying the request to the actual third-party servers. Although widely used, this technique isn’t scalable.

Technique 2:

Another way is to use frame elements to create new areas in the current Web page, and to fetch any third-party content using GET requests. After being fetched, however, the content in the frames would be subject to the same-origin policy limitations.

Technique 3 (Using JSONP):

A more promising way to overcome this limitation is to insert a dynamic script element in the Web page, one whose source is pointing to the service URL in the other domain and gets the data in the script itself. When the script loads, it executes.
It works because the same-origin policy doesn’t prevent dynamic script insertions and treats the scripts as if they were loaded from the domain that provided the Web page. But if this script tries to load a document from yet another domain, it will fail. Fortunately, you can improve this technique by adding JavaScript Object Notation (JSON) to the mix.

JSONP Using Javasript:

Your client-side code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
<title>jsonp</title>
</head>
<body>
<span></span>
<script>
//this function is the callback, it needs to be a global variable
function readResponse(response){
document.getElementsByTagName('SPAN')[0].innerHTML = response.time + ' is from  php file';
console.log(response);
}
(function(){
//note the "readResponse" at the end
var src = 'http://www.your-cross-domain.com/index.php?id=18&callback=readResponse',
script = document.createElement('SCRIPT');
script.src = src;
document.body.appendChild(script);
})();

</script>
</body>
</html>

Your server-side coding:

<?php
$array = array("time"=>time());
if($_GET['callback']){
header('Content-type: application/json');
echo $_GET['callback']."(".json_encode($array).")";
exit();
}
?>

JSONP using jQuery:

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="images">
</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "cat",
tagmode: "any",
format: "json"
}, function (data) {
$.each(data.items, function (i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 3) return false;
});
});
</script>
</body>
</html>

1Aug/100

Need RSS feed parser for a wordpress site?

Importing and displaying external RSS feeds on your site is a great way to share your online activity with your visitors. If you are active on Flickr, Delicious, Twitter, or Tumblr, your visitors will enjoy staying current with your updates. Many social media sites provide exclusive feeds for user-generated content that may be imported and displayed on virtually any web page. In this article, you will learn three ways to import and display feed content on your WordPress-powered website — without installing yet another plugin.

  • Importing and displaying feeds with WordPress & Magpie
  • What is magpie?
    MagpieRSS is an XML-based (expat) RSS parser in PHP. WordPress uses Magpie to parse RSS and Atom feeds and display them on your website. Magpie parses feeds for two different WordPress functions.

    • wp_rss() - fetches and parses feeds for instant
    • fetch_rss() - fetches and parses feeds for advanced

    Ref Site: Readmore

    24Apr/100

    Show Password Text in Password Input Field

    As you know, the user login box of the website contains the following fields username and password. Furthermore, most of them put the “Username” inside user name field and “********” inside password field to save the space within designing.In this post I’ll show you how to show “Password” text in the password field. It doesn’t actually does so but this tips will make it looks like so.

    How it's done

    The type of field cannot be changed with Javascript from type="text" to type="password" so there are actually two fields for the password: a regular password field, and a second plain text field with the default "Password" value.

    When the page is loaded the CSS makes the plain text field hidden. Then the jQuery / js makes the password field hidden and the plain text field visible. It's best to do it this way so if Javascript is not enabled (or there's a Javascript error which causes the rest of the script to stop running) then the user still has a regular password field with obscured text.

    When the user clicks the plain text field, the jQuery / JS code makes the plain text field hidden, the password field visible and puts focus on the password field. On blur, if the password field contains an empty value the plain text field is restored as the visible one to show the default value.

    Demo

    Download (Both jQuery type and js type)

    26Apr/0912

    Ajax PHP Flat Calendar – Customizable PHP based event Calendar

    Are you looking for php based calendar script for your site?

    Here is the download link for this calendar. Hope this will help for you!

    Demo: AJAX PHP FLAT CALENDER


    Features:

    1. Ajax based PHP Calendar - No page reloading and Flat type calendar.
    2. Simple in Coding - Used very basic php and ajax script
    3. Easy to customize for your web based php project.
    4. Completely free to download and free to modify this script.
    5. It works with PHP4 and PHP 5

    Installation:

    1. Extract this folder to your server directory.
    2. Point out the directory(ajaxcalender) in your browser.
    25Dec/083

    Important MySQL Questions and Answers

    How many types of join are supported by mysql? Which are they? Explain:

    ans: there are three types of joins supported in mysql as inner, right and left.
    The inner join displays all the rows from both tables where match is found.
    Left join returns all the rows from first table even if the match is not found in second table.
    While the right join returns all the rows from second table even if match is not found in first table.

    What are the advantages of mysql comparing with oracle?

    MySql has many advantages in comparison to Oracle.

    1 - MySql is Open source, which can be available any time

    2 - MySql has no cost of development purpose.

    3 - MySql has most of features , which oracle provides

    4 - MySql day by day updating with new facilities.

    5 - Good for small application.

    6 - easy to learn and to become master.

    7 - MySql has a good power these days.

    even though MySql having so many advantages, Oracle is best database ever in Software development.

    What are the limitations of mysql in Comparison of Oracle?

    • Mysql supports six different types of tables, four of which do not support transactions (MyISAM, MERGE, ISAM, and HEAP)
    • MySQL only supports one index type
    • Unlike Oracle, MySQL date data types can store invalid dates, do not support time zones, and the precision of time values is limited to one second.

    How many drivers in MYSQL?

    There are eleven drivers in MYSQL .Six of them from MySQL AB and five by MYSQL Communities. They are1.PHP Driver2.ODBC Driver3.JDBC Driver4.ado.net5.mxj6.CAPI1PHP DRIVER2.PERL DRIVER3.PYTHON DRIVER4.RUBY DRIVER5.C++ WRAPPER

    How are triggers created in MySQL?

    CREATE TRIGGER `tgr_name` AFTER UPDATE ON `addresses` FOR EACH ROW begin

    update products set countryName = new.countryName where products.shippingAddressId = old.id;

    end;

    3Dec/081

    Problem with transparent image resizing? – PHP

    You will get black background if you resize a transparent image. To fix it, You need set alpha channel imagecolorallocatealpha to 127. With imagecolorallocatealpha, it will allocate a color for an image.

    Usage:
    int imagecolorallocatealpha ( resource image, int red, int green, int blue, int alpha)

    From PHP manual:
    imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha which may have a value between 0 and 127. 0 indicates completely opaque while 127
    indicates completely transparent. Returns FALSE if the allocation failed.

    Before using it, you must set to false the blending mode for an image and set true the flag to save full alpha channel information.

    Example:

    <?

    $newImg = imagecreatetruecolor($nWidth, $nHeight);

    imagealphablending($newImg, false);

    imagesavealpha($newImg,true);

    $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);

    imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);

    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);

    ?>

    Another way to fix this issue:

    phpThumb() - Resize images on the fly

    Description: phpThumb() uses the GD library  to create thumbnails from images (JPEG, PNG, GIF, BMP, etc) on the fly. The output size is configurable (can be larger or smaller than the source), and the source may be the entire image or only a portion of the original image.

    Download: Download

    Site: phpThumb()

    Demo: Demo

    Installation:

    1. unzip the folder and upload the content into the server
    2. give the correct path of the phpThumb.php and image path as per the following syntax

    Resize Syntax:
    <img src="../phpThumb.php?src=images/watermark.png&bg=FFFFFF&f=png" alt="">
    <img src="../phpThumb.php?src=images/watermark.png&bg=FFFFFF&f=gif" alt="">
    <img src="../phpThumb.php?src=images/watermark.png&bg=FFFFFF&f=jpeg" alt="">

    where the bg=FFFFFF represents the bg color of your transparent image.

    30Oct/080

    Media Box tools package using Mootools JS.

    Media Box tools package using Mootools JS.

    Ref: http://iaian7.com/webcode/Mediabox

    Demo:open Yahoo Movies »

    Download link: MediaBox Download link

    I have created this package file for ready  to access. This package contains following list of files

    • index.php
    • css/mediabox.css
    • js/mediabox.js
    • js/swfobject.js
    • js/mootools.js

    Installation:

    • extract the zip file in to system.
    • upload mediabox folder into your server.
    • access the mediabox  folder from the browser.

    Using the MooTools 1.11 JavaScript library, Media box lets you open flash, video, and html content in a floating “lightbox” style window.

    Mediabox will read Flickr, Google, MetaCafe, MySpace, Revver, YouTube, Veoh, Viddler, and Vimeo links by automatically translating them into embed code and inserting the video into the lightbox style effect.

    Flash animation, flash video, QuickTime, windows media, inline content and external html content is all automatically recognised as well. Every link listed below is shown with the code used to make it.

    19Oct/080

    Playing with author feature in WordPress and author plug-in list

    If you have a wordpress blog with one or more author, then it is most important to list author details in the wordpress post pages. The followings functions will help you list out author details such as

    • the_author
    • the_author_description
    • the_author_login
    • the_author_firstname
    • the_author_lastname
    • the_author_nickname
    • the_author_ID
    • the_author_email
    • the_author_url
    • the_author_link (Version 2.1)
    • the_author_aim
    • the_author_yim
    • the_author_posts
    • the_author_posts_link
    • wp_list_authors

    Okay, will discuss in detail below,

    the_author

    Description: it displays Author's 'Public' Name

    Syntax: <?php the_author(); ?>

    Example: <p> this post was written by <?php the_author(); ?></p>


    the_author_description

    Description: Displays the contents of the about yourself field in an author's profile (Administration > Profile > Your Profile). About yourself is a block of text often used to publicly describe the user and can be quite long. This tag must be used within The Loop.

    Syntax: <?php the_author_description(); ?>

    Example: <p>Cindy biography: <?php the_author_description(); ?></p>


    the_author_login

    Description: This tag displays the login name of the author of a post. The login is also referred to as the Username an author uses to gain access to a WordPress blog. This tag must be used within The Loop

    Note: It's usually not a good idea to provide login information publicly. But it can be used for some other purposes

    Syntax: <?php the_author_login(); ?>

    Example: <p>Author username: <?php the_author_login(); ?></p>


    The_author_firstname, the_author_ lastname, the_author_ nickname

    Description: The following tags display the name for the author of a post. The First Name field is set in the user's profile (Administration > Profile > Your Profile). This tag must be used within The Loop.

    Syntax: <?php the_author_firstname(); ?>, <?php the_author_nickname(); ?>, <?php the_author_lastname(); ?>

    Example: <p>This post was written by <?php the_author_firstname(); ?></p>


    the_author_ID

    Description: Displays the unique numeric user ID for the author of a post; the ID is assigned by WordPress when a user account is created. This tag must be used within The Loop.

    Syntax: <?php the_author_ID(); ?>

    Example: <a href="/blog/index.php?author=<?php the_author_ID(); ?>">View all
    posts by <?php the_author_nickname(); ?></a>


    the_author_email

    Description: This tag displays the email address for the author of a post. The E-mail field is set in the user's profile (Administration > Profile > Your Profile). This function must be used within The Loop.

    Note that the address is not encoded or protected in any way from harvesting by spambots

    Syntax: <?php the_author_email(); ?>

    Example: <a href="mailto:<?php the_author_email(); ?>">Contact the author</a>
    Secure your author’s email:
    This example partially 'obfuscates' address by using the internal function antispambot()
    to encode portions in HTML character entities (these are read correctly by your browser).
    Note the example uses get_the_author_email() function, because the_author_email()
    echoes the address before antispambot() can act upon it.
    Eg: <a href="mailto:<?php echo antispambot(get_the_author_email()); ?>">email
     author</a>


    the_author_url

    Description: This tag displays the URL to the Website for the author of a post. The Website field is set in the user's profile (Administration > Profile > Your Profile). This tag must be used within The Loop.

    Syntax: <?php the_author_url(); ?>

    Example: <p>Author's web site:
    <a href="<?php the_author_url(); ?>"><?php the_author_url(); ?></a></p>
     


    the_author_aim

    Description: This tag displays the AOL Instant Messenger screenname for the author of a post. The AIM field is set in the user's profile (Administration > Profile > Your Profile). This tag must be used within The Loop.

    Syntax: <?php the_author_aim(); ?>

    Example: <p>Contact me on AOL Instant Messenger: <?php the_author_aim(); ?></p>


    the_author_yim

    Description: This tag displays the Yahoo IM ID for the author of a post. The Yahoo IM field is set in the user's profile (Administration > Profile > Your Profile). This tag must be used within The Loop.

    Syntax: <?php the_author_yim(); ?>

    Example: <p>Contact me on Yahoo Messenger: <?php the_author_yim(); ?></p>


    the_author_posts

    Description: Displays the total number of posts an author has published. Drafts and private posts aren't counted. This tag must be used within The Loop.

    Syntax: <?php the_author_posts(); ?>

    Example: <p><?php the_author(); ?> has blogged <?php the_author_posts(); ?>
    posts</p>


    the_author_posts_link

    Description: Displays a link to all posts by an author. The link text is the user's Display name publicly as field. The results of clicking on the presented link will be controlled by the Template Hierarchy of Author Templates. This tag must be used within The Loop.

    Syntax: <?php the_author_posts_link(); ?>

    Example: <p>Other posts by <?php the_author_posts_link(); ?></p>


    wp_list_authors

    Description: Displays a list of the blog's authors (users), and if the user has authored any posts, the author name is displayed as a link to their posts. Optionally this tag displays each author's post count and RSS feed link.

    Syntax: <?php wp_list_authors('arguments'); ?>

    Example: <?php $defaults = array(
              'optioncount' => false,
              'exclude_admin' => true,
              'show_fullname' => false,
              'hide_empty' => true,
              'feed' => ,
              'feed_image' =>  ); ?>
    By default, the usage shows:
        * Does not display the count of the number of posts
        * Excludes the 'admin' author from the list
        * Does not display the full name (first and last) but displays the author nickname
        * Excludes users with no posts
        * No author feed text is displayed
        * No author feed image is displayed
    <?php  wp_list_authors('show_fullname=1&optioncount=1'); ?>
    


    Author image in every post - Plug in:

    Description:

    Display image (if present) and/or name for the author of a post, or for all authors on the blog.

    for more info and downloads:http://coffee2code.com/wp-plugins/author-images/