Thursday, 5 July 2018

Welcome to my blog

I didn't choose PHP, I got a job(my first) that required good skills in PHP. So, I guess you can say that PHP chose me. Since then, I have been in love with the language, now I feel like I'm kind of addicted to it. I learned it the hard way, by coding, browsing the internet to find the answers, more coding and with it a lot of frustration. But now, looking back, I can't believe I have learned so much in the past few months. So, the only advice I would like to give to anybody starting PHP is, be patient, try out few things, use php.net, join blogs like Nettuts, but most importantly, build, build and build more. If you have a programming language like I did in C and C++, you won't find PHP difficult.

I created this blog so that I can document anything that I find interesting or important. Writing things down has never been my thing. The stuff that I write here are mostly my understanding of the work done by people like Jeffrey Way of Nettus and Alex of PhpAcademy. Jeffrey Way once wrote an article on Nettuts describing how difficult it was for him at first in the web developing industry. That really inspired me during my initial stages when I was struggling with the syntax of PHP. Its always good to know that even the best in the business had to struggle at first. Following the work done by these guys is so much fun.  And interpreting them in my own words, even more so.

I plan to also include a few projects that I have done for my company, like creating Apps for Facebook and Twitter and converting HTML to PDF using Fpdf library.

Wednesday, 20 March 2013

jQuery: How to change image src attribute to ''

Suppose you are doing an Ajax request and you want a loading image to show up till you get the result
You do something like this

$('#loader_img').attr('src','images/ajax-loader.gif');
$.ajax({

    type : "POST",
    url : 'validate_form.php',
    data : params
     }).done(function(msg){
$('#loader_img').attr('src','');
});

But it is more than likely that this is not gonna workout and you will still see the image after the ajax request is completed. The solution would be to put a base64 encoded value of an empty image as the src like this
$('#loader_img').attr('src','data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==');

Tuesday, 28 February 2012

How to use multiple selection check boxes with PHP

A multiple selection checkbox will look like this:


In order to post each values properly, we need to use the name attribute as an array, like this,
 <select multiple name = "opts[]" size="4">
Now lets try whats being POSTed,
<?php
if(isset($_POST['submit']))
echo '<pre>';
 print_r($_POST);
 echo '</pre>';
?>
<html>
<head>
    <title>1</title>
</head>
<body>
 <form method="post">
  <select multiple name = "opts[]" size="4">
   <option value="1">One</option>
   <option value="2">Two</option>
  <option value="3">Three</option>
  <input type="submit" value="submit" name="submit" />
  </select>
 </form>
</body>
</html>
Gives a nice array like this:
Array
(
    [opts] => Array
        (
            [0] => 2
            [1] => 3
        )

    [submit] => submit
)

Thursday, 23 February 2012

WTF is THIS

Simply do a console.log(this). You will see that this refers to the parent or the window object.

Lets try it inside a self invoking function, like this:
(function doSomething(){
   console.log(this);
})();


Again it gives the window object

Now lets try to run the function when an anchor tag is clicked
<a href="http://www.google.ca">click</a>

$('a',on('click',doSomething)); 
Now you will see that this will refer to the anchor tag.

Suppose if we put the functin as a method inside an object like this:
var obj = {
        init : function(e){
                e.preventDefault();
                console.log(this);
            }
    };

    $('a').on('click',obj.init);
Now also, this will refer to the anchor tag. But if we do like this,
    var obj = {
        init : function(){
                    console.log(this);
            }
    };

    $('a').on('click',function(e){
        obj.init();
            e.preventDefault();
    });
This will refer to the object now.

How to specify what this this refers to:

This can be dcne using the call or apply methods
    $('a').on('click',function(e){
        obj.init.call(this);
            e.preventDefault();
    });
Now, this will refer to the anchor tag instead of the object. You can also pass the

event object like so, obj.init.call(this,e);

You can also use jQuery's $.proxy method to set the value for this manually,
$('a',on('click',$.proxy(obj.init, obj))
If we do like this, this will refer to obj within the function

jQuery Tip: How to properly append content to the DOM

Doing like this is sloppy and bad:
$('<p>Add to the Dom</p>').appendTo('body');
It can get extremely complicated sometimes. Imagine if you want to add a class or add some styling to it. So instead, use this format.

$('<p></p>',{
    text: "Add to the Dom",
   class: "ClassName"
}).insertAfter('h1');

Can using google's CDN for jQuery speed up your web site?

The answer is yes. Even if not by a significant amount, it can speed up you site. This is because there is a fair chance that the user has google's jquery API cached in his browser. Obviously, this would mean your website will load slower if you use the jQuery file stored on your server.

Sunday, 22 January 2012

Simple pagination using PHP

We will be making use of Mysql's LIMIT functionality to do the pagination. If we do like this,
SELECT * FROM pagination limit 0,4;
the first 4 elements will be selected. The first option is the starting number and the 2nd option is the number of elements.
But first, we find out the number of rows, using
SELECT COUNT(*) FROM pagination;
Then the number of pages will be equal to count/no. of elements in one page.
We then need to pass the page number as a GET variable like this,
<a href="?page='.$i.'">' .$i.'</a>, //$i will be in a for loop incrementing from 1 to no. of pages

It is always a good idea to do the database connections on a seperate page
prepare($sql);
$stmt->bind_param('ii',$start,$num_results);
$pages = 'SELECT count(*) FROM pagination';
$stmt2 = $conn->query($pages);
$count = $stmt2->fetch_array();
$count = $count[0];
?>


The bind_param function will bind the variables $start and $num_results to dynamically insert the values for the LIMIT function.
$count stores the number of rows.

Now in the second page, we calculate the number of pages and the starting value for the LIMIT function i.e, $start which will be ($page - 1) * $num_results where $page is the page number. For example, if we click on page 3, it should display results from 2*4 =8 to 12.
But first we should check if GET is set using isset function like this,
if(isset($_GET['page'])){
  $page = $_GET['page'];
}
else $page=1;
This is to put the default page as 1.
We then execute the query using execute() and bind the results to variables.

So, here is the index.php page,
execute() or die("Error with query");
$stmt->bind_result($id,$name);

while($stmt->fetch()){
     echo $id.$name.'
'; } for($i=1;$i<$num_pages+1;$i++) { echo ($i == $page) ? '' .$i.'' : '' .$i.''; } ?>
In the final step, we have checked the condition, $i==$page to make the current page bold.