PathFinder's Weblog

Thumbnail Grabbing from Youtube Video

Posted by: kazi abdullah al Mamun (sumon) on: November 17, 2009

You Tube provides two types (small/large) of thumbnails for each video. It quite simple task to grab thumbnail from YouTube video. I created this function for grabbing thumbnails form YouTube videos. Its able to grab from both URL and Embedded code and also small and large size.

Function Body:

/**
* Function: youtube thumb grabber
*
* @description :
* @param  $ : video code, url type (embed/url),size (small/Large),thumb link
* @return : thumb path
* @author : Mamun.
* @last -modified-by: Mamun.
*/
if (! function_exists('youtube_thumb_grabber' ))
{

     function youtube_thumb_grabber($video_code, $link_type = "embed", $size = "small", $thumb_link = "")
    {
            if ($video_code != '')
            {
                   if ($link_type == "embed")
                   {

                                  $splited_data = explode("=",$video_code);

                                  $video_unique_code = substr(strrchr($splited_data[4],"/"),1,-strlen(strrchr($splited_data[4],"&")));

                  }
                  else if ($link_type == "url")
                  {
                                  $splited_data = explode("=",$video_code);
                                  $video_unique_code = substr($splited_data[1],0,-strlen(strrchr($splited_data[1],"&")));
                  }
                  else
                  {
                                  return;
                  }

                  if($size == "small")
                  {
                            return "<a href=\"$thumb_link\"><img src=\"http://img.youtube.com/vi/$video_unique_code/2.jpg\" alt=\"No image\" /></a>";
                  }
                  else if ($size == "large")
                  {
                            return "<a href=\"$thumb_link\"><img src=\"http://img.youtube.com/vi/$video_unique_code/0.jpg\" alt=\"No image\" /></a>";
                  }
                  else
                  {
                            return "<a href=\"$thumb_link\"><img src=\"http://img.youtube.com/vi/$video_unique_code/2.jpg\" alt=\"No image\" /></a>";

                   }

             }

      }
}

Calling Function:

<?php 

echo youtube_thumb_grabber($video["video_code"],"embed","small","resources/videos/view/".$video["video_title_url"]);

?>

Its Cool. :D

Star Rating using Jquery and CodeIgniter

Posted by: kazi abdullah al Mamun (sumon) on: October 23, 2009

In all Entertainment sites, Star rating is a common phenomena. We need to use star rating for rating different resources like videos, articles, thesis, posts even sometimes persons. JQuery has an excellent Star Rating plugin, which I recently use with PHP CodeIgniter. This is very simple to integrate with controller and show high quality rating options.

Jquery Call:


$(function() {
       $('.auto-submit-star').rating({
            required: true,
            callback: function(value, link) {

            $.ajax({
                     type: "post",
                     url: site_url + "user/view/star",
                     dataType: "json",
                     data: "&video=" + $('#video_url').val() + "&rate_val=" + value,

              success: function(e) {
                   $.jGrowl(e.code + "<br>" + e.msg);
               }
         });
     }
});

Controller Method:

public function star()
    {
        $rate = $this->input->post("rate_val", true);
        $video_url = $this->input->post("video", true);
        $this->load->model("Model Name");
        $video_id = $this->model_name->get_video_id($video_url);
        unset($this->layout); //Block template Layout
        if (get_user_id())   //get_user_id() return login user id
        {
            if (!$this->model_name->is_video_rated(get_user_id(), $video_id))
            {
                $data = array("video_id" => $video_id,
                    "user_id" => get_user_id(),
                    "videos_rating_value" => $rate,
                    "videos_rating_date" => "" . date("Y-m-d H:i:s") . ""
                    );
                if ($this->model_name->insert_rating($data, $video_id, $rate))
                {
                    echo json_encode(array("code" => "Success", "msg" => "Your Video Rating has been posted"));
                }
                else
                {
                    echo json_encode(array("code" => "Error", "msg" => "There was a problem rating your video"));
                }
            }
            else
            {
                echo json_encode(array("code" => "Error", "msg" => "You have already rated this video"));
            }
        }
        else
        {
            echo json_encode(array("code" => "Error", "msg" => "You have to login to rate the video"));
        }
        exit(0);
    }

Presentation View:

    if (!get_user_id()) //Check if user logged in
    {
        $radio_level = "disabled";
    }
    else
    {
        $radio_level = " ";
    }

    for($i = 1;$i <= 5;$i++)
    {
        if ($i == round($row["total_rate"]))
        {
       ?>
       <input class="auto-submit-star" type="radio" name="rating" <?php echo "$radio_level";

            ?> value="<?php echo $i;

            ?>" checked="checked"/>
	<?php
        }
        else
        {
         ?>
	<input class="auto-submit-star" type="radio" name="rating" <?php echo "$radio_level";

            ?> value="<?php echo $i;

            ?>"/>
   <?php
        }
    } //end of for
?>
    

Its a very cool :) rating JQuery plugins.
For demo click

Import CSV to MySQL

Posted by: kazi abdullah al Mamun (sumon) on: October 22, 2009

Import from CSV to MySQL is pretty simple and just a matter of single line command. This post might be helpful for those are newbie in PHP/MySQL.

The command:


LOAD DATA LOCAL INFILE 'Drive Letter:\\\file_name.csv'
into TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1,field2,field3)

Be careful about the “\\\” after drive letter and the data type for MySQL table fields. data type should be set according
to CSV data format.

Argentina Survives !!!!

Posted by: kazi abdullah al Mamun (sumon) on: October 15, 2009

Diego-Maradona

Millions of Argentine’s fans were got releave when Argentina got a surprising victory against Uruguay. Being an Argentine fan, I’m also excited that I can see the exciting classical performance of Argentina in 2010 FIFA World Cup.

It was really a tough time for Diego Maradona and he is nearly going to prove, a great player never always be a great Coach but Maradona can let out a massive sigh of relief after  1-0 win against Uruguay in Montevideo, Uruguay. Argentina would have missed its first World Cup since 1970 if it had lost.

Cheers for Argentina

Congratulations Shakib !!!!

Posted by: kazi abdullah al Mamun (sumon) on: October 10, 2009

Shakib al hasan

Shakib al hasan

Shakib Al Hasan adjudged

Wisden Test Player of the Year.

Bangladesh all rounder Shakib Al Hasan has been voted The Wisden Cricketer magazine’s 2009 world test player of the year.

Shakib, who led Bangladesh to their first overseas test series victory against West Indies in July, 2009 is the first Bangladesh player to win the award.

Congratulations Shakib. We, the  whole nation are proud of you.


Social Bookmarking widget using PHP

Posted by: kazi abdullah al Mamun (sumon) on: October 7, 2009

Add This feature helps website publishers and bloggers spread their content across the web by making it easy for visitors to bookmark and share content to their favorite social destinations. Here I share my recently developed widget for Add This Service which can be easily integrate with PHP application.


/**
 * Function: share_addthis
 *
 * @description : share with Add This bookmarking service
 * @param  $ : $val
 * @return : String
 * @author : Mamun
 */
 function share_addthis($brand = "", $link_title = "Share" , $opt_array = "")
 {

 if(!empty($opt_array))
 {
 $opt = $opt_array;
 }
 else
 {
 $opt = array("digg", "facebook", "favorites", "furl", "google","linkedin", "live","multiply", "myspace",  "reddit", "segnalo", "haredstuff",  "stumbleupon", "technorati", "twitter");
 }

 $share_options = "";

 foreach ($opt as $option)
 {
 $share_options .= $option.", ";
 }

 $share_options = $share_options." more";

 $share_element= '<script type="text/javascript">
 var addthis_pub="'.$brand.'";
 var addthis_brand = "'.$brand.'";
 var addthis_header_color = "#ffffff";
 var addthis_header_background = "#1783C6";
 var addthis_options = "'.$share_options.'";
 </script>';

 $share_element.= '<script type="text/javascript" src="http://s7.addthis.com/js/200/addthis_widget.js"></script>';

 $share_element .= "<a href=\"http://www.addthis.com/bookmark.php?v=20\" target=\"_blank\" onmouseover=\"return addthis_open(this, '', '[URL]', '[TITLE]')\" onmouseout=\"addthis_close()\" onclick=\"return addthis_sendto()\">$link_title</a>";

 return $share_element;

 } // End Function share_addthis()

Call this widget with your project name, share Label and share options and it will automatically display the Add this icons.


share_addthis($brand = "Your Project Name", $link_title = "Share" , $opt_array = "")

JQ Grid with Codeigniter

Posted by: kazi abdullah al Mamun (sumon) on: October 4, 2009

jQGrid is a free jQuery grid and table plugin. I had awesome working experience on JQGrid. Its is very simple and easy to integrate with the main library. last couple of days, I received some requests on how to integrate JQGrid with Codeigniter.

Follow the steps to integrate JQGrid with CI:

Controller:

public function browse ()
	{
		$req_param = array (

				"sort_by" => $this->input->post( "sidx", TRUE ),
				"sort_direction" => $this->input->post( "sord", TRUE ),
				"page" => $this->input->post( "page", TRUE ),
				"num_rows" => $this->input->post( "rows", TRUE ),
				"search" => $this->input->post( "_search", TRUE ),
				"search_field" => $this->input->post( "searchField", TRUE ),
				"search_operator" => $this->input->post( "searchOper", TRUE ),
				"search_str" => $this->input->post( "searchString", TRUE ),
				"search_field_1" => "msg_to",
				"search_field_2" => "msg_in_inbox",
				"user_id" => get_user_id()
		);

		$data->page = $this->input->post( "page", TRUE );
		$data->records = count ($this->model_name->get_data ($req_param,"all")->result_array());
		$data->total = ceil ($data->records /10 );
		$records = $this-> model_name-> get_data ($req_param)->result_array();
		$data->rows = $records;

		echo json_encode ($data );
		exit( 0 );
	}

Models:

public function get_data($params = "" , $page = "all")
	{

		$this->db->select("data")->from( "table_name");

		if (!empty($params))
		{
			if ( (($params ["num_rows"] * $params ["page"]) >= 0 && $params ["num_rows"] > 0))
			{
				if  ($params ["search"] === TRUE)
				{
					$ops = array (

							"eq" => "=",
							"ne" => "<>",
							"lt" => "<",
							"le" => "<=",
							"gt" => ">",
							"ge" => ">="
					);

				}

				if ( !empty ($params['search_field_1']))
				{
					$this->db->where ($params['search_field_1'], $params['user_id']);
				}

				if ( !empty ($params['search_field_2']))
				{
					$this->db->where ($params['search_field_2'], "1");
				}

				$this->db->order_by( "{$params['sort_by']}", $params ["sort_direction"] );

				if ($page != "all")
				{
					$this->db->limit ($params ["num_rows"], $params ["num_rows"] *  ($params ["page"] - 1) );
				}

				$query = $this->db->get();

			}
		}
		else
		{
				$this->db->limit (5);
				$query = $this->db->get ($this->_table );

		}
		return $query;
	}

Views:

<script type="text/javascript">
$(document).ready(function(){
	jQuery("#grid_name").jqGrid({
	   	url:'<?php
		      echo site_url( "message/inbox/browse" );
		      ?>',
		datatype: "json",
		mtype : "post",
		colNames:['col 1','col 2','col 3','col 4'],
	   	colModel:[
			{name:'msg_id',index:'msg_id', width:70, align:"center",hidden:true},
	   		{name:'sender',index:'sender', width:180},
	   		{name:'msg_subject',index:'msg_subject', width:180,align:"left"},
	   		{name:'msg_timestamp', index:'msg_timestamp', width:150},
	   		{name:'act',index:'act', width:90, align:"center", sortable:false}
	   	],
	   	rownumbers: true,
	   	rowNum:10,
	   	rowList:[10,20,30],
	   	pager: jQuery('#pager2'),
	   	sortname: 'msg_timestamp',
	   	autowidth: true,
	   	height: "100%",
	    viewrecords: true,
	    loadComplete: function(){
						$("#grid_name").setLabel("id","",{'text-align':'center'});
						$("#grid_name").setLabel('role_name',"",{'text-align':'center'});
						var ids = jQuery("#grid_name").getDataIDs();
							for(var i=0;i<ids.length;i++){

								var cl = ids[i];

								be = '<span class="one_line">'
								+'<a href="javascript:;" onclick="del_message(\''+ids[i]+'\');"><span class="ui-icon ui-icon-closethick"></span></a>'
								+'</span>';
								jQuery("#grid_name").setRowData(ids[i],{act:be});
							}
					    },

	    sortorder: "desc",

	    jsonReader: { repeatitems : false, id: "0" },
	    caption:"Caption Text");?>"
	}).navGrid('#pager2',{edit:false,add:false,del:false});
});

function del_message(message_id)
{
	if(confirm("Confirm Message")){

		$.ajax({
			url : site_url+"/message/inbox/del_message",
			type : "post",
			dataType : "json",
			data : "message_id="+message_id+"",
			success : function(e){
				$("#msg").html(e.msg)
				alert($("#msg").html());
				//$.jGrowl(e.code+"<br>"+e.message);
				jQuery("#grid_name").trigger("reloadGrid");
			}
		});
	}
}

</script>

HTML BODY:

<table id="grid_name" cellpadding="0" cellspacing="0"></table>
<div id="pager2" class="scroll" style="text-align: center;"></div>

Hope this looks very easy to integrate with CI. Enjoy :)

Now I’m MBA :)

Posted by: kazi abdullah al Mamun (sumon) on: September 29, 2009

Finally, My Internship Thesis paper has been accepted :) which at last bring me at the end of almost three years long Journey. When I joined to DU Business school in marketing department,  I didn’t have clear idea about why I’m here. Even I was confused that which one I will choose as my major concentration.  I was inspired by some of my friends those were admitted to MBA program in different business schools. But when the time progressed, I had the idea why I’m here.

The time I passed here that really exciting. I find lots of good friends and well wishers from different professional backgrounds some of them with very high profiles. In their close touch, I came to learn many things and ideas that I couldn’t even think of before.

I have many mixed unforgettable memories at this DU campus. I will definitely miss that campus. I can never forget those exciting moments that I spent here with my friends. I can’t forget that Addabazi, Random roaming through the campus.

The following things that I will definitely miss:

  • Addabazi in TSC (one of my favorite place in DU)
  • Egg mam lets and Sweets from Madhu da’s  Canteen.
  • Delicious Food of Nirob (Vorta vagi and brain fry)
  • Biriyani from Haji Nanna (This is the best biriyani in Dhaka in my choice)
  • Roaming with Rickshaw in Fuller Road. (nice place for roaming in evening time)
  • Top roof of fine arts Buildings.
  • Bot Tola in front of Arts buildings.
  • Some of our funny and interesting professors.
  • Cha mama der lal cha r Ice cream mamar Ice cream.

Things that need to forget:

  • Lift of business faculty (You never know whether you can reach the destination)
  • Canteen of Business faculty (You will feel more panic and pain rather than taste)
  • Computers in Lab/class room (Anti-virus vendors can easily update their database from here, all categories are available here)
  • Our Study room (Magnitude 5 earthquake is enough to destroy this)
  • Of course some irritating professors of Marketing Department (Name can’t be mention)

In this long journey, I have lots of memories and experiences that really never be old. Its helps me to think in a new way. But the reality is, all things must have an ending. that is the ending. I had some bad memories also but I don’t want to  share those in this happy moment.

I’m really thankful to all my friends and faculty members for their co-operation. Without their co-operation I couldn’t achieve this goal.

Good bye DU Campus but I will miss you always.

Eid-ul-Fitr in Dhaka

Posted by: kazi abdullah al Mamun (sumon) on: September 20, 2009

May the Eid bring you every joy and may the coming days be filled with lasting Happiness.

Eid Mubarak

I’m celebrating EID-UL-FITR as usual in Dhaka with my friends and family. The scenarios of Dhaka has been changed suddenly. No Traffic Jam, NO hassles. Its become a quiet City. I wish if it will remain same always.  Every year I enjoyed to roam in the Dhaka city by Rickshow, hope this year there will not be any alternative.

MyISAM vs InnoDB in MySQL

Posted by: kazi abdullah al Mamun (sumon) on: September 20, 2009

MySQL has 10 Storage Engines. The storage-engine is what will store, handle, and retrieve information for a particular table. Most of us don’t bother about the Database Engine when creating the database. In Most cases, We use default storage Engine which is MyISAM.

Among the all Storage Engines MyISAM and InnoDb are the most popular storage Engines. These two storage engines perform in different ways in creating and  managing databases.

It will be better to identify which will best suited in which situation. Lets starts the discussion on this two:

MyISAM: MyISAM is the default storage engine. It is based on the older ISAM code but has many useful extensions. Data in MyISAM tables is split between three different files on the disk. One for the table format, another for the data, and lastly a third for the indexes.

  • Large files (up to 63-bit file length) are supported on file systems and operating systems that support large files.
  • There is a limit of 232 (~4.295E+09) rows in a MyISAM table.
  • The maximum number of indexes per MyISAM table is 64.
  • BLOB and TEXT columns can be indexed.

InnoDB: InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data. InnoDB row-level locking and Oracle-style consistent nonlocking reads increase multi-user concurrency and performance.

The Comparison:

  1. InnoDB is more strict in data integrity while MyISAM is not.
  2. InnoDB implements row-level lock for inserting and updating while MyISAM implements table-level lock.
  3. InnoDB has transactions while MyISAM does not.
  4. InnoDB has foreign keys and relationship contraints while MyISAM does not.
  5. InnoDB has better crash recovery while MyISAM is poor at recovering data integrity at system crashes.
  6. MyISAM has full-text search index while InnoDB has not.

Decision Matrix

Is your table is going to be inserted, deleted, and updated much much more than it is going to be selected? InnoDB
If you need full-text search MyISAM
If you prefer/require relational database design InnoDB
Is disk-space or ram an issue? MyISAM
Not Sure? MyISAM

Advantages of InnoDB

  1. InnoDB should be consider first where data integrity comes as first priority because it supports relationship constraints and transactions.
  2. Faster in write-intensive (inserts, updates) tables because it utilizes row-level locking and only hold up changes to the same row that’s being inserted or updated.

Disadvantages of InnoDB

  1. More complex process for designing DB.
  2. Consumes more more memory space to perform tasks.
  3. Doesn’t support full-text indexing.

Advantages of MyISAM

  1. Easy to design and create.
  2. Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources.
  3. Supports Full-text indexing.
  4. Performs better in READ (SELECT) operations.

Disadvantages of MyISAM

  1. No data integrity (e.g. relationship constraints) check, which then comes a responsibility and overhead of the database administrators and application developers.
  2. Doesn’t support (ACID properties) transactions management which is important for secure data management.
  3. Slower than InnoDB for tables in the Write (INSERT, UPDATE ) operations.