How to auto resize Textarea based on the input

My previous article was about “MongoDB and PHP tutorial for beginners”. Recently I came across a task to auto resize textarea based on the input. You may know textarea element doesn’t resize automatically as like other html elements, so I need to write a script to update the textarea height based on the content. I have done this using simple script which I would like to share with you.

Source Code:

Step 1:

Download jquery library or Google CDN library link. Include it into your web page.

Step 2:

I have fixed the minimum height to 50px. Paste below code into your html page.

<textarea id=”txtarea” class=”comment”></textarea>
<div id=”hidden-textarea-content” class=”comment hidden”></div>

<style type=”text/css”>
.comment {
    overflow: hidden;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word; 
.hidden {

Step 3:

Now paste below code to make our auto resizing to work.

<script type=”text/javascript”>

     var textarea = $(“#txtarea”), 
         clonedTextarea = $(“#hidden-textarea-content”), 
         content = null;

             textarea.on(“keyup focus keypress cut paste change keydown”, function() {
                  content = textarea.val();

                  clonedTextarea.css(“width”, textarea.width());
                  textarea.css(‘height’, clonedTextarea.height() + “px”);           



Step 4:

Finally run the page and you can see when you type content into textarea it's height will automatically change.

View Demo:

For a demo, you may have a look at my jsfiddle. Make sure before hit run before you test.


You can see this simple script will auto resize your textarea. You can still improve the script and also can make script into plugin. Hope this helps, if so please don’t forget to leave your comments, share and give a small like.
Keep visiting.

MongoDB PHP Tutorial for Beginners

My previous article was about “Dependency Injection in PHP”. Today I would like to write about using MongoDB with PHP. This simple tutorial will help you how to start with popular NoSql database MongoDB and php. MongoDB it stores data as structured json format, which improves application performance and allowing you to write scalable application.

MongoDB and PHP tutorial

Installing MongoDB

Before diving into creating application using PHP and MongoDB let us see install MongoDb in your system. MongoDB runs on most of the platforms. I have provided few step below “how to install MongoDB in Ubuntu (Linux) system”.

Open your terminal and execute below command-

sudo apt-key adv --keyserver hkp:// --recv 7F0CEB10

echo 'deb dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

Now update your local package database by executing below command and install latest stable version of MongoDB.

sudo apt-get update
sudo apt-get install mongodb-org

Here are few useful url for MongoDB installation. For more detail info of linux Installation

Windows Installation

You can download mongo driver from below link

Unzip the archive and put php_mongo.dll inside your php extension directory and add below line to your php.ini file.


Restart your apache server. That’s it! So we are done with the installation of MongoDB. Let us follow following steps to connect with mongo and do simple crud operations.

Connecting MongoDB with PHP

Connecting MongoDb is very easy and very similar with any other database abstraction class (PDO, Mysqli). By default MongoDb connect with the port 28017. You may access server info by simply entering.


Without login credentials.

$mongo = new MongoClient(); or 
$mongo = new Mongo();

With Credentials.

$host = ‘localhost’;
$port = ‘28017’;
$database = ‘test’;
$connecting =  sprintf('mongodb://%s:%d/%s', $host, $port, $database);
$mongo = new Mongo($connecting, array('username'=> $username, 'password'=> $password));

MongoDB default database is “test”. You can create your own database as below.

Selecting Database

$db = $mongo->your_database_name;

Creating Collections or Creating table

$collection = $db->products;

   $document = array( 
      "name" => "", 
      "description" => "The Technical Blog", 
      "url" => "",
      "by", "Sanjoy Dey"


Finding document

Find all document from your collections and iterate data to display title.

$collection = $db->products;
$data = $collection->find();

   foreach ($data as $document) {
      echo $document["name"] . "
"; }

Updating Document

Update document with simple update or save method.

$productArray =  array("name"=> "MongoDB");
$product = $collection->findOne($productArray);
$product [‘name’] = ‘MongoDB and PHP Tutorial’;
$product[‘by’] = ‘Sanjoy’;
$product[‘description’] = “Awesome! simple and best tutorial”;
try  {
} catch (MongoException $e) {
     echo $e->getMessage();

Deleting Document from Collection

Deleting document is as simple as other methods explained above. You can simple delete record from collections with remove method using the key.

$productArray = array( 'name' => 'MongoDB'); // or you can delete by id
 $collection->remove( $productArray, array( 'safe' => true ) );


So finally in this short article we have covered basic CRUD operation using PHP and MongoDB. You can explore much more to build large application. Hope this article helpful to you, if so please don’t forget to leave your comments, share and give a small like.

Keep visiting for latest post.

Diving into the power of Dependency Injection Pattern in PHP

Dependency Injection in PHP


In my previous article I shown you "How to build a simple form using Cygnite PHP Framework with Mysql and Angular Js". Today I have an Interesting topic.

Dependency Injection? Sounds Interesting. Yes! Currently it is one of the raising discussion topics among many PHP developers and communities. It is not a new pattern however commonly used in language like java etc. These concepts are mostly used in MVC (Symfony2, Cygnite Framework, Zend2, Laravel etc.) architecture to decouple code. It is because PHP has been adapted to enterprise level and that is why increasing the demand of quality programming with some patterns. If you already know concept of Dependency Injection then you may simply skip the article and visit us back for other latest posts.

Well! What is Dependency Injection?

It is a simple design pattern to create most decoupled software. It makes your code testable, modular and maintainable.

Advantages of Dependency Injection

• Makes your code Testable, maintainable and modular.
• Gives you to flexibility to change dependencies at runtime.
• Allows you building large and scalable projects.

You might have used this pattern unknowingly. So let us see some example how dependency injection are best practice.

class DataGrid
    public function render($data)

class Application 
    private $connection;

    private $session;
    public function __construct($session, $host, $username, $password)
          $this->db = new MySqlDatabase($host, $username, $password);
          $this->session = $session; 

   public function renderGrid()
          $grid = new DataGrid;
          return $grid->render($this->db->fetchAll());

So in the above example we can see Foo class is dependent on MysqlDatabase class which is hard coded and tightly coupled with each other. Many people says above code is good but if you closely have a look above code has many problem. It uses S.O.L.I.D principle.

What If you want to use some other database class, may be Oracle or any other in future?

What if you want to access extra parameter inside your MysqlDatabase class?

Why to avoid above code?

• Let’s image if we have added extra parameter to MysqlDatabase class, then we need to modify each and every class where MysqlDatabase object created.
• Doing unit testing is hard because all classes are tightly coupled.

How to solve this issue?

Dependency Injection is the solution. There are different types of Injection you can take the advantage of.

• Constructor Injection.
• Setter or Property Injection.
• Interface Injection etc.

Let us rewrite the above code with DI pattern

class Application 
    private $connection;
    private $grid;

    private $session;
    public function __construct($session, MySqlDatabase $database, DataGrid $grid)
          $this->db =  $database;
          $this->session = $session;
          $this->grid = $grid;  

   public function renderGrid()
          return $this->grid->render($this->db->fetchAll());

$app = new Application($sessionName, new MysqlDatabase(), new DataGrid());

You can see in the above example we have reduced the complexity and improved it by decoupling it. We have done constructor injection with Type Hinting. It is easy to do unit test now for each class.

You also inject dependencie using property injection or Interface injection. You may have a look at Cygnite Framework DI container, it resolves controller dependencies without any configuration.

Over using DI pattern into your code may lead you to messy code.

When to use Dependency Injection?

Actually it is not when to use Dependency Injection, you can use it for writing more clean code. However Dependency Injection is most preferable in long term projects. It attracts the best developers to follow your code.

Open Source Dependency Injection Frameworks

These days DI became very popular to PHP developers and many framework uses DI container to resolve Dependencies of your Controller class. Some of them are listed below-

Symfony2 Container based on Java Spring.
Cygnite Framework DI Container.
Zend2 DI.
Laravel IoC etc.


So at the end I will say use the pattern wherever applicable, it should not overkill your smaller project. Hope the above article is useful to you and if you have any real time stories to share about Dependency Injection please don't forget to leave a comment below, also give a small like or share. Keep visiting for latest posts.

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 All rights reserved. Powered By- Sanjoy Dey Productions