Archive for the 'PHP' Category

PHP/MySQL Interview Questions

Thursday, September 14th, 2006

How can we repair a MySQL table?
The syntax for repairing a mysql table is
REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]
This command will repair the table specified
if the quick is given the mysql will do a repair of only the index tree if the extended is given it will create index row by row

maximum length of mnames of database, table, columns
database- 64
table -64
columns-64
alias-255

How many values can the SET function of MySQL take?
Mysql set can take zero or more values but at the maximum it can take 64 values
What are the other commands to know the structure of table using MySQL commands except explain command?
describe table_name;

How can we find the number of rows in a table using MySQL? How can we find the number of rows in a result set using PHP?
Use this for mysql
>SELECT COUNT(*) FROM table_name;
but if u r particular about no of rows with some special result
do this
>SELECT [colms],COUNT(*) FROM table_name [where u put conditions];

and for PHP it cant be more simple

$result = mysql_query($any_valid_sql, $database_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;
#

How many ways we can we find the current date using MySQL?
SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()

What is the difference between char and varchar data types?
Set char to occupy n bytes and it will take n bytes even if u r storing avalue of n-m butes
Set varchar to occupy n bytes and it will take only the required space and will not use the n bytes
eg. name char(10) will waste 5 bytes if we store ‘kumar’, if each char takes a byte
eg. name varchar(10) will just use 5 bytes if we store ‘kumar’, if each char takes a byte. rest 5 bytes will be free.

What is the functionality of md5 function in PHP?
string md5(string)
Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. I use it to generate keys which I use to identify users etc. If I add random no techniques to it the md5 generated now will be totally different for the same string I am using.

How can I load data from a text file into a table?
The mysql provides a LOAD DATA INFILE syntax. U can load data from a file. Gr8 tool but u need to make sure that
a) data is delimited
b) u match the colms and data correctly
dont use w/out first learning the syntax

How can we know the number of days between two given dates using MySQL?
Use DATEDIFF()
>SELECT DATEDIFF(NOW(),’1947-08-15′);
will give u the exact no of days India got independence from British.

How can we know the number of days between two given dates using PHP?
Simple arithmetic.
$date1 = date(”Y-m-d”);
$date2 = “1947-08-15″;
$days = (strtotime() - strtotime()) / (60 * 60 * 24);
echo “No of $days we got independence from Britts”;

How can we change the name of a column of a table?
How can we change the name and data type of a column of a table?
this will change the name of colm
> ALTER TABLE table_name CHANGE old_colm_name new_colm_name
this will change the name of colm and also the datatype
> ALTER TABLE table_name CHANGE old_colm_name new_colm_name [data type]

What are the differences between drop a table and truncate a table?
DROP TABLE table_name
Will DELETE the table and DATA
TRUNCATE TABLE table_name
Will DELETE the table DATA not the table definition

What is PEAR in PHP
PEAR is short for “PHP Extension and Application Repository” and is pronounced just like the fruit. The purpose of PEAR is to provide:

  • A structured library of open-sourced code for PHP users
  • A system for code distribution and package maintenance
  • A standard style for code written in PHP
  • The PHP Foundation Classes (PFC),
  • The PHP Extension Community Library (PECL),

A web site, mailing lists and download mirrors to support the PHP/PEAR community

PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.

http://pear.php.net/manual/en/introduction.php

What is the difference between GROUP BY and ORDER BY in Sql?
Group by which is used to sort a table interms of colums order by which is used to index a table by colum value
ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on.
GROUP BY [col1],[col2],…,[coln]; Tels DBMS to group results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average

What is MIME?
MIME is Multipurpose Internet Mail Extensions is an internet standard for the format of e-mail. Howewer browsers also uses MIME standart to transmit files. MIME has a header wich is added to a begining of the data. When browser sees such header it shows the data as it would be a file (for example image)
some mimes:
audio/x-ms-wmp
image/png
aplication/x-shockwave-flash

How can we know that a session is started or not?
a session starts by session_start()function.
this session_start() is always declared in header portion.it always declares first.then we write session_register().

What are the differences between MySQL_fetch_array(), MySQL_fetch_object(), MySQL_fetch_row()?
Ans:- MySQL_fetch_array()->Fetch a result row as an associative array,numeric array.
MySQL_fetch_object()->Fetch a result row as an object.
MySQL_fetch_row()->Fetch a result set as an array().

If we login more than one browser window at the same time with same user and after that we close one window then is the session is exist to other window or not.And if yes then why? or if no then why?
If we login more than one browser window at the same time with same user and after that we close one window then is the session is exist to other window or not.And if yes then why? or if no then why?
session depends on browser. if browser is closed then session is lost. the session data will be deleted after session time out. if connection is lost and u recreate connection, then also sesssion will continue in the browser.

What are the database files stored in system?
data’s are stored in name.Myd
table Structure are name.$frm
Index tables are name.myi

Difference between php4 and php5?
php4 cannot support oops concepts and zend engine1 will be used
in php5 support oops concepts and zends engine2 will be used
error supporting will increased in php5
xml and sqllite will be incresed in php5

Single Quotes vs Double Quotes in PHP

Tuesday, August 1st, 2006

Most of us use only Double Quotes ['’] when writing PHP code. Usage of single quotes is better than using Double Quotes

Instead of :

<?php echo “Visit http://www.weberblog.com/“;?>

You can Use :

<?php echo ‘Visit http://www.weberblog.com‘;?>

In the above example there is no difference but have a look at this example :

Double Quotes way :

<?php echo ” <table cellspacing=”\” cellpadding=”\” border=”\”>”;?>

Single Quotes way :

<?php echo ‘<table cellspacing=”0″ cellpadding=”0″ border=”1″>’; ?>

In this example you can see that we don’t need to add escape characters for each Double Quote we want to echo as HTML. This, by its self is a good enough reason to migrate, however, a 2nd reason is performance. Using Single Quotes is always at least as fast as Double Quotes and in some cases faster by hundreds of percents.

Conclusion:Single and double quoted strings behave almost the same with one exception: Don’t use the a lonely ($) in double quoted string unless you want to reference a PHP-var; or use (\$).

Note : When working with special formatting characters such as \n \r \t etc… Single Quotes are somewhat problematic because they ignore these formatting codes. What you need to do in case you need these formatting codes is :

<?php echo ‘check out http://www.weberblog.com . “\n\r” . ‘for the best PHP, MySQL Web Logs on the net’;?>

Small Note on Class and Objects (PHP 5) from PHP manual

Thursday, July 20th, 2006

Class
Every Class definition begins with keyword class. Class is a combination of member function and member variables. A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object).

Autoloading Objects
_autoload function will get called automatically in case of trying to use a class which is not defined. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Constructors
Constructors are used to intialize the objects before it is used.

Destructors
Destructors method will be called as soon as all references to a particular object are removed or when the object is explicitily destroyed

Visibility
The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.

Scope Resolution Operator
Token which allows access to static, constant, and overridden members or method of a class. When referencing these items from outside the class definition, use the name of the class

Static Keyword
Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).

Abstraction
Abstract class is the class in which instance cannot be created.Methods defined as abstract simply declare the method’s signature they cannot define the implementation.

Overloading
Both method calls and member accesses can be overloaded via the __call, __get and __set methods. These methods will only be triggered when your object or inherited object doesn’t contain the member or method you’re trying to access. All overloading methods must not be defined as static.

Final Keyword
Final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Best Practices for Function/Method

Monday, May 22nd, 2006

Returning arrays with care
When your function (or method) returns an array, you need to ensure that the return value is a defined array because the code from which the function is called is expecting an array. For example, review the following bad code segment.

// BAD
function getData()
{
$stmt = “SELECT ID, myField1, myField2 from myTable”;
$result = $this->dbi->query($stmt);
if ($result != NULL)
{
while($row = $result->fetchRow())
{
$retArray[$row->ID] = $row;
}
}
return $retArray;
}
In this example, the function called getData() returns an array called $retArray when the SQL statement executed returns one or more rows. The function works fine if the SQL select statement always returns at least one row. However, it returns nothing when the SQL statement returns no rows. In such a case, the following code segment, which calls the function, produces a PHP warning
message:
error_reporting(E_ALL);
$rowObjectArray = $this->getData();
while(list($id, $rowObject) = each($rowObjectArray))
{
// do something here
}
$rowObjectArray causes each() to generate a warning when the myFunction() method fails to return a real array. Here’s a better version of the getData() method:

// GOOD
function getData()
{
$retArray = array();
$stmt = “SELECT ID, myField1, myField2 from myTable”;
$result = $this->dbi->query($stmt);
if ($result != null)
{
while($row = $result->fetchRow())
{
$retArray[$row->ID] = $row;
}
}
return $retArray;
}
The second version of getData() function initializes $retArray as an array, which ensures that functions such as each() do not complain about it.

Best Practices for naming variables and functions in PHP

Monday, May 22nd, 2006

When creating a variable or function ask yourself the following questions. What is the purpose of the variable? In other words, what does this variable hold? Can you use a descriptive name that represents the data the variable holds?

If the descriptive name appears to be too long, can you use meaningful abbreviations? For example, $textMessage is as good as $txtMsg.
Names exceeding 15 characters probably need to be reconsidered for abbreviation.

Use title casing for each word in multiword names. However, the very first word should be lowercase. For example, $msgBody is a better name
then $msgbody, $messageBODY, or $message_body. Single word names should be kept in lowercase. For example, $path and $data are single
word variables.

Use all capital letters to name variables that are “constant like” — in other words, variables that do not change within the application. For
example, if you read a variable from a configuration file, the name of the variable can be in all uppercase. To separate uppercase words, use underscore character (for example, use $TEMPLATE_DIR instead of $TEMPLATEDIR). However, when creating constants it is best to use define()
function. For example, define(PI, 3.14) is preferred over $PI = 3.14. The defined constant PI cannot be changed once defined whereas $PI can
be changed.

Use verbs such as get, set, add, delete, modify, update, and so forth in naming your function or method. For example, getSomething(),setSomething(), and modifySomething() are better function names than accessSomething(), storeSomething(), and editSomething(),respectively.