PHP MySQL script

Useful php and mysql script


1. Use empty() insted of isset() ; 
 
Isset() checks if a variable has a value including ( Flase , 0 , or Empty string) , But not NULL. 
In other words, a variable is set if it has been assigned a value other than NULL.

On the other hand the empty() function checks if the variable has an empty value empty string , 0, NULL ,or False. 
Returns FALSE if var has a non-empty and non-zero value. 
 
In other words, a variable is empty if it is an empty string, 0, “0″, false, NULL, array(), and an unset variable are all empty. 
<?php
        $var = NULL;
        
        if(isset($var)){
            echo " I am set". PHP_EOL;            
        }
        
        if(empty($var)){
            echo " I am empty". PHP_EOL;
        }
 ?>
 
 Output : 
        
        I am empty

 <?php
 
        $var = '';
         
        if(isset($var)){
            echo " I am set". PHP_EOL;
        }
         
        if(empty($var)){
            echo " I am empty". PHP_EOL;
        } 
        
?>
 Output : 
    I am set     I am empty

Note: Now when you are validating forms to make sure a user did not leave a form field blank, it is probably best to use neither empty() or isset(). Since it is possible your form might accept 0 as a valid answer. Therefore you should just check to make sure it is not an empty string.
 
<?php

if($_GET['var'] == "") {
    echo "You must enter a value for var!". PHP_EOL;
}
?>

You can add headers to the HTTP response in PHP using the Header() function. Since the response headers are sent before any of the actual response data, you have to send these headers before outputting any data. So, put any such header calls at the top of your script.

Redirection
<?php
    header('Location: http://www.php.net');
?>
Setting a Last-Modified Header
<?php
 header('Last-Modified: '.gmdate('D, d M Y H:i:s',getlastmod()).' GMT');
?>

Avoid all Caching
<?php
 header('Cache-Control: no-cache, must-revalidate');
 header('Pragma: no-cache');
 header('Expires: Mon,13 Jal 1980 05:00:00 GMT');
?>


Many times I get request from client for data dump. I use mysql database, and in mysql it is quite
easy to create CSV files directly from MySQL with just one query!

Let's say you want to export the email and name fields from your member table to a CSV file. Here is your code:

SELECT email, name INTO OUTFILE '/tmp/data_dump_member.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM member
Note : Make sure your MySQL server has write permissions to the location where you want to store the results file.

You can either download the csv file from server's '/tmp' directory, or you can move this to http root directory and send link to client to download.
cd /tmp/
mv data_dump_member.csv /var/www/html/
gzip -9 data_dump_member.csv

Object Oriented programming requires a different way of thinking how you construct your applications. Objects enable you to more closely model in code the real-world tasks, processes and ideas that your application is designed to handle. You can think of a class as a blueprint for constructing an object, you can build multiple instance of an object.

Lets start with creating a simple class example

Class begins with keyword Class and followed by a name that isn't reserved word in php. It contains the definition of methods, members and attributes of a class.
<?php
class demo{

    private $_name;

    public function __construct($name){
        $this->_name = $name;
    }

    public function getName(){
        return $this->_name;
    }

    public function setName($name){
        $this->_name = $name;
    }

    public function __destruct(){
    
    }
}
?>
The contructor to this object set class property 'name'.  The accessor method getname(), enable you to fetch the value of the private member variable. Similarly, the setname() method enable you to assign a new value to variable.

In test_demo.php, write following lines
<?php
require_once('class_demo.php');
try {
    $objdemo = new Demo('example1');
    echo "Class name is : ". $objdemo->getName();
    $objdemo->setName('Example2');
    echo "Class new name is : " . $objdemo->getName();
} catch(Exception $e) {
    echo "There was a problem :" . $e->getMessage();    
}
?>
Access this file in your favourite browser, output should be somethink like following :
       Class name is : example1
       Class new name is : example2


This post describes how to properly redirect a web page using an HTTP 301 status code and Location header. The 301 status code is used to indicate that a page has permanently moved. 301 redirect is the most efficient and Search Engine Friendly method for webpage redirection. PHP redirect tells the browser (or a search engine bot) that the page has been permanently moved to a new location.
<?php
// Permanent redirection
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.new-domain.com/");
exit();
?>
If you set the Location header by itself, PHP automatically sets the status code to HTTP/1.1 302 Found

Note: if you attempt to send headers after content has been sent, you will get a warning like, "Warning: Cannot modify header information - headers already sent by ...". Look for empty lines and spaces between PHP open and close tags.

Tip: Use lower-case name for the header function (not Header) to make sure your PHP redirect code is compatible with PHP 6.

You can redirect the page to new location along with parameters; this PHP code will redirect users to new location along with its query string:
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.new-domain.com".strtolower($REQUEST_URI));
exit();
?>