Sunday, 14 April 2013

Top 10 things wordpress programmer needs to know

1. How to change server details in wordpress file.

Answer : Go to directory where wordpress installed.
         -> Open file name : wp-config.php
       
 ---------------------------------------------------------------
 To change database name -> 
 define('DB_NAME', 'please-enter-data-base-name-here');
----------------------------------------------------------------
 To change database password -> 
 define('DB_PASSWORD', 'please-enter-data-base-password-here');
----------------------------------------------------------------
 To change database user name-> 
 define('DB_USER', 'please-enter-data-base-user-name-here');
----------------------------------------------------------------
 To change language 
 define('WPLANG', '');
 please prefer this link 
----------------------------------------------------------------

2. How to create custom post type in wordpress codex.

Answer :
Custom post types are new post types you can create. A custom post type can be added to WordPress via the register_post_type() function. This function allows you to define a new post type by its labels, supported features, availability and other specifics.
Note that you must call register_post_type() before the admin_menu and after the after_setup_theme action hooks. A good hook to use is the init hook.

Example1

add_action( 'init', 'create_post_type' );
function create_post_type() {
	register_post_type( 'acme_product',
		array(
			'labels' => array(
				'name' => __( 'Products' ),
				'singular_name' => __( 'Product' )
			),
		'public' => true,
		'has_archive' => true,
		)
	);
}

  

Example2


add_action( 'init', 'create_post_type' );
function create_post_type() {
	register_post_type( 'acme_product',
		array(
			'labels' => array(
				'name' => __( 'Products' ),
				'singular_name' => __( 'Product' )
			),
			'public' => true,
			'has_archive' => true,
			'rewrite' => array('slug' => 'products'),
		)
	);
}
  

Function Reference

Post Typesregister_post_type(),


----------------------------------------------------------------


3. How to create shortcode in wordpress theme file or in plugin.



Answer :  
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
	extract( shortcode_atts( array(
		'foo' => 'something',
		'bar' => 'something else',
	), $atts ) );

	return "foo = {$foo}";
}
add_shortcode( 'bartag', 'bartag_func' );
This creates a "[bartag]" shortcode that supports two attributes: ["foo" and "bar"]. Both attributes are optional and will take on default options [foo="something" bar="something else"] if they are not provided. The shortcode will return as foo = {the value of the foo attribute}
-----------------------------------------------------------------

4. How to create menus by wordpress codex in admin panel.

<?php
/** Step 2 (from text above). */
add_action( 'admin_menu', 'my_plugin_menu' );

/** Step 1. */
function my_plugin_menu() {
	add_options_page( 'My Plugin Options', 'My Plugin', 'manage_options', 'my-unique-identifier', 'my_plugin_options' );
}

/** Step 3. */
function my_plugin_options() {
	if ( !current_user_can( 'manage_options' ) )  {
		wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
	}
	echo '<div class="wrap">';
	echo '<p>Here is where the form would go if I actually had options.</p>';
	echo '</div>';
}
?>

Inserting the Pages

Here is an example of a WordPress plugin that inserts new menus into various places:
<?php
/*
Plugin Name: Menu Test
Plugin URI: http://codex.wordpress.org/Adding_Administration_Menus
Description: Menu Test
Author: Codex authors
Author URI: http://example.com
*/

// Hook for adding admin menus
add_action('admin_menu', 'mt_add_pages');

// action function for above hook
function mt_add_pages() {
    // Add a new submenu under Settings:
    add_options_page(__('Test Settings','menu-test'), __('Test Settings','menu-test'), 'manage_options', 'testsettings', 'mt_settings_page');

    // Add a new submenu under Tools:
    add_management_page( __('Test Tools','menu-test'), __('Test Tools','menu-test'), 'manage_options', 'testtools', 'mt_tools_page');

    // Add a new top-level menu (ill-advised):
    add_menu_page(__('Test Toplevel','menu-test'), __('Test Toplevel','menu-test'), 'manage_options', 'mt-top-level-handle', 'mt_toplevel_page' );

    // Add a submenu to the custom top-level menu:
    add_submenu_page('mt-top-level-handle', __('Test Sublevel','menu-test'), __('Test Sublevel','menu-test'), 'manage_options', 'sub-page', 'mt_sublevel_page');

    // Add a second submenu to the custom top-level menu:
    add_submenu_page('mt-top-level-handle', __('Test Sublevel 2','menu-test'), __('Test Sublevel 2','menu-test'), 'manage_options', 'sub-page2', 'mt_sublevel_page2');
}

// mt_settings_page() displays the page content for the Test settings submenu
function mt_settings_page() {
    echo "<h2>" . __( 'Test Settings', 'menu-test' ) . "</h2>";
}

// mt_tools_page() displays the page content for the Test Tools submenu
function mt_tools_page() {
    echo "<h2>" . __( 'Test Tools', 'menu-test' ) . "</h2>";
}

// mt_toplevel_page() displays the page content for the custom Test Toplevel menu
function mt_toplevel_page() {
    echo "<h2>" . __( 'Test Toplevel', 'menu-test' ) . "</h2>";
}

// mt_sublevel_page() displays the page content for the first submenu
// of the custom Test Toplevel menu
function mt_sublevel_page() {
    echo "<h2>" . __( 'Test Sublevel', 'menu-test' ) . "</h2>";
}

// mt_sublevel_page2() displays the page content for the second submenu
// of the custom Test Toplevel menu
function mt_sublevel_page2() {
    echo "<h2>" . __( 'Test Sublevel2', 'menu-test' ) . "</h2>";
}

?>

Sample Menu Page

Note: See the Settings API for information on creating settings pages.
The example above contains several dummy functions, such as mt_settings_page, as placeholders for actual page content. We need to turn them into real menu pages. So, let's assume that our plugin has an option called mt_favorite_color, and that we want to allow the site owner to type in his/her favorite color via a Settings page. The mt_options_page function will need to put a data entry form on the screen to enable this, and also process the entered data. Here is a function that does this:
// mt_settings_page() displays the page content for the Test settings submenu
function mt_settings_page() {

    //must check that the user has the required capability 
    if (!current_user_can('manage_options'))
    {
      wp_die( __('You do not have sufficient permissions to access this page.') );
    }

    // variables for the field and option names 
    $opt_name = 'mt_favorite_color';
    $hidden_field_name = 'mt_submit_hidden';
    $data_field_name = 'mt_favorite_color';

    // Read in existing option value from database
    $opt_val = get_option( $opt_name );

    // See if the user has posted us some information
    // If they did, this hidden field will be set to 'Y'
    if( isset($_POST[ $hidden_field_name ]) && $_POST[ $hidden_field_name ] == 'Y' ) {
        // Read their posted value
        $opt_val = $_POST[ $data_field_name ];

        // Save the posted value in the database
        update_option( $opt_name, $opt_val );

        // Put an settings updated message on the screen

?>
<div class="updated"><p><strong><?php _e('settings saved.', 'menu-test' ); ?></strong></p></div>
<?php

    }

    // Now display the settings editing screen

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

    // header

    echo "<h2>" . __( 'Menu Test Plugin Settings', 'menu-test' ) . "</h2>";

    // settings form
    
    ?>

<form name="form1" method="post" action="">
<input type="hidden" name="<?php echo $hidden_field_name; ?>" value="Y">

<p><?php _e("Favorite Color:", 'menu-test' ); ?> 
<input type="text" name="<?php echo $data_field_name; ?>" value="<?php echo $opt_val; ?>" size="20">
</p><hr />

<p class="submit">
<input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Save Changes') ?>" />
</p>

</form>
</div>

<?php
 
}
A few notes:
  • The WordPress functions such as add_menu_page and add_submenu_page take a capability which will be used to determine whether the top-level or sub-level menu is displayed.
  • The function which is hooked in to handle the output of the page must check that the user has the required capability as well.
  • The WordPress administration functions take care of validating the user login, so you don't have to worry about it in your function.
  • The function example above has been internationalized -- see the Internationalization section of Writing a Plugin for more information.
  • The function processes any entered data before putting the data entry form on the screen, so that the new values will be shown in the form (rather than the values from the database).
  • You don't have to worry about this working the first time, because the WordPress update_option function will automatically add an option to the database if it doesn't already exist.
  • These admin-menu-adding procedures are parsed every single time you navigate to a page in Admin. So if you are writing a plugin which has no options page, but add one later, you can just add it using the instructions above and re-upload, and tweak until you're happy with it. In other words, menus are not "permanently added" or put into a database upon activating a plugin. They're parsed on the fly, so you can add or subtract menu items at will, re-upload, and the change will be reflected right away.

Page Hook Suffix

Every function that adds a new administration menu (add_menu_page()add_submenu_page() and its specialized versions such as add_options_page()) returns a special value called Page Hook Suffix. It can be used later as a hook to which an action called only on that particular page can be registered.
One such action hook is load-{page_hook}, where {page_hook} is the value returned by one of these add_*_page() functions. This hook is called when the particular page is loaded. In the example below, it is used to display the "Plugin is not configured" notice on all admin pages except for plugin's options page:
<?php
add_action('admin_menu', 'my_plugin_menu');

// Here you can check if plugin is configured (e.g. check if some option is set). If not, add new hook. 
// In this example hook is always added.
add_action( 'admin_notices', 'my_plugin_admin_notices' );

function my_plugin_menu() {
	// Add the new admin menu and page and save the returned hook suffix
	$hook_suffix = add_options_page('My Plugin Options', 'My Plugin', 'manage_options', 'my-unique-identifier', 'my_plugin_options');
	// Use the hook suffix to compose the hook and register an action executed when plugin's options page is loaded
	add_action( 'load-' . $hook_suffix , 'my_load_function' );
}

function my_load_function() {
	// Current admin page is the options page for our plugin, so do not display the notice
	// (remove the action responsible for this)
	remove_action( 'admin_notices', 'my_plugin_admin_notices' );
}

function my_plugin_admin_notices() {
	echo "<div id='notice' class='updated fade'><p>My Plugin is not configured yet. Please do it now.</p></div>\n";
}

function my_plugin_options() {
	if (!current_user_can('manage_options'))  {
		wp_die( __('You do not have sufficient permissions to access this page.') );
	}
	echo '<div class="wrap">';
	echo '<p>Here is where the form would go if I actually had options.</p>';
	echo '</div>';
}
?>

----------------------------------------------

5. How to create menus location in theme function.php.

Answer : <?php wp_nav_menu$args ); ?> 

Usage (Showing Default Values)

<?php

$defaults = array(
	'theme_location'  => '',
	'menu'            => '',
	'container'       => 'div',
	'container_class' => '',
	'container_id'    => '',
	'menu_class'      => 'menu',
	'menu_id'         => '',
	'echo'            => true,
	'fallback_cb'     => 'wp_page_menu',
	'before'          => '',
	'after'           => '',
	'link_before'     => '',
	'link_after'      => '',
	'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
	'depth'           => 0,
	'walker'          => ''
);

wp_nav_menu( $defaults );

?>

Examples


Default example

<div class="access">
  <?php wp_nav_menu(); ?>
</div>

Targeting a specific Menu

<?php wp_nav_menu( array('menu' => 'Project Nav' )); ?>

Used in the Twenty Ten theme

<div id="access" role="navigation">

    <?php /*

    Allow screen readers / text browsers to skip the navigation menu and
    get right to the good stuff. */ ?>

    <div class="skip-link screen-reader-text">
        <a href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentyten' ); ?>">
        <?php _e( 'Skip to content', 'twentyten' ); ?></a>
    </div>

    <?php /*

    Our navigation menu.  If one isn't filled out, wp_nav_menu falls
    back to wp_page_menu.  The menu assigned to the primary position is
    the one used.  If none is assigned, the menu with the lowest ID is
    used. */

    wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?>

</div><!-- #access -->

Removing the Navigation Container

In order to remove navigation container, theme location specified in functions.php and used among arguments in function wp_nav_menu ( eg. 'theme_location' => 'primary-menu' ) must have a menu assigned to it in administration! Otherwise argument 'container' => 'false' is ignored.
<?php
function my_wp_nav_menu_args( $args = '' )
{
	$args['container'] = false;
	return $args;
} // function

add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
?>
OR
<?php wp_nav_menu( array( 'container' => '' ) ); ?>

Removing the ul wrap

This example will remove the ul around the list items.
<?php wp_nav_menu( array( 'items_wrap' => '%3$s' ) ); ?>

Adding a Word at the Beginning of the Menu

This example will allow you to add the word of your choice to the beginning of your menu as a list item. In this example, the word "Menu:" is added at the beginning. You may want to set an id on the list item ("item-id" in this example) so that you can use CSS to style it.
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'items_wrap' => '<ul><li id="item-id">Menu: </li>%3$s</ul>' ) ); ?>
----------------------------------------------------------------

6. what is wp_head and wp_footer. what is the need of both of functions in theme development.  

Answers :
The newer versions of WordPress require this in your theme's footer.php file before the </body> tag:
<?php wp_footer();?>
You should also have this in the <head> section of your theme's header.php file:
<?php wp_head();?>
It's worth checking to make sure they are there, especially if your theme was released prior to the release of WordPress v.2.8. If either or both of them are missing, you may have conflicts with plugins not working properly.

------------------------------------------------------------------------------------------------------------------------------------------------------------

7. How to create meta data and update meta data.

Answers: 

Function Reference

Add/Delete Metadata
Get/Update Metadata

Database Requirements

This function assumes that a dedicated MySQL table exists for the $meta_type you specify. Some desired $meta_types do not come with pre-installed WordPress tables, and so they must be created manually.

Default Meta Tables

Assuming a prefix of wp_, WordPress's included meta tables are:
wp_commentmeta 
Metadata for specific comments.
wp_postmeta 
Metadata for pages, posts, and all other post types.
wp_usermeta 
Metadata for users.

Meta Table Structure

To store data for meta types not included in the above table list, a new table needs to be created. All meta tables require four columns...
meta_id 
BIGINT(20)unsignedauto_incrementnot null, primary key.
object_id 
BIGINT(20)unsignednot null. Replace object with the singular name of the content type being used. For instance, this column might be named post_id or term_id. Although this column is used like a foreign key, it should not be defined as one.
meta_key 
VARCHAR(255)
meta_value 
LONGTEXT
--------------------------------------------------------------------------











8. Some useful wordpress inbuild functions.

Answers: 

  1. REMOVING THE AUTO CAPITALISATION OF ‘WORDPRESS’

    When version  3.0 was released a fairly simple filter appeared called capital_P_dangit. This was committed to the core by Matt Mullenweg for the purposes of brand reinforcement. Suffice to say many in the community weren’t thrilled by this passive-aggressive pedantry for a multitude of very good reasons but that’s another story (you can read all about it in Justin Tadlock’s article on the subject).
    // remove capital_P_dangit
    foreach( array( 'the_content', 'the_title', 'comment_text' ) as $filter )
        remove_filter( $filter, 'capital_P_dangit' );
  2. CHANGE EXCERPT LENGTH

    The default excerpts in WordPress are reasonable but rarely fit with the design you are working to. Alter the number of characters returned in an excerpt with the following snippet.
    function theme_excerpt_length( $length ) {
        return 80; // 80 words long
    }
    add_filter('excerpt_length', 'theme_excerpt_length');
  3. CHANGE THE EXCERPT TRUNCATION TEXT

    You can alter the text that appears at the point of truncation, ie. ‘[...]‘, to anything you want, including a useful link to the post page.
    function theme_excerpt_more( $more ) {
        global $post;
        return '&hellip; <a class="read-more" href="'. get_permalink($post->ID) . '">' . __('Continue reading') . '</a>';
    }
    add_filter('excerpt_more', 'theme_excerpt_more');
  4. ADDING CONTACT METHODS TO THE USER PROFILE

    On every recent project we have had there has been a need for extra user data, such as Twitter username, FaceBook URL and so on. The user profile screen can be edited using a combination of action hooks but WordPress also has a very simple way to add extra contact methods.
    function more_contactmethods( $contactmethods ) {
        $contactmethods['twitter'] = 'Twitter username';
        $contactmethods['facebook'] = 'Facebook URL';
        return $contactmethods;
    }
    add_filter( 'user_contactmethods', 'more_contactmethods' );
  5. REMOVING THE INLINE STYLESHEET FROM GALLERIES

    By default WordPress spits out an inline stylesheet whenever the gallery shortcode is used within a post. The reasoning is that users can control the number of columns each gallery has and the sizes of the images within them as well as a few other options. While it is a noble quest to give users more power over their images it also allows them to screw things up in new and exciting ways when using a custom theme. Adding style tags within the body of an HTML document is also invalid markup.
    Thanks to Safirul Alredha for this code:
    // remove gallery shortcode styling
    add_filter('gallery_style',
        create_function(
            '$css',
            'return preg_replace("#<style type=\'text/css\'>(.*?)</style>#s", "", $css);'
        )
    );
  6. REPLACING THE GALLERY SHORTCODE HANDLER

    While the above snippet does a good enough job in many cases I still find the built in gallery shortcode function to be questionable. For example you can change what HTML tags the gallery outputs with (the default being a semantically poor series of definition lists) but there is no way to set theme defaults without parsing post/page content and adding the attributes to the shortcode programmatically. This is a bad idea for general use themes because it will screw up peoples sites if they switch to another theme in future.
    The shortcode can be rescued however by simply removing it and replacing it with your own callback:
    // replace gallery shortcode
    remove_shortcode('gallery');
    add_shortcode('gallery', 'theme_gallery_shortcode');
    
    function theme_gallery_shortcode( $attr ) {
        global $post, $wp_locale;
        // create your own gallery output...
    }
    You can alternatively use the built in shortcode’s internal filter ‘post_gallery’ to change the output and handling of the standard shortcode attributes.
  7. ADDING CUSTOM POST TYPES TO SEARCH RESULTS

    Hopefully any custom post types that are set as publicly queryable will be included in the search results by default in future releases of WordPress but for now you can use the following code:
    function search_post_types( $query ) {
        if ( $query->is_search )
            $query->set( 'post_type', get_post_types( array( 'publicly_queryable' => 1 ) ) );
        return $query;
    }
    add_filter( 'the_search_query', 'search_post_types' );
  8. ADDING CUSTOM POST TYPES TO THE MAIN RSS FEED

    This can make sense for some sites if you want an amalgamated feed of all your content. We use an array filter in this case to get only those post types that have taxonomies so page-like content is ignored.
    function feed_post_types( $vars ) {
        if ( isset($vars['feed']) && !isset($vars['post_type']) )
            $vars['post_type'] = array_filter( get_post_types( array( 'publicly_queryable' => 1 ) ), 'get_object_taxonomies' );
        return $vars;
    }
    add_filter( 'request', 'feed_post_types' );
  9. ENABLE POST THUMBNAILS

    This is one is pretty straightforward. Make use of WordPress 3.0′s post thumbnail feature in your theme.
    add_theme_support( 'post-thumbnails' );
  10. ENABLE SHORTCODES IN THE TEXT WIDGET

    This little trick makes the text widget into a much more powerful tool. It’s used on this site to add an author list to the widget space in the footer, avoiding the need to code a specific author list widget.
    add_filter( 'widget_text', 'do_shortcode' );
---------------------------------------------------------------

9. How to create template in wordpress theme codex.









Answers :   Theme Stylesheet

In addition to CSS style information for your theme, style.css provides details about the Theme in the form of comments. The stylesheet must provide details about the Theme in the form of comments. No two Themes are allowed to have the same details listed in their comment headers, as this will lead to problems in the Theme selection dialog. If you make your own Theme by copying an existing one, make sure you change this information first.
The following is an example of the first few lines of the stylesheet, called the stylesheet header, for the Theme "Twenty Ten":
/*
Theme Name: Twenty Ten
Theme URI: http://wordpress.org/
Description: The 2010 default theme for WordPress.
Author: wordpressdotorg
Author URI: http://wordpress.org/
Version: 1.0
Tags: black, blue, white, two-columns, fixed-width, custom-header, custom-background, threaded-comments, sticky-post, translation-ready, microformats, rtl-language-support, editor-style, custom-menu (optional)

License:
License URI:

General comments (optional).
*/
NB: The name used for the Author is suggested to be the same as the Theme Author's wordpress.org username, although it can be the author's real name as well. The choice is the Theme Author's.


Thanks 

Saturday, 13 April 2013

Joomla code that you should know.

HOW TO GET LOGIN ID

<?php
$user=& JFactory::getuser();
$id2=$user->get('id');
if($id2>0){

}else{
 $mainframe =& JFactory::getApplication('site');
 $mainframe->redirect($indexpath."/index.php");
}
?>

HOW TO GET USER INFO
function  getUserValue($id,$field){

  $db   =& JFactory::getDBO();
  $query="SELECT $field from #__users Where id=".$id;
  $db->setQuery($query);
  $result=$db->loadObject($field);
  
  return str_replace("<br />","\n",$result->$field);

}/*How to show the function data*/
<?php echo getUserValue($this->user->get('id'),'address');?>"
<?php echo getUserValue($id1,'homepage');?>

how to call the function :-

Joomla is an award-winning content management system (CMS), which enables you to build Web sites and powerful online applications.Best of all, Joomla is an open source solution that is freely available to everyone.


1.  Month ,  Date , Year User define Function.


 Html Code

<tr height="20">
            <td align="right" class="normaltext">&nbsp;</td>
            <td align="right" class="normaltext"><div align="left">Date Of Birth :</div></td>
            <td align="left"><select name="month" id="month"  style="width:80px" class="whiteselectsmall">
                <?php echp "month_opt(get_month($uid))"; ?>
              </select>
              <select name="day" id="day" style="width:40px" class="whiteselectsmall">
                <?= set_day($uid) ?>
              </select>
              <span class="normaltext">
              <select name="year" id="day" style="width:80px" class="whiteselectsmall">
              <?=set_year($uid);?>
              </select>
              </span> </td>
          </tr>



Wednesday, 26 October 2011

Change backgorund colors of template using javascript and php

Different people have different taste of colors therefore it is important that all users can change there template color ,text color , font family etc.

Today we learn how to change different  background colors of different divs in the template using php javascript.


Code explanation :-  i am using jscolor color picker to select color . /

<script type="text/javascript" src="jscolor/jscolor.js"></script>

<input class="color" id="textbox1" name="textbox1"/>

To change the background color of div. div id is important for example :-
<script type="text/javascript" src="jscolor/jscolor.js"></script> 
<form name="form1" id="form1"><div id="div1" style="width:400px; height:50px;"></div>
<input class="color" id="textbox1" name="textbox1" onchange="backColor(this.form1.textbox1.value)"//></form>
<script type="text/javascript">
function backColor(color){
color = '#' + color ;
var myDiv = document.getElementById("div1"); 
myDiv.style.backgroundColor = color;
} 
</script>

To change the color of navbar.

<script type="text/javascript" src="jscolor/jscolor.js"></script>

<script type="text/javascript">
function backColor(color,ids){
color = '#' + color ;
var myDiv = document.getElementById(ids); 
myDiv.style.backgroundColor = color;
//alert(ids);
}</script><html><form name="form" id="form" method="post">Nav  :-<input class="color" id="navbarColor" name="navbarColor"  onchange="backColor(this.form.navbarColor.value ,'navbar')" value="<?php echo $navbarColor;?>"/><br/> 
<div class="navbar" id="navbar"></div>
</html>


In above code input field has id that is navbarColor and have a onchange event function backColor() and has two parameters one get input field value and other contain id div which we want to change color.
In backColor function has two variable name color  and ids .


To change font 

function tfontFamily(font){var myDiv = document.getElementById("bground"); 
myDiv.style.fontFamily = font;
myDiv.style.color = '#fff';

}

How to store data in database filed .

-- Table structure for table `settings`
--

CREATE TABLE IF NOT EXISTS `settings` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `contColor` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `topColor` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `navbarColor` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `mainColor` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `postColor` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `postRightColor` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `postRightAds` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `pageColor` varchar(10) COLLATE latin1_general_ci NOT NULL,
  `footerColor` varchar(10) COLLATE latin1_general_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=4 ;

--

To save all the field data in the mysql database it is important to know insert query.

Please download code files to learn how code work..

Please leave your  valuable comments .
Thank you . 

Saturday, 22 October 2011

signin signup using php mysql javascript

sign-in and sign-up pages are required to develop good iterative dynamic website  that store the information of users. In this post we do sign up sign in profile info access update point on signin and signout.


Website Previews






 Required Languages  :-

PHP MYSQL CSS JAVASCRIPT HTML.

Site directory chart :-

Explanation :- Index.php

Html code : In index.php file we only link the signin page and signup page.
<table width="50%" border="0" align="center" cellpadding="2" cellspacing="10">
  <tr>
    <td colspan="2" align="center" bgcolor="#0000FF"><h2><a href="http://www.eaglexwebs.blogspot.com" style="text-decoration:none;"><span class="style1">eaglexwebs.blogspot.com</span></a></h2></td>
  </tr>
  <tr>
    <td width="46%" align="center"><a href="login.php"><div class="box" onmouseover="this.className='box1'" onmouseout="this.className='box'">Sign In</div></a></td>
    <td width="54%" align="center"><a href="register.php"><div class="box" onmouseover="this.className='box1'" onmouseout="this.className='box'">Sign Up</div></a></td>
  </tr></table> 
Php code : session code (required to change language )
<?php
session_start();ob_start();

if($_SESSION['lang']=='')
{
 $_SESSION['lang'] = "en";
} 
include 'languages/lang.'.$_SESSION['lang'].'.php';

    
 ?>

register.php 

<form action="" id="form1" method="post" name="form1" onsubmit="return validate();">
</form>

onsubmit="return validate(); is user define JavaScript function that validate the field .
Find the validate() function in register.php page . Php code :
<?php session_start();ob_start();

 

 if($_SESSION['lang']=='')
{
 $_SESSION['lang'] = "en";
} 
 include 'languages/lang.'.$_SESSION['lang'].'.php';

   include("include/db.inc.php");
   include("include/bit_functions.inc.php");
   include("include/function.register.php");
   $db1=new db;
   $db1->open(); 
   $headermsg= _CREATE_ACCOUNT_;   
   $str=randamString();

?>
<?   
   if(isset($_POST['submit_reg']))
   { 
echo "submit button is post :"; 
}
?>
 <input name="submit_reg" type="submit" class="inputsubmit" value="<?=_REGS_NOW_?>">
extract($_POST) function is add $ in all the post field.(city , $city )(name , $name ).
     extract($_POST);  
mysql_query("insert into city set stateid='$state',city='$other',status='1'");
  $city=mysql_insert_id();
  }     
    
     $sql="insert INTO user(id,uname,email,password, bday, state, city, time_zone, question, answar, ccode) values('','$name','$email','$pwd','$bday','$state','$city', '$time_zone','$question','$ans','$ccode')";
    $res=mysql_query($sql) or die(mysql_error());
   $i_id=mysql_insert_id();
   $profile_set="insert into profile_setting set uid='$i_id',basic_info='1',contact_info='1',personal='1',
       educational='1',course='1',wall='1',photo='1',friends='1',share='1',
    notes='1',groups='1'";
    mysql_query($profile_set);
Login :-
$query1=mysql_fetch_array(mysql_query("SELECT id FROM user WHERE email='$email' and password='$password'  and confirm='1'  and blocked='1' and deactive='0'"));
  $query2=mysql_fetch_array(mysql_query("SELECT id FROM user WHERE email='$email' and password='$password'   and confirm='1'  and blocked='0' and deactive='1'"));
  $query3=mysql_fetch_array(mysql_query("SELECT id FROM user WHERE email='$email' and password='$password'   and confirm='1'  and blocked='1' and deactive='1'"));
  $query4=mysql_fetch_array(mysql_query("SELECT id FROM user WHERE email='$email' and password='$password'   and confirm='1'  and blocked='0' and deactive='0'"));
  $query5=mysql_fetch_array(mysql_query("SELECT id FROM user WHERE email='$email' and password='$password'   and confirm='0' "));
  if($query1['id'])
  header("location:login.php?msg=blocked");
  if($query2['id'])
  header("location:login.php?msg=deactive&deactivate=1");
  if($query3['id'])
  header("location:login.php?msg=deactiveblock");
  if($query5['id']){
  header("location:login.php?msg=confirm");}
  if($query4['id'])
  {
   $_SESSION[id]=$query4['id'];
    
    $gm=$_SESSION[id];
    list($lastlogin)=mysql_fetch_array(mysql_query("select lastlogin from user where id='$gm'"));
    $qry="update user set second_lastlogin='$lastlogin',lastlogin=now() where id='$gm'";
    $res=mysql_query($qry);
    
    
   if(!empty($_GET['code']))
   {   
   $id=$_SESSION['id']; 
   $q="insert into friends(id,user_id,fr_id,fr_type,status) values('','$id','$i_id',1)";
   mysql_query($q) or die(mysql_error());
   }
   
   //code to insert data in mypoint table or to show Login points
   $mypoint_res=mysql_query("select * from mypoint where uid='$gm'"); 
   $mypoint_row=mysql_fetch_object($mypoint_res);
   $login_cnt=$mypoint_row->loginpoint;
   $cc=mysql_num_rows($mypoint_res);
   if($cc)
    {
       $clv=loginpoint100();
       $lc=$login_cnt+$clv;
       $qry="update mypoint set loginpoint='$lc' where uid='$gm'"; 
    mysql_query($qry);
    
    }
   else
    {
    $lc=loginpoint100();
    mysql_query("insert into mypoint values('','$gm','$lc','','','')");
    }
   //end of code to insert data in mypoint table or to show Login points
   header("location:user_detail.php");
  }
Logout :-
<?
session_start();ob_start();
session_destroy();
header("Location: index.php");
?>
User detail :-
<?php
session_start();ob_start();
    include("include/db.inc.php");
   
 if($_SESSION['lang']=='')
{
 $_SESSION['lang'] = "en";
} 
 include 'languages/lang.'.$_SESSION['lang'].'.php';
  
 include_once("include/bit_functions.inc.php");
    $db1=new db;
    $db1->open();
 checked_login();
 
 
 $uid=$_SESSION[id];  
 
 $query= "select * fROM  user where id = '$uid'";
 $sql=mysql_query($query); 
 $res=mysql_fetch_array($sql);
 $query1= "select * fROM  profile where uid = '$uid'";
 $sql1=mysql_query($query1); 
 $res1=mysql_fetch_array($sql1);
 
 
 
 ?>
<table width="100%" cellpadding="3" cellspacing="3" style="font:Verdana, Arial, Helvetica, sans-serif ; font-size:16px; color:#9900CC; background-color:#99FFFF;">
      <tr>
        <td width="22%">User Name</td>
        <td width="25%"><?php echo $res['uname'];?></td>
        <td width="19%">Email Id</td>
        <td width="34%"><?php echo $res['email'];?></td>
      </tr>
      <tr>
        <td>Gender</td>
        <td><?php if($res1['sex'] == m) { Echo "Male";}?><?php if($res1['sex'] == f) { Echo "Female";}?></td>
        <td>Last LogIn </td>
        <td><?php echo $res['lastlogin'];?></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
    </table> 
db.inc.php
       var $host = 'localhost';
    var $user ='root';
    var $password ="";
    var $database ='eaglex';
    var $persistent = false;
 var $adminid='admin';
 var $adminipwd='admin';
define('_BASEURL_','http://localhost/signup-signin'); //protocol required (http://)
define('_DOMAINURL_','http://localhost/signup-signin');
define('_BASEPATH_','http://localhost/signup-signin'); 

Database :- user
CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uname` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `fname` varchar(40) COLLATE latin1_general_ci NOT NULL,
  `lname` varchar(30) COLLATE latin1_general_ci NOT NULL,
  `email` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `password` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `bday` date NOT NULL,
  `state` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `city` int(11) NOT NULL,
  `college` int(11) NOT NULL,
  `collstatus` int(11) NOT NULL,
  `collyear` int(11) NOT NULL,
  `time_zone` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `question` varchar(100) COLLATE latin1_general_ci NOT NULL,
  `answar` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `blocked` enum('0','1') COLLATE latin1_general_ci NOT NULL,
  `deactive` enum('0','1') COLLATE latin1_general_ci NOT NULL DEFAULT '0',
  `couse` text COLLATE latin1_general_ci NOT NULL,
  `confirm` enum('0','1') COLLATE latin1_general_ci NOT NULL DEFAULT '0',
  `ccode` varchar(100) COLLATE latin1_general_ci NOT NULL,
  `second_lastlogin` datetime NOT NULL,
  `lastlogin` datetime NOT NULL,
  `p_view` int(11) NOT NULL,
  `online` enum('0','1') COLLATE latin1_general_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=134 ;
State :-
CREATE TABLE IF NOT EXISTS `state` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `state` varchar(30) COLLATE latin1_general_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=11 ;
City :-
-- Table structure for table `city`
--

CREATE TABLE IF NOT EXISTS `city` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stateid` int(11) NOT NULL,
  `city` varchar(200) COLLATE latin1_general_ci NOT NULL,
  `status` enum('0','1') COLLATE latin1_general_ci NOT NULL DEFAULT '1',
  UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=33 ;