Tuesday, 12 June 2012

Php isset


isset

(PHP 4, PHP 5)
issetDetermine if a variable is set and is not NULL

reject note Description

bool isset ( mixed $var [, mixed $... ] )
Determine if a variable is set and is not NULL.
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

reject note Parameters

var
The variable to be checked.
...
Another variable ...

reject note Return Values

Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

reject note Changelog

VersionDescription
5.4.0
Checking non-numeric offsets of strings now returns FALSE

Example #1 isset() Examples
<?php

$var 
'';
// This will evaluate to TRUE so the text will be printed.if (isset($var)) {
    echo 
"This var is set so I will print.";
}
// In the next examples we'll use var_dump to output
// the return value of isset().
$a "test";$b "anothertest";
var_dump(isset($a));      // TRUEvar_dump(isset($a$b)); // TRUE
unset ($a);
var_dump(isset($a));     // FALSEvar_dump(isset($a$b)); // FALSE
$foo NULL;var_dump(isset($foo));   // FALSE
?>


This also work for elements in arrays:

<?php

$a 
= array ('test' => 1'hello' => NULL'pie' => array('a' => 'apple'));
var_dump(isset($a['test']));            // TRUEvar_dump(isset($a['foo']));             // FALSEvar_dump(isset($a['hello']));           // FALSE

// The key 'hello' equals NULL so is considered unset
// If you want to check for NULL key values then try: 
var_dump(array_key_exists('hello'$a)); // TRUE

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUEvar_dump(isset($a['pie']['b']));        // FALSEvar_dump(isset($a['cake']['a']['b']));  // FALSE
?>

Example #2 isset() on String Offsets
PHP 5.4 changes how isset() behaves when passed string offsets.
<?php
$expected_array_got_string 
'somestring';var_dump(isset($expected_array_got_string['some_key']));var_dump(isset($expected_array_got_string[0]));var_dump(isset($expected_array_got_string['0']));var_dump(isset($expected_array_got_string[0.5]));var_dump(isset($expected_array_got_string['0.5']));var_dump(isset($expected_array_got_string['0 Mostel']));?>
Output of the above example in PHP 5.3:
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
Output of the above example in PHP 5.4:
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)


        

Friday, 4 May 2012

Linux interview questions 3


What are the process states in Linux?
Process states in Linux:
Running: Process is either running or ready to run
Interruptible: a Blocked state of a process and waiting for an event or signal from another process
Uninterruptible:-  a blocked state. Process waits for a hardware condition and cannot handle any signal
Stopped: Process is stopped or halted and can be restarted by some other process
Zombie: process terminated, but information is still there in the process table.

What is a zombie? 
Zombie is a process state when the child dies before the parent process. In this case the structural information of the process is still in the process table. Since this process is not alive, it cannot react to signals. Zombie state can finish when the parent dies. All resources of the zombie state process are cleared by the kernel

Explain each system calls used for process management in linux.
System calls used for Process management:
Fork () :- Used to create a new process
Exec() :- Execute a new program
Wait():- wait until the process finishes execution
Exit():- Exit from the process
Getpid():- get the unique process id of the process
Getppid():- get the parent process unique id
Nice():- to bias the existing property of process

Linux interview questions 2


What does nslookup do? Explain its two modes.
Nslookup is used to find details related to a Domain name server. Details like IP addresses of a machine, MX records, servers etc. It sends a domain name query packet to the corresponding DNS.
Nslookup has two modes. Interactive and non interactive. Interactive mode allows the user to interact by querying information about different hosts and domains.
Non interactive mode is used to fetch information about the specified host or domain.
Interactive mode:
Nslookup [options] [server]

What is Bash Shell?
Bash is a free shell for UNIX. It is the default shell for most UNIX systems. It has a combination of the C and Korn shell features.  Bash shell is not portable. any Bash-specific feature will not function on a system using the Bourne shell or one of its replacements, unless bash is installed as a secondary shell and the script begins with #!/bin/bash. It supports regular and expressions. When bash script starts, it executes commands of different scripts.

Explain Some Network-Monitoring Tools in Linux: ping, traceroute, tcpdump, ntop
Network monitoring tools are used to monitor the network, systems present on the network, traffic etc.
Ping: Ping command is used to check if the system is in the network or not. To check if the host is operating.
e.g. ping ip_address
When the command is executed, it returns a detailed summary of the host. Packets   sent, received, lost by estimating the round trip time.
Traceroute : the command is used to trace the path taken by the packet across a network. Tracing the path here means finding out the hosts visited by the packet to reach its destination. This information is useful in debugging. Roundtrip time in ms is shown for every visit to a host.
Tcpdump: commonly used to monitor network traffic. Tcdump captures and displays packet headers and matching them against criteria or all. It interprets Boolean operators and accepts host names, ip address, network names as arguments.
Ntop : Network top shows the network usage. It displays summary of network usage by machines on the network in a format as of UNIX top utility. It can also be run in web mode, which allows the display to be browsed with a web browser. It can display network traffic statistics, identify host etc. Interfaces are available to view such information.

Explain file system of linux. The root "/" filesystem, /usr filesystem, /var filesystem, /home filesystem, /proc filesystem.
Root "/" file system: The kernel needs a root file system to mount at start up. The root file system is generally small and should not be changed often as it may interrupt in booting. The root directory usually does not have the critical files. Instead sub directories are created. E.g. /bin (commands needed during bootup), /etc (config files) , /lib(shared libraries).
/usr filesystem : this file system is generally large as it contains the executable files to be shared amongst different machines. Files are usually the ones installed while installing Linux. This makes it possible to update the system from a new version of the distribution, or even a completely new distribution, without having to install all programs again. Sub directories include /bin, /include, /lib, /local (for local executables)
/var filesystem : this file system is specific to local systems. It is called as var because the data keeps changing. The sub directories include /cache/man (A cache for man pages), /games (any variable data belong to games), /lib (files that change), /log (log from different programs), /tmp (for temporary files)
/home filesystem: - this file system differs from host to host. User specific configuration files for applications are stored in the user's home directory in a file. UNIX creates directories for all users directory. E.g /home/my_name. Once the user is logged in ; he is placed in his home directory.
/proc filesystemthis file system does  not exist on the hard disk. It is created by the kernel in its memory to provide information about the system. This information is usually about the processes. Contains a hierarchy of special files which represent the current state of the kernel .Few of the Directories include /1 (directory with information about process num 1, where 1 is the identification number), /cpuinfo (information about cpu), /devices (information about devices installed), /filesystem (file systems configured), /net (information about network protocols), /mem (memory usage)

Linux interview questions 1


What is Kernel? Explain the task it performs. 
Kernel is used in UNIX like systems and is considered to be the heart of the operating system. It is responsible for communication between hardware and software components. It is primarily used for managing the systems resources as well.
Kernel Activities:
The Kernel task manager allows tasks to run concurrently.
Managing the computer resources: Kernel allows the other programs to run and use the resources

Resources include i/o devices, CPU, memory.
Kernel is responsible for Process management. It allows multiple processes to run simultaneously allowing user to multitask.
Kernel has an access to the systems memory and allows the processes to access the memory when required.
Processes may also need to access the devices attached to the system. Kernel assists the processes in doing so.
For the processes to access and make use of these services, system calls are used.

What is Linux Shell? What is Shell Script?
Linux shell is a user interface used for executing the commands. Shell is a program the user uses for executing the commands. In UNIX, any program can be the users shell. Shell categories in Linux are:
Bourne shell compatible, C shell compatible, nontraditional, and historical
A shell script, as the name suggests, is a script written for the shell. Script here means a programming language used to control the application. The shell script allows different commands entered in the shell to be executed. Shell script is easy to debug, quicker as compared to writing big programs. However the execution speed is slow because it launches a new process for every shell command executed. Examples of commands are cp, cn, cd.

What are Pipes? Explain uses of pipes.
A pipe is a chain of processes so that output of one process (stdout) is fed an input (stdin) to another. UNIX shell has a special syntax for creation of pipelines. The commands are written in sequence separated by |. Different filters are used for Pipes like AWK, GREP.
e.g. sort file | lpr ( sort the file and send it to printer)
Uses of Pipe
Several powerful functions can be in a single statement
Streams of processes can be redirected to user specified locations using >

Explain trap command; shift Command, getopts command of linux.
Trap command: controls the action to be taken by the shell when a signal is received.
Trap [OPTIONS] [ [arg] signspec..]
Arg is the action to be taken or executed on receiving a signal specified in signspec.
e.g. trap “rm $FILE; exit” // exit (signal) and remove file (action)
Shift Command:  Using shift command, command line arguments can be accessed. The command causes the positional parameters shift to the left. Shift [n] where n defaults to 1. It is useful when several parameters need to be tested.
Getopts command: this command is used to parse arguments passed. It examines the next command line argument and determines whether it is a valid option
Getopts {optstring} {variable1}. Here, optsring contains letters to be recognized if a letter is followed by a colon, an argument should be specified. E.g (whether the argument begins with a minus sign and is followed by any single letter contained inside options ) If not, diagnostic messages are shown. It is usually executed inside a loop.

What Stateless Linux server? What feature it offers?
A stateless Linux server is a centralized server in which no state exists on the single workstations. There may be scenarios when a state of a partilcuar system is meaningful (A snap shot is taken then) and the user wants all the other machines to be in that state. This is where the stateless Linux server comes into picture.
Features:
It stores the prototypes of every machine
It stores snapshots taken for those systems
It stores home directories for those systems
Uses LDAP containing information of all systems to assist in finding out which snapshot (of state) should be running on which system.

Thursday, 3 May 2012

PhpMyAdmin Tutorial 6


Retrieving Data with SELECT

Retrieving information from our tables is probably the operation we do most of the times. This is the way to get answers to questions like �what are the cities with a population over a certain number?�.
In fact, we previously did a SELECT when we clicked on the Browse link for table cities. This generated a simple form of the SELECT statement:
SELECT * FROM `cities` LIMIT 0,30;
Here, the asterisk means �all the columns�. We add FROM and the name of the table which we want to query. The LIMIT 0,30 means to start at row number 0 (the first one), and select a maximum of 30 rows.
Let's try a Search to see more options for the SELECT. We go to the Search sub-page for table cities, and we choose only some columns we need:


Then at the bottom of the page, we choose to display by the result by population in descending order:

   
Executing the search generates the following query:
SELECT `city_name` , `population`
FROM `cities`
WHERE 1
ORDER BY `population` DESC LIMIT 0,30
We see that the asterisk has been replaced by a comma-separated list of columns. A condition WHERE 1 has been added by phpMyAdmin, this is a condition which is always true and selects all rows. We will see in a moment that we can replace it with some other condition. Also, the clause ORDER BY appears, followed by the column on which we want to sort results, and the keyword DESC for descending order (we could also use ASC for ascending).

Conditions

To easily add a condition, on the results page we can click on SQL-query: Edit, which brings the Query window popup. We add a condition on the country:
SELECT `city_name` , `population`
FROM `cities`
WHERE country_code = 'zh'
ORDER BY `population`  DESC
which displays all cities located in China (ok, we were a bit lazy with data entry, but you get the picture).
Conditions can be expressed using a rich array of operators and functions. Here are two examples:
Finding the Canadian cities with a population over 100000:
WHERE population > 100000 AND country_code = 'ca'
Finding the cities whose name starts with �A�:
WHERE city_name like 'A%'

 

 

Aggregate functions

Summary information may be generated by grouping on a specific column. Here we ask the average city population per country:
SELECT country_code, AVG(population)
FROM cities
GROUP BY country_code
Other possible aggregate functions are MIN()MAX()SUM() and COUNT(), which compute respectively the minimum value, maximum value, sum of values, and number of values. For example, we could get the number of cities per country with:
SELECT country_code, count(city_name)
FROM cities
GROUP BY country_code

Joins

Normally, a relational database involves many tables, linked on common keys. We may need at times to run queries on more than one table. Linking, or joining, tables can be done using different techniques; we will focus on a simple method involving key comparison.
In the following query, the FROM clause contains a comma-separated list of tables. In the columns list, we use the table name and a dot as a prefix before each column name (not strictly necessary if each column name is only present in one table).
SELECT cities.city_name, cities.population, countries.country_name
FROM cities, countries
WHERE cities.country_code = countries.country_code LIMIT 0,30


Conclusion

The SQL language has much more to it than the basic statements that we have covered here. However, this article has covered the basics of SQL and how to use the phpMyAdmin tool to advance your knowledge of SQL.


<<< PREVIOUS                                                                                                             Will come.....

PhpMyAdmin Tutorial 5


Data modification

In this section, we will learn the basic syntax for the INSERTUPDATEDELETE, and SELECT statements.

Adding Data with INSERT

Let's first examine the INSERT statement, by looking at the code phpMyAdmin generates when we do an Insert operation. We bring up the Insert sub-page, in Table view for the countries table, and we enter data about a country:


When we click Go, the data is inserted and phpMyAdmin shows us the INSERT statement used:
INSERT INTO `countries` ( `country_code` , `country_name` )
VALUES ('ca', 'Canada');
After the INSERT INTO part, we have the table name. In MySQL, we can enclose table names and column names within backticks, in case there are special characters in them, like reserved words or accented characters. Then we open a first set of brackets, listing the columns in which we want to insert, separated by commas. The reserved word VALUES follows, then the last set of brackets enclosing the values, in the same order as the columns list. If the values have a character data type, we have to enclose them within quotes.
We can now insert a city.
INSERT INTO `cities` ( `id` , `city_name` , `latitude` , `longitude` , `population` , `country_code` )
VALUES ('', 'Sherbrooke', '45 23 59.00', '-71 46 11.00', 125000, 'ca');
Here, we put an empty value for id, because this column's auto-increment attribute will provide a value. We also see that the population value, being numeric, does not need to be surrounded by quotes.
Let's end this section by inserting some data for another country and city, which we will need later.
INSERT INTO `countries` ( `country_code` , `country_name` )
VALUES ('zh', 'China');
INSERT INTO `cities` ( `id` , `city_name` , `latitude` , `longitude` , `population` , `country_code` )
VALUES ('', 'Shanghai', '31 13 58.00', '121 26 59.99', 11000000, 'zh');

Updating Data with UPDATE

We first click on Browse for table cities, displayed our single row of data.


By clicking on the small pencil-shaped icon (or Edit link), we go to the Edit panel for this row. We decide to change the population value to 130000. After a click on Save, phpMyAdmin shows the following statement:
UPDATE `cities` SET `population` = '130000' WHERE `id` = '1' LIMIT 1 ;
Here we have the UPDATE keyword, followed by the table name. The SET keyword introduces the list of modifications (here only the population), which follows the format column = new value.
We now see the condition WHERE `id` = '1', which uses the primary key information to limit the change to only this row, i.e. only this city.
The limit 1 part is a safeguard added by phpMyAdmin, in case there would be no primary key defined, to avoid doing the change to more than one row.
More than one column can be changed in a single UPDATE operation:
UPDATE `cities` SET `city_name` = 'Sherbrooke, Qu�bec',
`population` = '130001' WHERE `id` = '1' LIMIT 1 ;

Deleting Data with DELETE

In Browse mode on table cities, clicking on the small red trash-can icon (or Delete link) brings up a dialog to confirm the execution of the following statement:
DELETE FROM `cities` WHERE `id` = '1' LIMIT 1 ;
The syntax is simple, involving just the table name, and the condition to apply for the delete operation.
Omitting the WHERE condition in an UPDATE or DELETE operation is perfectly legal in SQL, but then the operation takes place on every rows of the table!

<<< PREVIOUS                                                                                                                NEXT >>>   

PhpMyAdmin Tutorial 4

Learning SQL Using phpMyAdmin

What is SQL?

Structured Query Language is a non-procedural language used to define, manipulate and retrieve data. It was developed by IBM (System/R project) in 1974-1979. The American National Standards Institute (ANSI) published in 1986 the first official standard of the language (later revised in 1989, 1992 and 1999), and since then,  the industry has widely adopted SQL as the relational database language. Virtually every database system nowadays is interfaced through SQL.
The specific data architecture addressed by SQL is called the relational architectureThe various pieces of data (columns) are grouped into tables contained in databases, and we retrieve data using relations expressed between the tables.
In this article, we will use MySQL, a popular open-source implementation of SQL that is deployed by most Web host providers.

Toolkit for this guide

To be able to do the exercises in this guide, you will need an access to a MySQL server. Your interface to MySQL will be phpMyAdmin, a PHP application running on a PHP-enabled Web server.

Creating Sample Tables

We will use a geographical information system as an example. We decide that we need information about cities and countries, so we design two tables, which will be part of a database called geodb (although any database name would do). To create the tables, we can use phpMyAdmin's Structure sub-page inDatabase view, or we can use the SQL query box to enter the appropriate statement:


The table creation is accomplished with the CREATE TABLE statement, in which we give the new table's name. The statement begins with CREATE TABLE, followed by the table name. Then, enclosed in brackets, we put the list of columns,  and information about the keys. Each column is assigned a name, data type, the NULL or NOT NULL attribute (here, NOT NULL means the column cannot have a NULL value) and a default value, if appropriate.
CREATE TABLE cities (
  id int(11) NOT NULL auto_increment,
  city_name varchar(50) NOT NULL default '',
  latitude varchar(15) NOT NULL default '',
  longitude varchar(15) NOT NULL default '',
  population int(11) NOT NULL default '0',
  country_code char(2) NOT NULL default '',
  PRIMARY KEY  (id)
) TYPE=MyISAM AUTO_INCREMENT=1 ;
The id column is our primary key, a column which uniquely identifies each city. Its data type is INT (an integer number), and MySQL will assign unique numbers to it, thanks to the auto_increment attribute. Note that we cannot use the city name as a primary key, as some city names are not unique in the world. We also use an integer for the population data.
The other columns use character (CHAR) or variable character (VARCHAR) data types. When we know the exact length of data, it's better to use CHAR, specifying the length of the column as in CHAR(2). Otherwise we use a variable character data type, which will take only the space needed by each piece of data, and we specify the maximum length, as in VARCHAR(15).
After the columns list, we have some table-specific information, like its type, and the first value for the auto-increment column. SQL statements end with a semi-colon.
Having created our cities table, we do the same operation, this time for the countries table.
CREATE TABLE countries (
  country_code char(2) NOT NULL default '',
  country_name varchar(100) NOT NULL default ''
) TYPE=MyISAM;
We notice that the country_code column is present in both tables. This shows the relational principle: the country_code in cities refers to the same column incountries. This way, we save on space, having each  country name only once in our database.


<<< PREVIOUS                                                                                                                  NEXT >>>