Sunday, September 29, 2013

how to use APC example cache file in php


APC caching with PHP

Today I have another interesting article for PHP. We will talking about caching, and practice of using caching in php. I will make review of APC caching and will show you how you can use APC in PHP. We will prepare useful class for working with APC for us and several examples. A little of history: Long ago, when computer networks and Web sites only evolved, most web sites were static (and all data/files stored at disks). After, people invented a ‘database’ to store the data they. This was great innovation, was comfortably hold data in database, not in the files as before.


We started saving into database more and more, even small pieces of data. Years passed, the size of sites grew, and people began to notice that the performance of sites falls under the too frequent reading data from database. And we came up with new optimization way – caching (where we store data in the cache files on the server). Interesting, isn`t it? This looks like ‘Forward, to the past’ :-)

But why it happened? It’s simple – the speed of hard drives has increased, even outgrown the velocity of the databases. At the moment I am talking about mySQL. Possible another types of databases still faster. But in any case, progress is not standing still. Now people have learned to use the server memory for data storage. RAM much faster than hard disk, and the price of memory falls all the time, so let’s use all these advantages of the?

Today I have prepared an example on using APC with PHP.


Now –download in package
the source files and lets start coding !

Step 1. PHP

I made this useful class for you. We will use this class to working with memory using APC caching system.

<?

class CacheAPC {

    var $iTtl = 600; // Time To Live
    var $bEnabled = false; // APC enabled?

    // constructor
    function CacheAPC() {
        $this->bEnabled = extension_loaded('apc');
    }

    // get data from memory
    function getData($sKey) {
        $bRes = false;
        $vData = apc_fetch($sKey, $bRes);
        return ($bRes) ? $vData :null;
    }

    // save data to memory
    function setData($sKey, $vData) {
        return apc_store($sKey, $vData, $this->iTtl);
    }

    // delete data from memory
    function delData($sKey) {
        $bRes = false;
        apc_fetch($sKey, $bRes);
        return ($bRes) ? apc_delete($sKey) : true;
    }
}

?>
----------------------------------------------------------------------------- 
I prepared here several necessary functions which we will use: getData,
 setData and delData. Now, lets check first example file: 
 <?php

$aData = array(
    'name' => 'table',
    'color' => 'brown',
    'size' => array(
        'x' => 200,
        'y' => 120,
        'z' => 150,
    ),
    'strength' => 10,
);

require_once('classes/apc.caching.php');
$oCache = new CacheAPC();

echo 'Initial data: <pre>'; // lets see what we have
print_r($aData);
echo '</pre>';

if ($oCache->bEnabled) { // if APC enabled

    $oCache->setData('my_object', $aData); // saving data to memory
    $oCache->setData('our_class_object', $oCache);
 // saving object of our class into memory too

    echo 'Now we saved all in memory, click <a href="ndex2.php">here</a>
 to check what we have in memory';

} else {
    echo 'Seems APC not installed, please install it to perform tests';
}

?> 
----------------------------------------------------------------------------- 
In this file you can see that I saving 2 objects in memory: some 
predefined array and class object. Now, lets check second example file: 

<?php

require_once('classes/apc.caching.php');
$oCache = new CacheAPC();

if ($oCache->bEnabled) { // if APC enabled

    $aMemData = $oCache->getData('my_object'); // getting data from memory
    $aMemData2 = $oCache->getData('our_class_object'); 
// getting data from memory about our class

    echo 'Data from memory: <pre>'; // lets see what we have from memory
    print_r($aMemData);
    echo '</pre>';

    echo 'Data from memory of object of CacheAPC class: <pre>';
    print_r($aMemData2);
    echo '</pre>';

    echo 'As you can see - all data read successfully, now lets remove data 
from memory and check results, click <a href="index3.php">here</a> to continue';

} else {
    echo 'Seems APC not installed, please install it to perform tests';
}

?> 
-----------------------------------------------------------------------------
Here we only reading data from memory. And, as we see – all data is 
successfully read from the memory. Now, lets check last example file:
<?php

require_once('classes/apc.caching.php');
$oCache = new CacheAPC();

if ($oCache->bEnabled) { // if APC enabled

    $oCache->delData('my_object'); // removing data from memory
    $oCache->delData('our_class_object'); // removing data from memory

    $aMemData = $oCache->getData('my_object'); // lets try to get data again
    $aMemData2 = $oCache->getData('our_class_object');

    echo 'Data from memory: <pre>'; // lets see what we have from memory
    print_r($aMemData);
    echo '</pre>';

    echo 'Data from memory of object of CacheAPC class: <pre>';
    print_r($aMemData2);
    echo '</pre>';

    echo 'As you can see - all data successfully removed. Great !';

} else {
    echo 'Seems APC not installed, please install it to perform tests';
}

?>
 

Saturday, September 28, 2013

what is ACID use in PHP??

Database ACID (Atomicity, Consistency, Isolation, Durability) Properties

There are a set of properties that guarantee that database transactions are processed reliably, referred to as ACID (Atomicity, Consistency, Isolation, Durability).

Atomicity

Atomicity refers to the ability of the database to guarantee that either all of the tasks of a transaction are performed or none of them are. Database modifications must follow an all or nothing rule. Each transaction is said to be atomic if when one part of the transaction fails, the entire transaction fails.

Consistency

The consistency property ensures that the database remains in a consistent state before the start of the transaction and after the transaction is over (whether successful or not). For example, in a storefront there is an inconsistent view of what is truly available for purchase if inventory is allowed to fall below 0, making it impossible to provide more than an intent to complete a transaction at checkout time. An example in a double-entry accounting system illustrates the concept of a true transaction. Every debit requires an associated credit. Both of these happen or neither happen.
A distributed data system is either strongly consistent or has some form of weak consistency. Once again, using the storefront example, a database needs to provide consistency and isolation, so that when one customer is reducing an item in stock and in parallel is increasing the basket by one, this is isolated from another customer who will have to wait while the data store catches up. At the other end of the spectrum is BASE (Basically Available Soft-state Eventual consistency).
Weak consistency is sometimes referred to as eventual consistency, the database eventually reaches a consistent state. Weak consistency systems are usually ones where data is replicated; the latest version is sitting somewhere in the cluster, older versions are still out there. Eventually all nodes will see the latest version.

Isolation

Isolation refers to the requirement that other operations cannot access or see the data in an intermediate state during a transaction. This constraint is required to maintain the performance as well as the consistency between transactions in a database. Thus, each transaction is unaware of another transactions executing concurrently in the system.

Durability

Durability refers to the guarantee that once the user has been notified of success, the transaction will persist, and not be undone. This means it will survive system failure, and that the database system has checked the integrity constraints and won't need to abort the transaction. Many databases implement durability by writing all transactions into a transaction log that can be played back to recreate the system state right before a failure. A transaction can only be deemed committed after it is safely in the log.
Durability does not imply a permanent state of the database. Another transaction may overwrite any changes made by the current transaction without hindering durability.

Thursday, September 26, 2013

Easy way to integration of ccavenue payment gateway using php

CCavenue is most popular Payment gateway for online Shopping. It provide payment through using International credit card as well using your Bank (who have bond with CCavenue) online Account or using it's debit card(ATM card). It is one of the most secure place for given your money to online shop.

For Integrate it with your website you should have ccavenue account and they give you a merchant id and a unique key for your site that is most important for money transaction.


Creat a validCCAvenueparam.php  for server side generate valid checksum param
----------------------------------------------------------------------------------------
<?php


function getchecksum($MerchantId,$Amount,$OrderId ,$URL,$WorkingKey)
  {
  $str ="$MerchantId|$OrderId|$Amount|$URL|$WorkingKey";
  $adler = 1;
  $adler = adler32($adler,$str);
  return $adler;
  }


function verifychecksum($MerchantId,$OrderId,$Amount,$AuthDesc,$CheckSum,$WorkingKey)
  {
  $str = "$MerchantId|$OrderId|$Amount|$AuthDesc|$WorkingKey";
  $adler = 1;
  $adler = adler32($adler,$str);

  if($adler == $CheckSum)
  return "true" ;
  else
  return "false" ;
  }


function adler32($adler , $str)
  {
  $BASE =  65521 ;


$s1 = $adler & 0xffff ;
  $s2 = ($adler >> 16) & 0xffff;
  for($i = 0 ; $i < strlen($str) ; $i++)
  {
  $s1 = ($s1 + Ord($str[$i])) % $BASE ;
  $s2 = ($s2 + $s1) % $BASE ;
  //echo "s1 : $s1 <BR> s2 : $s2 <BR>";


}
  return leftshift($s2 , 16) + $s1;
  }


function leftshift($str , $num)
  {


$str = DecBin($str);


for( $i = 0 ; $i < (64 - strlen($str)) ; $i++)
  $str = "0".$str ;


for($i = 0 ; $i < $num ; $i++) 
  {
  $str = $str."0";
  $str = substr($str , 1 ) ;
  //echo "str : $str <BR>";
  }
  return cdec($str) ;
  }


function cdec($num)
  {


for ($n = 0 ; $n < strlen($num) ; $n++)
  {
  $temp = $num[$n] ;
  $dec =  $dec + $temp*pow(2 , strlen($num) - $n - 1);
  }


return $dec;
  }
  ?>
-------------------------------------------------------------------------------------------------------------------------------

Step -2
create cat page form cart.php


 <?php
    $Merchant_Id = "M_apa18528_18528";//This id(also User Id)  available at "Generate Working Key" of "Settings & Options" 
    $Amount = 900;;//your script should substitute the amount in the quotes provided here
    $Order_Id = 689663;//your script should substitute the order description in the quotes provided here
    $WorkingKey = "";//Note : if you empty the working value then CCavenue "return 
Error Code: 108
Error Description: Checksum+mismatch
because CCavenue security key providing to merchant . 

    $Redirect_Url ="http://www.englishleap.com/users/payment/";
    $Checksum = getCheckSum($Merchant_Id,$Amount,$Order_Id ,$Redirect_Url,$WorkingKey); // Validate All value 
    ?>


<form action="https://www.ccavenue.com/shopzone/cc_details.jsp" method="post">
<!--<br/>Merchant_Id:
--><input type="hidden" value="<?php echo $Merchant_Id; ?>" name="Merchant_Id">
<!--<br/>Amount:
--><input type="hidden" value="<?php echo $Amount; ?>" name="Amount">
<!--<br/>Order_Id:
--><input type="hidden" value="<?php echo $Order_Id; ?>" name="Order_Id">
<!--<br/>Redirect_Url:
--><input type="hidden" value="<?php echo $Redirect_Url; ?>" name="Redirect_Url">
<!--<br/>Checksum:
--><input type="hidden" value="<?php echo $Checksum; ?>" name="Checksum">
<!--<br/>billing_cust_name:
--><input type="hidden" value="bp.nayak20000" name="billing_cust_name"> 
<!--<br/>billing_cust_address:
--><input type="hidden" value="" name="billing_cust_address"> 
<!--<br/>billing_cust_country:
--><input type="hidden" value="" name="billing_cust_country"> 
<!--<br/>billing_cust_state:
--><input type="hidden" value="" name="billing_cust_state"> 
<!--<br/>billing_zip:
--><input type="hidden" value="" name="billing_zip"> 
<!--<br/>billing_cust_tel:
--><input type="hidden" value="" name="billing_cust_tel"> 
<!--<br/>billing_cust_email:
--><input type="hidden" value="bp.nayak20000@gmail.com" name="billing_cust_email"> 
<!--<br/>delivery_cust_name:
--><input type="hidden" value="bp.nayak20000" name="delivery_cust_name"> 
<!--<br/>delivery_cust_address:
--><input type="hidden" value="" name="delivery_cust_address"> 
<!--<br/>delivery_cust_country:
--><input type="hidden" value="" name="delivery_cust_country"> 
<!--<br/>delivery_cust_state:
--><input type="hidden" value="" name="delivery_cust_state"> 
<!--<br/>delivery_cust_tel:
--><input type="hidden" value="" name="delivery_cust_tel"> 
<!--<br/>delivery_cust_notes:
--><input type="hidden" value="" name="delivery_cust_notes"> 
<!--<br/>Merchant_Param:
--><input type="hidden" value="" name="Merchant_Param"> 
<!--<br/>billing_cust_city:
--><input type="hidden" value="" name="billing_cust_city"> 
<!--<br/>billing_zip_code:
--><input type="hidden" value="" name="billing_zip_code"> 
<!--<br/>delivery_cust_city:
--><input type="hidden" value="" name="delivery_cust_city"> 
<!--<br/>delivery_zip_code:
--><input type="hidden" value="" name="delivery_zip_code"> 
<input type="submit" class="button-placeorder" value="Pay by CCavenue ">
</form>

Wednesday, September 25, 2013

how to improve english speaking tips top and better way

Hello guys i was facing lot of problem to speak English. i found better improvement to  study this way and also improved my self. i want to share to other people who have facing problem to speak English. i think you can find the way you can and you can ..all the best...:)
below follow those step thoroughly
1.    Make reading the newspaper a daily ritual. You may be comfortable reading a particular section but make an effort to read different articles on every page. The editorial page is highly recommended not only for vocabulary but also for structuring and presenting thought.
2.    Make it a habit to read a new book every week. It is not surprising that those who read a lot develop a good vocabulary. You can consider becoming a member of the local library. Make a list of words that are new to you and look up their meanings in the dictionary.
3.    Watching English movies and television shows is important for improving English and learning new English words. The best part about watching English videos is that you can learn the correct pronunciation as well.
4.    Use vocabulary cards. Vocabulary cards are used by students who are trying to learn many words in a short period of time. You can make your own cards by writing the word on one side and the meaning on the other side of a square piece of paper. It is a convenient tool to learn new words in your free time
5.    Use the internet. The internet is an unlimited resource for reading material. Pick up a topic of your choice and search for articles about it. You will come across plenty of material to read, which you might find interesting, and importantly, will also introduce you to new words. Be sure to look them up in a dictionary.
6.    Don’t forget the new words. The best way to ensure that you never forget the new words you learn is to start using them in your day to day conversation. Do not try to force them into a conversation but do use them if you think they are appropriate.
7.    Learn pronunciation. Most dictionaries provide us with pronunciations of words using phonetic symbols. It is important to learn the sounds that correspond to these phonetic symbols, in order to become comfortable pronouncing new words.
8.    Learning in groups is always more fun. If you have friends who also want to improve their vocabulary, then you can form a group and share new words with each other. You can meet at regular intervals and measure your progress.
9.    Learn the root words. Root words are words from which words grow with the addition of prefixes and suffixes. For e.g.:. The word vocabulary is derived from the Latin root word ‘voc’, which means 'word' or 'name'. Other words like advocacy, vocal and vociferous are also derived from the same root word. Hence, if you can recognize some root words, you will get a fair idea of many derived words. Check out our list of common root words.
10. Keep revising. While it is important to read and learn new words, it is equally important to revise what you have learnt. Fix a particular day of the week to revise all the words you have learnt in that week and add them to your daily vocabulary.

Saturday, September 21, 2013

php mysql experienced interview questions and answers?

Q. What are magic functions or methods in php?
The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

__sleep()   and __wakeup()

serialize() checks if your class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn’t return anything then NULL is serialized and E_NOTICE is issued.
Note:
It is not possible for __sleep() to return names of private properties in parent classes. Doing this will result in an E_NOTICE level error. Instead you may use the Serializable interface.
The intended use of __sleep() is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup(). If present, this function can reconstruct any resources that the object may have.
The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
Differentiate the LIKE and REGEXP operators?
SELECT * FROM pet WHERE name REGEXP “^b”;
SELECT * FROM pet WHERE name LIKE “%b”;
What are the String types are available for a column?
The string types are CHAR, VARCHAR, BLOB, TEXT, ENUM, and SET.
An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time.
An enumeration value must be a quoted string literal; it may not be an expression, even one that evaluates to a string value. For example, you can create a table with an ENUM column like this:
CREATE TABLE sizes (
    name ENUM('small', 'medium', 'large')
); 

What is the REGEXP?
A REGEXP pattern match succeed if the pattern matches anywhere in the value being tested.
What is the difference between CHAR AND VARCHAR?
The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved.
The length of a CHAR column is fixed to the length that you declare when you create the table.
The length can be any value between 1 and 255. When CHAR values are stored, they are right-padded with spaces to the specified length. When CHAR values are retrieved, trailing spaces are removed.
How quoting and escaping work in SELECT QUERY?
SELECT ‘hello’, ‘hello’,‘hello’, ‘hel‘‘lo’, ‘\‘hello’.
What is the difference between BLOB AND TEXT?
A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB differ only in the maximum length of the values they can hold.
The four TEXT types TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT correspond to the four BLOB types and have the same maximum lengths and storage requirements. The only difference between BLOB and TEXT types is that sorting and comparison is performed in case-sensitive fashion for BLOB values and case-insensitive fashion for TEXT values. In other words, a TEXT is a case-insensitive BLOB.
How we get Sum of column?
mysql> SELECT * FROM tablename;
How do you get current user in mysql?
SELECT USER();
How would you change a table to InnoDB?
ALTER TABLE name_file ENGINE innodb;
How do you concatenate strings in MySQL?
CONCAT (string1, string2, string3)
what is difference between primary key and candidate key?
Primary Key
- are used to uniquely identify each row of the table. A table can have only one primary Key.
Candidate Key
- primary key is a candidate key. There is no difference. By common convention one candidate key is designated as a primary one and that key is used for any foreign key references.
How do you get the month from a timestamp?
SELECT MONTH(january_timestamp) from tablename;
What do % and _ mean inside LIKE statement?
% corresponds to 0 or more characters, _ is exactly one character.
If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this table?
999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits.
How do you get the current date in Mysql?
SELECT CURRENT_DATE();
What is the difference between mysql_fetch_array and mysql_fetch_object?
mysql_fetch_array(): – returns a result row as a associated array, regular array from database.
mysql_fetch_object: – returns a result row as object from database.
You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user?
SELECT SQL_CALC_FOUND_ROWS page_title FROM web_pages LIMIT 1,10; SELECT FOUND_ROWS();
What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id)?
It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id
How do you display the list of database in mysql?
SHOW DATABASES;
How do you display the structure of the table?
DESCRIBE table_name;
How do you find out which auto increment was assigned on the last insert?
SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do?
On initialization places a zero in that column, on future updates puts the current value of the timestamp in.
How many drivers in Mysql?
There are eleven drivers in MYSQL .Six of them from MySQL AB and five by MYSQL Communities.They are
PHP Driver
ODBC Driver
JDBC Driver
ado.net5.mxj
CAPI1PHP DRIVER
PERL DRIVER
PYTHON DRIVER
RUBY DRIVER
C WRAPPER
How do you run batch mode in mysql?
mysql < batch-file >;
mysql < batch-file > mysql.out
What Storage Engines do you use in MySQL?
Storage engines used to be called table types.
Data in MySQL is stored in files (or memory) using a variety of different techniques. Each of these techniques employs different storage mechanisms, indexing facilities, locking levels and ultimately provides a range of different functions and capabilities. By choosing a different technique you can gain additional speed or functionality benefits that will improve the overall functionality of your application.
Where MyISAM table is stored?
Each MyISAM table is stored on disk in three files.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension
Define Primary key?
MYSQL allows only one primary key. A primary key is used to uniquely identify each row in a table. It can either be part of the actual record itself.A primary key can consist of one or more fields on a table. When multiple fields are used as a primary key, they are called a composite key.
If the value in the column is repeatable, how do you find out the unique values?
SELECT DISTINCT user_firstname FROM users;
Explain the difference between FLOAT, DOUBLE and REAL?
FLOATs store floating point numbers with 8 place accuracy and take up 4 bytes. DOUBLEs store floating point numbers with 16 place accuracy and take up 8 bytes. REAL is a synonym of FLOAT for now.
How do you get the current version of mysql?
SELECT VERSION();
Is Mysql query has LETTERCASE?
No.
Ex :
SELECT VERSION(), CURRENT_DATE;
select version(), current_date;
SeLeCt vErSiOn(), current_DATE;
What is the LIKE?
A LIKE pattern match, which succeeds only if the pattern matches the entire value.
What are ENUMs used for in MySQL?
You can limit the possible values that go into the table.
CREATE TABLE months (month ENUM ’January’, ’February’, ’March’,); INSERT months VALUES (’April’).
What are the advantages of Mysql comparing with oracle?
MySql is Open source, which can be available any time. Provides Gui with Command Prompt. Supports the administration using MySQL Admin,MySQL Query Browser.Oracle is best database ever in Software development.
What is the difference between CHAR_LENGTH and LENGTH?
The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.
How are ENUMs and SETs represented internally?
As unique integers representing the powers of two, due to storage optimizations.
How do you change a password for an existing user via mysqladmin?
mysqladmin -u root -p password “newpassword”
What Is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.
What is meant by PEAR in php?
Answer1:
PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install packages
Answer2:
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.
How can we know the number of days between two given dates using PHP?
Simple arithmetic:
$date1 = date(’Y-m-d’);
$date2 = ‘2006-07-01′;
$days = (strtotime() – strtotime()) / (60 * 60 * 24);
echo Number of days since ‘2006-07-01′: $days;
How can we repair a MySQL table?
The syntex for repairing a mysql table is:
REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED
This command will repair the table specified.
If QUICK is given, MySQL will do a repair of only the index tree.
If EXTENDED is given, it will create index row by row.
What is the difference between $message and $$message?
Anwser 1:
$message is a simple variable whereas $$message is a reference variable. Example:
$user = ‘bob’
is equivalent to
$holder = ‘user’;
$$holder = ‘bob’;
Anwser 2:
They are both variables. But $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message. For example, if $message contains var, $$message is the same as $var.
What Is a Persistent Cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser’s computer. By default, cookies are created as temporary cookies which stored only in the browser’s memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
Temporary cookies can not be used for tracking long-term information.
Persistent cookies can be used for tracking long-term information.
Temporary cookies are safer because no programs other than the browser can access them.
Persistent cookies are less secure because users can open cookie files see the cookie values.
What does a special set of tags do in PHP?
What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.
How do you define a constant?
Via define() directive, like define (MYCONSTANT, 100);
What are the differences between require and include, include_once?
Anwser 1:
require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.
But require() and include() will do it as many times they are asked to do.
Anwser 2:
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors.
Anwser 3:
All three are used to an include file into the current page.
If the file is not present, require(), calls a fatal error, while in include() does not.
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.
Anwser 4:
File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.
What is meant by urlencode and urldecode?
Anwser 1:
urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode(10.00%) will return 10%2E00%25?. URL encoded strings are safe to be used as part of URLs.
urldecode() returns the URL decoded version of the given string.
Anwser 2:
string urlencode(str)  Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version:
Alphanumeric characters are maintained as is.
Space characters are converted to + characters.
Other non-alphanumeric characters are converted % followed by two hex digits representing the converted character.
string urldecode(str)  Returns the original string of the input URL encoded string.
For example:
$discount =10.00%;
$url = http://domain.com/submit.php?disc=.urlencode($discount);
echo $url;
You will get http://domain.com/submit.php?disc=10%2E00%25?.
How To Get the Uploaded File Information in the Receiving Script?
Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:
$_FILES[$fieldName]['name']  The Original file name on the browser system.
$_FILES[$fieldName]['type']  The file type determined by the browser.
$_FILES[$fieldName]['size']  The Number of bytes of the file content.
$_FILES[$fieldName]['tmp_name']  The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$fieldName]['error']  The error code associated with this file upload.
The $fieldName is the name used in the <INPUT,>.
What is the difference between mysql_fetch_object and mysql_fetch_array?
MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array
How can I execute a PHP script using command line?
Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, php myScript.php, assuming php is the command to invoke the CLI program.
Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.
How to get size & type of uploaded image?
list($width, $height, $type) = getimagesize($_FILES['photo_file']['tmp_name']);
How can we submit a form without a submit button?
The main idea behind this is to use Java script submit( function in order to submit the form without explicitly clicking any submit button. You can attach the document.formname.submit( method to onclick, onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the form after xx seconds once the loading is done (can be seen in online test sites.
In how many ways we can retrieve the data in the result set of MySQL using PHP?
You can do it by  Ways
. mysql_fetch_row.
. mysql_fetch_array
. mysql_fetch_object
. mysql_fetch_assoc
What is the difference between mysql_fetch_object and mysql_fetch_array?
mysql_fetch_object( is similar tomysql_fetch_array(, with one difference – an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names.
What is the difference between $message and $$message?
It is a classic example of PHP’s variable variables. take the following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP variable that we are used to. But the $$message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like this${$message} => $mizanSometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.
How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’
using regular expression of PHP?

preg_match(”/^http:\/\/.+@(.+$/”,’http://info@abc.com’,$found;
echo $found[];
How can we create a database using PHP and MySQL?
We can create MySQL database with the use of
mysql_create_db(“Database Name”
What are the differences between require and include, include_once and require_once?
The include( statement includes and evaluates the specified file.The documentation below also applies to require(. The two constructs are identical in every way except how they handlefailure. include( produces a Warning while require( results in a Fatal Error. In other words, use require( if you want a missingfile to halt processing of the page.
include( does not behave this way, the script will continue regardless.
The include_once( statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include( statement, with the only differencebeing that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.include_once( should be used in cases where the same file might be included and evaluated more than once during a particularexecution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
require_once(
should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
Can we use include (”abc.PHP” two times in a PHP page “makeit.PHP”?
Yes we can use include( more than one time in any page though it is not a very good practice.
What are the different tables present in MySQL, which type of table is generated when we are creating a table in the following syntax:
create table employee (eno int(,ename varchar(0 ?

Total  types of tables we can create
. MyISAM
. Heap
. Merge
. INNO DB
. ISAM
MyISAM is the default storage engine as of MySQL . and as a result if we do not specify the table name explicitly it will be assigned to the default engine.
0
How can we encrypt the username and password using PHP?
0
The functions in this section perform encryption and decryption, and compression and uncompression:
encryption decryption
AES_ENCRYT( AES_DECRYPT(
ENCODE( DECODE(
DES_ENCRYPT(   DES_DECRYPT(

ENCRYPT(       Not available

MD(           Not available

OLD_PASSWORD(  Not available

PASSWORD(      Not available

SHA( or SHA( Not available

Not available   UNCOMPRESSED_LENGTH(
 How are ENUMs and SETs represented internally?
As unique integers representing the powers of two, due to storage optimizations.
 How do you start and stop MySQL on Windows?
net start MySQL, net stop MySQL
 How do you start MySQL on Linux?
/etc/init.d/mysql start
 Explain the difference between mysql and mysql interfaces in PHP?
mysqli is the object-oriented version of mysql library functions.
What’s the default port for MySQL Server?
0
 What does tee command do in MySQL?
tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command note.
 Can you save your connection settings to a conf file?
Yes, and name it ~/.my.conf. You might want to change the permissions on the file to 00, so that it’s not readable by others.
 How do you change a password for an existing user via mysqladmin?
mysqladmin -u root -p password “newpassword”
 Use mysqldump to create a copy of the database?
mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
 Have you ever used MySQL Administrator and MySQL Query Browser?
Describe the tasks you accomplished with these tools.
0 What are some good ideas regarding user security in MySQL?
There is no user without a password. There is no user without a user name. There is no user whose Host column contains % (which here indicates that the user can log in from anywhere in the network or the Internet. There are as few users as possible (in the ideal case only root who have unrestricted access.
 Explain the difference between MyISAM Static and MyISAM Dynamic. ?
In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.
 What does myisamchk do?
It compressed the MyISAM tables, which reduces their disk usage.
 Explain advantages of InnoDB over MyISAM?
Row-level locking, transactions, foreign key constraints and crash recovery.
 Explain advantages of MyISAM over InnoDB?
Much more conservative approach to disk space management – each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy ,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*s execute slower than in MyISAM due to tablespace complexity.
 What are HEAP tables in MySQL?
HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.
 How do you control the max size of a HEAP table?
MySQL config variable max_heap_table_size.
 What are CSV tables?
Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.
 Explain federated tables. ?
Introduced in MySQL .0, federated tables allow access to the tables located on other databases on other servers.
 What is SERIAL data type in MySQL?
BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
0 What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
 Explain the difference between BOOL, TINYINT and BIT. ?
Prior to MySQL .0.: those are all synonyms. After MySQL .0.: BIT data type can store  bytes of data and should be used for binary data.
 Explain the difference between FLOAT, DOUBLE and REAL. ?
FLOATs store floating point numbers with  place accuracy and take up  bytes. DOUBLEs store floating point numbers with  place accuracy and take up  bytes. REAL is a synonym of FLOAT for now.
 If you specify the data type as DECIMAL (,, what’s the range of values that can go in this table?
. to -.. Note that with the negative number the minus sign is considered one of the digits.
 What happens if a table has one column defined as TIMESTAMP?
That field gets the current timestamp whenever the row gets altered.
 But what if you really want to store the timestamp data, such as the publication date of the article?
Create two columns of type TIMESTAMP and use the second one for your real data.
Explain data type TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ?
The column exhibits the same behavior as a single timestamp column in a table with no other timestamp columns.
 What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do?
On initialization places a zero in that column, on future updates puts the current value of the timestamp in.
 Explain TIMESTAMP DEFAULT ‘00:0:0 ::? ON UPDATE CURRENT_TIMESTAMP. ?
A default value is used on initialization, a current timestamp is inserted on update of the row.
 If I created a column with data type VARCHAR(, what would I expect to see in MySQL table?
CHAR(, since MySQL automatically adjusted the data type.
 General Information About MySQL
MySQL is a very fast, multi-threaded, multi-user, and robust SQL (Structured Query Language database server.
0 MySQL is free software.
It is licensed with the GNU GENERAL PUBLIC LICENSE http://www.gnu.org/.
 What Is MySQL
MySQL, the most popular Open Source SQL database, is provided by MySQL AB. MySQL AB is a commercial company that builds is business providing services around the MySQL database. See section . What Is MySQL AB.
 MySQL is a database management system.
A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL. Since computers are very good at handling large amounts of data, database management plays a central role in computing, as stand-alone utilities, or as parts of other applications.
 MySQL is a relational database management system.
A relational database stores data in separate tables rather than putting all the data in one big storeroom. This adds speed and flexibility. The tables are linked by defined relations making it possible to combine data from several tables on request. The SQL part of MySQL stands for “Structured Query Language” – the most common standardized language used to access databases.
 MySQL is Open Source Software.
Open source means that it is possible for anyone to use and modify. Anybody can download MySQL from the Internet and use it without paying anything. Anybody so inclined can study the source code and change it to fit their needs. MySQL uses the GPL (GNU General Public License http://www.gnu.org, to define what you may and may not do with the software in different situations. If you feel uncomfortable with the GPL or need to embed MySQL into a commercial application you can buy a commercially licensed version from us.
 Why use MySQL?
MySQL is very fast, reliable, and easy to use. If that is what you are looking for, you should give it a try. MySQL also has a very practical set of features developed in very close cooperation with our users. You can find a performance comparison of MySQL to some other database managers on our benchmark page. See section . Using Your Own Benchmarks. MySQL was originally developed to handle very large databases much faster than existing solutions and has been successfully used in highly demanding production environments for several years. Though under constant development, MySQL today offers a rich and very useful set of functions. The connectivity, speed, and security make MySQL highly suited for accessing databases on the Internet.
 The technical features of MySQL
For advanced technical information, see section  MySQL Language Reference. MySQL is a client/server system that consists of a multi-threaded SQL server that supports different backends, several different client programs and libraries, administrative tools, and a programming interface. We also provide MySQL as a multi-threaded library which you can link into your application to get a smaller, faster, easier to manage product. MySQL has a lot of contributed software available.
It is very likely that you will find that your favorite application/language already supports MySQL. The official way to pronounce MySQL is “My Ess Que Ell” (not MY-SEQUEL. But we try to avoid correcting people who say MY-SEQUEL.
Session and cookie
What is the difference between session and cookie ?
flash
How can we call flash banner in dreamweaver..
php swapp two name surmane
why we use @?
Give the ans.
what is the difference between sql and mysql
SQL means “structured query language” which is the syntax of commands you send to database. MYSQL is the database program which accepts the those commands and gives out the data.
Please Help
I have created a php site in dreamweaver but i have not stored the files in www directory of wamp. now i want to move the files to www directory without losing the links that i’ve created… how is it possible??
How i get DPI of uploaded image
Can any one tell me how can i get DPI of uploaded image. Thanx
zend framework
Hi evryone, how do i call stored procedure from zend framework using oracle database and how to echo the data. muzeeb
what is the difference between echo and print in php?
When outputting something with PHP, we use print or echo functions. what exactly is the difference between those functions?
PHP – Drupal Joomla Developer required 2 – 3 Years Experienced – MNC Bangalore
Please send your resumes for the Drupal Joomla Opening – Reputed Company – Bangalore Requirement: 2 – 3 years experience in Joomla / Drupal & PHP Contact on bshibin@gmail.com
difference between superkey candidate and primary keys
Super key is the set of attributes in a table that can uniquely identifies a database tuple(row or record). Candidate key is the minimal set of super key that can uniquely identifies a database record. Primary key is one of the candidate keys. you can select any candidate k
Custom redirect in drupal after the node is created?
Please use the following snippet for the custom redirect. function module_form_alter(&$form,$form_state,$form_id){ if (isset($form['#node']) && $form['#node']->type .’_node_form’ == $form_id) { $form['buttons']['submit']['#submit'][] = ‘module_redirect_handler’; }
How to enable HTML option for Drupal menus?
/* *Enabling HTML option for Drupal menus */ function theme_menu_item_link($link) { $link['localized_options']['html'] = true; return l($link['title'], $link['href'], $link['localized_options']); }
Why “pageTracker is not defined” error when using pageTracker._trackPageLoadTime();?
Please try use _gaq.push([‘_trackPageLoadTime’]); instead. It will work !!!
Why mousewheel.js/Jscrollpane.js ( scrolloing using mouse wheel ) not working in Firefox?
It might be because of Jscrollpane.js issue. The Quick solution to solve this issue is to edit the Jscroolpane.js. Go to particular line number ( Mostly:341 ) and change to var dragOffset = $drag.offset(false); currentOffset = { top: dragOffset.top, left:dragOffse
How to create admin settings form in Drupal?
How to extract content between anchor tags using Javascript?
In Jquery we can follow the following to iterate the contents.
Why “#” needs to be encoded in the URLs?
If you are using any “#” in the URLs it should be in the encoded form. Its because of this is used in URLs to mention where the fragment indicators ( eg:bookmarks or anchors in HTML ) begins in URLs.
Checking whether your MySQL server supports partitioning?
Before implementing any user defined partitioning in MySQL we need to make sure whether your mysql server supports partitioning. Finding out the same in your server will be simple. Type SHOW VARIABLES LIKE ‘%partition%’; on the command prompt as shown below. mysql> SHOW
why $_POST is better even though view source of the form gives the details
Plz some one give me the answer
Advantages of MySQL 5.1 compared to MySQL 5
Please find the following features that has been added to the MySQL version 5.1. 1. Partitioning 2. Row Based Replication 3. Plugin API 4. Server log table 5. Upgrade program 6. MySQL Cluster 7. Backup of tablespaces 8. Improvements to INFORMATION_SCHEMA 9. XML functio
disable the drupal cache for a page and for a module in drupal site
There is a contributed module to exclude drupal cache for particular pages in your drupal site. you can find the module in http://drupal.org/project/cacheexclude . for excluding drupal cache for a particular module write the below mentioned code in ur modulename_init() hook
How to send mail using MSSQL Express edition
I need to know the use of MS Sql express edition for sending mails.
Caching – How caching is implemented in Drupal?
For improving the the performance of the Drupal site we can use the caching mechanism. In caching rather than extracting the same data again and again every time, it stores the frequentltay accessed and static data in a convenient place and format. Drawback of caching is that,
Recommend commonly used modules for Drupal?
When an interviewer is asking these question please make sure before recommending any module 1. Whats the use of that module? 2. How well it is supported? 3. Any Vulnerabilities with the module?
Drupal – Overriding style sheets from modules and drupal core
Option 1 To override a core or contributed module style sheet, it must be specified in your theme’s .info file. For example, system-menus.css is located at “modules/system/system-menus.css”. If you place a file with the same name in your theme’s folder and add the following ent
Drupal – Overriding Drupal Core Javascript Files?
cognizant php interview questions?
Do any one have Cognizant/Capgemini interview questions for php/Drupal?
Openings with TCS BPO
Start Career With TCS Walk-in for graduates from the Batch 2010 and 2011 BA/BBA/BBM/B Com/BSc/MSc ( Statistics/Maths ) / M.Com On Saturday 16th April 2011 At TCS, Think Campus,#42, Electronic City, Phase II, Bangalore 100
Why the drupal blocks are disappearing after submitting the form?
Why the drupal blocks are disappearing after submitting the form?
Why the drupal blocks are disappearing after submitting the form?
Do any one have any idea why the blocks are disappearing?
How to create a new region in Drupal 6?
Please follow the following steps to create new regions for Drupal 6 ADD the following region information to you theme.info file: regions[left] = Left sidebar regions[right] = Right sidebar regions[content] = Content regions[header] = Header regions[footer] = Foote
how i can show msg for user when someone try to login
Hello everybody ..! :D i’m working on a E-Bank project , and i need script to show msg for the user when some try to login in at the same username and password at the same time ? Best Regards ..!
Altering form in drupal?
Hook_form_alter Drupal hook function or hook_form_alter(&$form, &$form_state, $form_id) Perform alterations before a form is rendered. One popular use of this hook is to add form elements to the node form. When altering a node form, the node object ca
What is AJAX?
Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire w
What is the difference between constructors in PHP4 & PHP5?
Constructors – PHP4 Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. If a class has no constructor, the constructor of the base cla
What is meant by Exceptional Handling?
Exceptions PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, try and caught within PHP. A Try block must include at least one catch block. Multiple catch blocks can be used to catch different classtypes; execution will co
What is meant by Virtual hosting?
Virtual hosting HTTP includes the concept of virtual hosting, where a single HTTP server can represent multiple hosts at the same IP address. A DNS server can allocate several different host names to the same IP address. When an HTTP client ma
What is meant by Session Clustering?
The Session Manager session support allows multiple server instances to share a common pool of sessions, known as a session cluster Session clustering setting up methods :
How does Database handle Sessions?
As you should be aware the HTTP protocol, as used for serving web pages, is completely stateless. This means that after the server has received a request, processed it and sent a response, the process which dealt with that request dies. Anything that
What is the difference between include and include_once?
Include() The include() statement includes and evaluates the specified file. This also applies to require(). The two constructs are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error.
Tell me some thing about mod_rewrite and url rewriting?
Mod_rewrite *************
What are static methods?
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). The static declar
What is Phishing?
In computing, phishing is a form of criminal activity using social engineering techniques. It is characterized by attempts to fraudulently acquire sensitive information, such as passwords and credit card details, by masquerading as a trustworthy person or business in an ap
Do you know about Cross site Scripting ?
Cross-site scripting (XSS) is a security exploit in which the attacker inserts malicious coding into an link that appears to be from a trustworthy
What is session hijacking?
Session hijacking, also known as TCP session hijacking, is a method of taking over a Web user session by surreptitiously obtaining the session ID and masquerading as the authorized user. Once the user’s session ID has been accessed (through session prediction), the attacker
Authentication – General Definition
Authentication is the process of determining whether someone or something is, in fact, who or what it is declared to be. In private and public computer networks (including the Internet), authentication is commonly done through the use of logon passwords. Knowledge of the p
What is smarty?
Smarty is a template engine written in PHP. Typically, these templates will include variables —such as {$variable}— and a range of logical and loop operators to allow adaptability within of the template.
What is Model-view-controller (MVC)?
Model-view-controller (MVC) is a design pattern used in software engineering. In complex computer applications that present lots of data to the user, one often wishes to separate data (model) and user interface (view) concerns, so that changes to the user interface do not
What is the difference between mysql_fetch_object and mysql_fetch_array?
Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. mysql_fetch_object() example
How can we submit a form without a submit button?
We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form
What is the difference between GET and POST methods in form submitting? Give the cases where we can use GET and POST methods?
The main difference between GET and POST is how the form data is passing. Both are used for passing form field values. All the values which is submitted by the GET method will be appended to the URL. Where as POST method send the data with out appending the URL(
What is the difference between strstr() and stristr()?
Strstr — Find first occurrence of a string strstr() example stristr — Case-insensitive strstr() stristr() example
What is meant by PEAR in php?
PEAR PHP Extension and Application Repository PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wiz
How can we know the count/number of elements of an array?
A) sizeof($urarray) This function is an alias of count() b) count($urarray)
What is the difference between the functions unlink() and unset()?
Unlink is a function for file system handling. It will simply delete the file in context unset will set UNSET the variable
What is meant by urlencode and urldecode?
String urlencode(str) where str contains a string like this “hello world” and the return value will be URL encoded and can be use to append with URLs, normaly used to appned data for GET like someurl.com?var=hello%world string urldocode(str)
How can we repair a MySQL table?
The syntex 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 in
What is the maximum length for database, table & column names?
database- 64 table -64 columns-64 alias-255
What are the commands to find the structure of a MySQL table other than EXPLAIN command?
Describe table_name
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 bytes 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 ‘testname&rsqu
What is the functionality of md5 function in PHP?
Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number.
What is the difference between GROUP BY and ORDER BY in MySQL?
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
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 transm
Is it possible to pass data from JavaScript to PHP?
A. Yes, but not without sending another HTTP request. B. Yes, because PHP executes before JavaScript. C. No, because JavaScript is ser
what is session_start() ?
When a user first encounters a page in your application that call ssession start(),a sessionis created for the user.PHP generates a random session identifier to identify the user,and then it sends a set-Cookieheader to the client.By default,the name of this cookie is PHPSE
How do you convert an old fashioned 10 digit ISBN to a new 13 digit ISBN using php ?
function isbn10_to_13($isbnold){ if (strlen($isbnold) != 10){ // Make sure we have a 10 digit string to start return ‘Invalid ISBN-10
What’s foreign data in php?
* Anything from a form * Anything from $_GET, $_POST, $_REQUEST * Cookies ($_COOKIES) * Web services data * Files
What is str_split function in php?
According to PHP official manual It is used to converts a string to an array. If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character
How can we encrypt and decrypt a data present in a MySQL table using MySQL?
There are two methods AES_ENCRYPT () and AES_DECRYPT ()
How can we find the number of rows in a table using MySQL?
SELECT COUNT(*) FROM tb_nme;
Where MyISAM table is stored ?
Each MyISAM table is stored on disk in three files. The ‘.frm&r
How many types of buffers does use MySQL?
Global buffers and per-connection buffers
what is the use of –i-am-a-dummy flag in MySql?
It Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.
Is MySQL better than MSSQL ?
Mysql is the most popular open source database server right now. It is used by large enteprise level companies and small, single websites. Is mysql actually better? ——————————— Mysql 5.
What is the Use of “WITH ROLLUP” in Mysql?
http://www.w3answers.com
How to determine the number of rows in the full result set and also restrict the number of rows that a query returns….
How to determine the number of rows in the full result set and also restrict the number of rows that a query returns,without running a second query ? Most of the developers using 2 queries to find total numbe
What is the maximum length of a table name, a database name, or a field name in MySQL?
Database name: 64 characters Table name: 64 characters Column name: 64 characters
How many values can the SET function of MySQL take?
MySQL SET function can take zero or more values, but at the maximum it can take 64 values.
How many ways we can we find the current date using MySQL?
SELECT CURTIME(); SELECT CURDATE(); SELECT CURRENT_TIME();
What is the difference between CHAR and VARCHAR data types?
Ans: CHAR is a fixed length data type.
How can we know the number of days between two given dates using MySQL?
Using DATEDIFF() SELECT DATEDIFF(NOW(),’2007-07-15′);
what is database testing and what we test in database testing?
Database testing basically include the following. 1)Data validity testing. 2)Data Integritity testing 3)Performance related to data base. 4)Testing of Procedure,triggers and functions. for doing data validity testing you should be good in SQL q
How can we take a backup of mysql table and restore it?
These are the simplest method to backup and restore the MySQl table For taking the bakup of all the databases mysqldump –user {user
Is it possible to set a time expire page in PHP.?
Yes it is Using header(“Expires: Mon, 26 Jul 2007 05:00:00 GMT&qu
How can we save an image from a remote web server to my web server using PHP?
what is the output of 2^2 in php ?
The answer is 0 (Zero) Important note Everyone expected answer would be 4.But answer is zero.How it happened only in php ? The ^ oper
what is the output of below script?
a. echo ‘line 3′; b. echo ‘line 2′; c. Error d. None of the above Ans: b (Answer is line2)
What is the output here?
a. hello sunil b. Parse error c. hello $x d. syntax error ANS: c published by http://www.w3answers.com
Tutoring Online – Cookies and Sessions
Hi my dear friends. Everybody knows what is cookie and session. But let me tell a truth, most of the beginners don’t know properly what is happening in cookies and sessions and what is the real use .I have taken so many Interviews but none of them given a good
What is PHP?
PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to create dynamic Web pages.
What can PHP do?
Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as coll
Your first PHP script – “Hello World”
PHP Test
How we can pass data from PHP to ASP,ASP.net?
PHP to ASP Let’s first look at how you can pass data from PHP to ASP using WDDX. You create a WDDX packet by first serializi
How can you block certain IP Addresses from accessing your site?
What Storage Engines do you use in MySQL?
MySQL Engines
What is Apache?
The most widely available HTTP server on the Internet. It supports the PERL and PHP languages.
Installing PHP on your Computer?
You can download apache2triad from
How to convert ASP Arrays to PHP and viceversa ?
ASP Arrays to PHP WDDX also allows more-complicated data structures to be passed between applications. Here we will pass an array from an ASP WDDX script to a PHP script.
Which of the following represents the proper way to set a session variable?
A. $_SESSION[‘foo’] = ‘bar’; B. session_start(); C. session_set_save_handler (‘myopen’, ‘myclose’, ‘myread’, ‘mywrite’, ‘mydelete’, ‘mygarbage&
PHP Functions for WDDX
PHP has a few other functions that can be useful when you’re working with WDDX:
what output do you get here?
a. home b. Array c. test d. httpd ANS: httpd
Which of the following functions is most efficient for substituting fixed patterns in strings?
A. preg_replace() B. str_replace() C. str_ireplace() D. substr_replace()
Which function in PHP gives us absolute path of a file on the server?
Ans: getcwd() Here I have stored my files under httdocs (using php5,i haven’t checked under php4) so I get the output as C:\apache2triad\htdocs you may get your path information while runnings the above code. :)
what is the output here ?
The output : http://www.w3answers.com and warning as below Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advise
what is the output ?
a. ouch b. echo c. none d. Parse error ANS: a
How can we extract string “w3answers.com” from a string mailto:info@w3answers.com using regular expression of PHP ?
Answer:  <?php $w3 = “mailto:info@w3answers.com”; preg_match(‘|.*@([^?]*)|’,$w3,$w3output); echo $w3output[1]; ?>
Why should we use Object oriented concepts in php ?
1. Object oriented PHP code is much more reusable because by its’ very nature, it is modular. 2. Object oriented PHP is easier to update. Again, because PHP code is organised into objects. 3. Object oriented PHP makes team programming much easier
which is faster mysql_unbuffered_query or mysql_query ?
When we do the select queries that retrieve large data sets from MySQL, mysql_unbuffered_query in PHP is likely to give better performance than mysql_query. PHP manual says, it “sends a SQL query query to MySQL, without fetching
How to capture content from the output buffer ? or Give me an example for Output caching in php?
What is the difference between $message and $$message?
$message is a simple variable whereas $$message is a variable’s variable,which means value of the variable. Example: $user = ‘bob’ is equivalent to $message = ‘user’; $$message = ‘bob’;
what is the php solution to dynamic caching ?
PHP offers an extremely simple solution to dynamic caching in the form of output buffering.
what are the most common caching policy approaches ?
1)Time triggered caching (expiry timestamp). 2)Content change triggered caching (sensitive content has changed, so cache must be updated). 3)Manually triggered caching (man
What Are PHP Arrays?
PHP arrays are associative arrays with a little extra machinery thrown in. The associative part means that arrays store element values in association with key values rather than in a strict linear index order. (If y
Are php strings immutable ?
PHP strings can be changed, but the most common practice seems to be to treat strings as immutable.Strings can be changed by treating them as character arrays and assigning directly into them, like this:
What is Memcache?
Memcache is a technology which caches objects in memory where your web application can get to them really fast. It is used by sites such as Digg.com, Facebook.com and NowPublic.com and is widely recognized as an essential ingredient in scaling any LAMP
How do I prevent Web browsers caching a page in php?
What is the process that takes place when you upload a file in php?
There are two basic things covered here. The form that will be used to post the file data to and the actual program that does the uploading. Further we will discuss the method that PHP itself suggests for uploading files. Process 1 HTML PART
Will persistent connection work in the CGI version of php ? mysql_connect() vs mysql_pconnect()?
Persistent database connections work only in the module installation of PHP. If you ask for a persistent connection in the CGI version, you will simply get a regular connection.
What are the ‘function problems’ you have met in php?
1)Call to undefined function we_w3answers() PHP is trying to call the function we_w3answers(), which has not been because you misspelled the name of a function (built-in or use
Explain Parse Errors ? what are the most common causes of parse errors ?
The most common category of error arises from mistyped or syntactically incorrect PHP code, which confuses the PHP parsing engine. 1)The missing semicolon If each PHP instruction is not duly finished off with a semicolon, a parse e
List out some session functions in php?
session_save_path — Get and/or set the current session save path session_is_registered — Find out whether a global variable is registered in a session session_unset — Free all session variables session_cache_expire — Ret
What is meant by Persistent Database Connections?
How many ways your web server can utilize PHP to generate web pages?
Mainly there are three ways
How to opening excel files in windows nad linux using php ?
if you’re using PHP on Windows, you can use the inbuilt COM library $excel = ne
what are the ways to check image mime types in php?
There are a few inbuilt options you can use however, for example getimagesize() can return the mimetype, as does some of the new fileinfo functions. The mime type in getimagesize is stored in ‘mime’, and can be accessed as shown below.
Given a line of text $string, how would you write a regular expression to strip all the HTML tags from it?
$stringOfText = “<p>This is a test</p>”; $expression = “/<
what you should know about cookies before start using in php?
There are a few things you should be aware of: 1. Since cookies are used to record info
what are the database space-saving functions available in php ?
# Use ip2long() and long2ip() to store the IP adresses as Integers instead of storing them as strings, which will reduce the
what are the security tips you should know before developing php/mysql web pages ?
1. Do not trust user input. 2. Validate user input on the server side. 3. Do not use user input directly in your MySQL queries. 4. Don’t put integers in quotes In your MySQL queries. 5. Always escape the output using ph
How to get the contents of a web page using php?
You can achieve this using curl in php see the example below.
what are the advantages of storing sessions in database?
If you store a session in a database you have several advantages:
How many HTTP headers will send to a web page(client side) from server when you use sessions (session_start()) in php ?
There are three HTTP headers included in the response: Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache
php supports following database
A) Solid & oracle b) mysql c) None of the above d) All of the above All of the above
PHP comments will be?
A) // b) /* fgfg */ c) All of the above d) First one ANS: All of the above
What is the output for the following script ?
a) syntax error b) runtime error c) all of the above d) hihihi welcome hihihi ANS: d
what is the output below mentioned?
a) String not matched b) Match found c) All of the above d) None of the above ANS : b (no
what is the output below mentioned ?
a) Error b) APPLE c) Apple d) None of the above ANS : APPLE
what is the output below mentioned?
a) mmer b) mer c) all of the above d) none of the above ANS: none of the above NOTE: if we execute the above code we get the output as ‘m programmer’
what is the output here?
a) false b) true c) error d) declaration error ANS : true
what output do you get here?
Www.w3answers.com w3answers.blogspot.com Ans:Array NOTE: use ‘foreach($r as $v)’ then try to output value ‘echo $v’ or use Print_r($r) so if we make above script as
what is scandir() ?
Www.w3answers.com List files and directories inside the specified path By default files order will be ascending $f = scandir($direct, 1); it will display the files as descending order
What function would you use to redirect the browser to a new page?
1. redir() 2. header() 3. location() 4. redirect() ANS:header()
What function can you use to open a file for reading and writing?
1. fget(); 2. file_open(); 3. fopen(); 4. open_file(); ANS:fopen();
How can you get round the stateless nature of HTTP using PHP?
ANS: using Sessions in PHP
What would the following code print to the browser? Why?
Ans: 10 because,its a call by value.$num is static here. change the above code as
What are the different functions in sorting an array?
Ans:
How can we know the number of elements in an array using php?
Ans:There are two ways: 1) sizeof($myarray) – This function is an alias of count() 2) count($array) – This function returns the number of elements in an array. Note if you just pass a simple variable instead of an array, count() will retur
How can we know the number of elements in an array using php?
Ans: There are two ways: 1) sizeof($myarray) – This function is an alias of count() 2) count($array) – This function returns the number of elements in an array. Note if you just pass a simple variable instead of an array, count() will return 1.
How can we get second of the current time using date function?
What will be the following script output?
A. 2 B. 1 C. Null D. True E. 3 Answer A is correct. Because of operator precedence, the modulus operation is performed first, yielding a result of 2 (the remainder of the division of 5 by 2). Then, the result of this operation is
Which data type will the $a variable have at the end of the following script?
A. (int) 1 B. (string) “1” C. (bool) True D. (float) 1.0 E. (float) 1 Answer B is correct. When a numeric string is assigned to a variable, it remains a string, and it is not converted until needed because of an operation that
What will be the following script output?
A. 2 B. 1 C. 3 D. 0 E. Null Answer B is correct.
what is ajax? when ajax was born?
“AJAX is an acronym for Asynchronous JavaScript and XML. If you think it doesn’t say much, we agree. Simply put, AJAX can be read “empowered JavaScript”, because it essentially offers a technique for client-side JavaScript to make background server calls(such as from PHP,ASP.NET,
What API function provides the connection between the client and server?
ANS:XMLHttpRequest
Should I use an HTTP GET or POST for my AJAX calls?
AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idem potency recommendations and is highly recommended for a consis
What is MySQL?
MySQL (pronounced “my ess cue el”) is an open source relational database management system (RDBMS) that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database. Because it is open source, anyone can download MySQL a
What Is a Persistent Cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser’s computer. By default, cookies are created as temporary cookies which stored only in the browser’s memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
  • Temporary cookies can not be used for tracking long-term information.
  • Persistent cookies can be used for tracking long-term information.
  • Temporary cookies are safer because no programs other than the browser can access them.

  • Persistent cookies are less secure because users can open cookie files see the cookie values.
What does a special set of tags do in PHP?
What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.
How do you define a constant?
Via define() directive, like define (”MYCONSTANT”, 100);
What are the differences between require and include, include_once?
Anwser 1:
require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.
But require() and include() will do it as many times they are asked to do.
Anwser 2:
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors.
Anwser 3:
All three are used to an include file into the current page.
If the file is not present, require(), calls a fatal error, while in include() does not.
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.
Anwser 4:
File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.
What is meant by urlencode and urldecode?
Anwser 1:
urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode(”10.00%”) will return “10%2E00%25″. URL encoded strings are safe to be used as part of URLs.
urldecode() returns the URL decoded version of the given string.
Anwser 2:
string urlencode(str) – Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version:
Alphanumeric characters are maintained as is.
Space characters are converted to “+” characters.
Other non-alphanumeric characters are converted “%” followed by two hex digits representing the converted character.
string urldecode(str) – Returns the original string of the input URL encoded string.
For example:
$discount =”10.00%”;
$url = “http://domain.com/submit.php?disc=”.urlencode($discount);
echo $url;
You will get “http://domain.com/submit.php?disc=10%2E00%25″.
How To Get the Uploaded File Information in the Receiving Script?
Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:
  • $_FILES[$fieldName]['name'] – The Original file name on the browser system.
  • $_FILES[$fieldName]['type'] – The file type determined by the browser.
  • $_FILES[$fieldName]['size'] – The Number of bytes of the file content.
  • $_FILES[$fieldName]['tmp_name'] – The temporary filename of the file in which the uploaded file was stored on the server.
  • $_FILES[$fieldName]['error'] – The error code associated with this file upload.
The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>.
What is the difference between mysql_fetch_object and mysql_fetch_array?
MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array
How can I execute a PHP script using command line?
Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.
Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.
I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?
PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.
Would I use print “$a dollars” or “{$a} dollars” to print out the amount of dollars in this example?
In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like “{$a},000,000 mln dollars”, then you definitely need to use the braces.
What are the different tables present in MySQL? Which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2),ename varchar(10))?
Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23. When you fire the above create query MySQL will create a MyISAM table.
How To Create a Table?
If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:
<?php
include “mysql_connection.php”;
$sql = “CREATE TABLE fyi_links (”
. ” id INTEGER NOT NULL”
. “, url VARCHAR(80) NOT NULL”
. “, notes VARCHAR(1024)”
. “, counts INTEGER”
. “, time TIMESTAMP DEFAULT sysdate()”
. “)”;
if (mysql_query($sql, $con)) {
print(”Table fyi_links created.\n”);
} else {
print(”Table creation failed.\n”);
}
mysql_close($con);
?>
Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script, you will get something like this:
Table fyi_links created.
How can we encrypt the username and password using PHP?
Answer1
You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(”Password”);
Answer2
You can use the MySQL PASSWORD() function to encrypt username and password. For example,
INSERT into user (password, …) VALUES (PASSWORD($password”)), …);
How do you pass a variable by value?
Just like in C++, put an ampersand in front of it, like $a = &$b
WHAT IS THE FUNCTIONALITY OF THE FUNCTIONS STRSTR() AND STRISTR()?
string strstr ( string haystack, string needle ) returns part of haystack string from the first occurrence of needle to the end of haystack. This function is case-sensitive.
stristr() is idential to strstr() except that it is case insensitive.
When are you supposed to use endif to end the conditional statement?
When the original if was followed by : and then the code block without braces.
How can we send mail using JavaScript?
No. There is no way to send emails directly using JavaScript.
But you can use JavaScript to execute a client side email program send the email using the “mailto” code. Here is an example:
function myfunction(form)
{
tdata=document.myform.tbox1.value;
location=”mailto:mailid@domain.com?subject=…”;
return true;
}
What is the functionality of the function strstr and stristr?
strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr(”user@example.com”,”@”) will return “@example.com”.
stristr() is idential to strstr() except that it is case insensitive.
What is the difference between ereg_replace() and eregi_replace()?
eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.
How do I find out the number of parameters passed into function9. ?
func_num_args() function returns the number of parameters passed in.
What is the purpose of the following files having extensions: frm, myd, and myi? What these files contain?
In MySQL, the default table type is MyISAM.
Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,
If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?
5, it’s a reference to existing variable.
Write a query for the following question
The table tbl_sites contains the following data:
—————————————
Userid sitename country
—————————————
1 sureshbabu indian
2 PHPprogrammer andhra
3 PHP.net usa
4 PHPtalk.com germany
5 MySQL.com usa
6 sureshbabu canada
7 PHPbuddy.com pakistan
8. PHPtalk.com austria
9. PHPfreaks.com sourthafrica
10. PHPsupport.net russia
11. sureshbabu australia
12. sureshbabu nepal
13. PHPtalk.com italy
Write a select query that will be displayed the duplicated site name and how many times it is duplicated? …
SELECT sitename, COUNT(*) AS NumOccurrences
FROM tbl_sites
GROUP BY sitename HAVING COUNT(*) > 1
How To Protect Special Characters in Query String?
If you want to include special characters like spaces in the query string, you need to protect them by applying the urlencode() translation function. The script below shows how to use urlencode():
<?php
print(”<html>”);
print(”<p>Please click the links below”
.” to submit comments about FYICenter.com:</p>”);
$comment = ‘I want to say: “It\’s a good site! :->”‘;
$comment = urlencode($comment);
print(”<p>”
.”<a href=\”processing_forms.php?name=Guest&comment=$comment\”>”
.”It’s an excellent site!</a></p>”);
$comment = ‘This visitor said: “It\’s an average site! ”‘;
$comment = urlencode($comment);
print(”<p>”
.’<a href=”processing_forms.php?’.$comment.’”>’
.”It’s an average site.</a></p>”);
print(”</html>”);
?>
Are objects passed by value or by reference?
Everything is passed by value.
What are the differences between DROP a table and TRUNCATE a table?
DROP TABLE table_name – This will delete the table and its data.
TRUNCATE TABLE table_name – This will delete the data of the table, but not the table definition.
What are the differences between GET and POST methods in form submitting, give the case where we can use GET and we can use POST methods?
Anwser 1:
When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn’t display these values.
Anwser 2:
When you want to send short or small data, not containing ASCII characters, then you can use GET” Method. But for long data sending, say more then 100 character you can use POST method.
Once most important difference is when you are sending the form with GET method. You can see the output which you are sending in the address bar. Whereas if you send the form with POST” method then user can not see that information.
Anwser 3:
What are “GET” and “POST”?
GET and POST are methods used to send data to the server: With the GET method, the browser appends the data onto the URL. With the Post method, the data is sent as “standard input.”
Major Difference
In simple words, in POST method data is sent by standard input (nothing shown in URL when posting while in GET method data is sent through query string.
Ex: Assume we are logging in with username and password.
GET: we are submitting a form to login.php, when we do submit or similar action, values are sent through visible query string (notice ./login.php?username=…&password=… as URL when executing the script login.php) and is retrieved by login.php by $_GET['username'] and $_GET['password'].
POST: we are submitting a form to login.php, when we do submit or similar action, values are sent through invisible standard input (notice ./login.php) and is retrieved by login.php by $_POST['username'] and $_POST['password'].
POST is assumed more secure and we can send lot more data than that of GET method is limited (they say Internet Explorer can take care of maximum 2083 character as a query string).
Anwser 4:
In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc. In the post method the data will be available as data blocks and not as query string in case of get method.
Anwser 5:
When we submit a form, which has the GET method it pass value in the form of query string (set of name/value pair) and display along with URL. With GET we can a small data submit from the form (a set of 255 character) whereas Post method doesn’t display value with URL. It passes value in the form of Object and we can submit large data from the form.
Anwser 6:
On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.
On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.
GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.
How do you call a constructor for a parent class?
parent::constructor($value)
WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP?
Here are three basic types of runtime errors in PHP:
1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although you can change this default behavior.
2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.
Internally, these variations are represented by twelve different error types
What’s the special meaning of __sleep and __wakeup?
__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.
How can we submit a form without a submit button?
If you don’t want to use the Submit button to submit a form, you can use normal hyper links to submit a form. But you need to use some JavaScript code in the URL of the link. For example:
<a href=”javascript: document.myform.submit();”>Submit Me</a>
Why doesn’t the following code print the newline properly? <?php $str = ‘Hello, there.\nHow are you?\nThanks for visiting fyicenter’; print $str; ?>
Because inside the single quotes the \n character is not interpreted as newline, just as a sequence of two characters – \ and n.
Would you initialize your strings with single quotes or double quotes?
Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.
How can we extract string ‘abc.com ‘ from a string http://info@abc.com using regular expression of php?
We can use the preg_match() function with "/.*@(.*)$/" as
the regular expression pattern. For example:
preg_match("/.*@(.*)$/","http://info@abc.com",$data);
echo $data[1];
What is the difference between the functions unlink and unset?
unlink() is a function for file system handling. It will simply delete the file in context.
unset() is a function for variable management. It will make a variable undefined.
How come the code works, but doesn’t for two-dimensional array of mine?
Any time you have an array with more than one dimension, complex parsing syntax is required. print “Contents: {$arr[1][2]}” would’ve worked.
How can we register the variables into a session?
session_register($session_var);
$_SESSION['var'] = ‘value’;
What is the difference between characters 23 and \x23?
The first one is octal 23, the second is hex 23.
How can we submit form without a submit button?
We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form. For example: <input type=button value=”Save” onClick=”document.form.submit()”>
How can we create a database using PHP and mysql?
We can create MySQL database with the use of mysql_create_db($databaseName) to create a database.
How many ways we can retrieve the date in result set of mysql using php?
As individual objects so single record or as a set or arrays.
Can we use include (”abc.php”) two times in a php page “makeit.php”?
Yes.
For printing out strings, there are echo, print and printf. Explain the differences.
echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:
<?php echo ‘Welcome ‘, ‘to’, ‘ ‘, ‘fyicenter!’; ?>
and it will output the string “Welcome to fyicenter!” print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.
I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP?
On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().
What’s the output of the ucwords function in this example?
$formatted = ucwords(”FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS”);
print $formatted;
What will be printed is FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS.
ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first.
What’s the difference between htmlentities() and htmlspecialchars()?
htmlspecialchars only takes care of <, >, single quote ‘, double quote ” and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.
How can we extract string “abc.com” from a string “mailto:info@abc.com?subject=Feedback” using regular expression of PHP?
$text = “mailto:info@abc.com?subject=Feedback”;
preg_match(’|.*@([^?]*)|’, $text, $output);
echo $output[1];
Note that the second index of $output, $output[1], gives the match, not the first one, $output[0].
So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()?
Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.
How can we destroy the session, how can we unset the variable of a session?
session_unregister() – Unregister a global variable from the current session
session_unset() – Free all session variables
What are the different functions in sorting an array?
Sorting functions in PHP:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()
How can we know the count/number of elements of an array?
2 ways:
a) sizeof($array) – This function is an alias of count()
b) count($urarray) – This function returns the number of elements in an array.
Interestingly if you just pass a simple var instead of an array, count() will return 1.
How many ways we can pass the variable through the navigation between the pages?
At least 3 ways:
1. Put the variable into session in the first page, and get it back from session in the next page.
2. Put the variable into cookie in the first page, and get it back from the cookie in the next page.
3. Put the variable into a hidden form field, and get it back from the form in the next page.
What is the maximum length of a table name, a database name, or a field name in MySQL?
Database name: 64 characters
Table name: 64 characters
Column name: 64 characters
How many values can the SET function of MySQL take?
MySQL SET function 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 a table using MySQL commands except EXPLAIN command?
DESCRIBE table_name;
How can we find the number of rows in a table using MySQL?
Use this for MySQL
SELECT COUNT(*) FROM table_name;
What’s the difference between md5(), crc32() and sha1() crypto on PHP?
The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.
How can we find the number of rows in a result set using PHP?
Here is how can you find the number of rows in a result set in PHP:
$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();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();
Give the syntax of GRANT commands?
The generic syntax for GRANT is as following
GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password]
Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.
We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.
Give the syntax of REVOKE commands?
The generic syntax for revoke is as following
REVOKE [rights] on [database] FROM [username@hostname]
Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.
We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.
Answer the questions with the following assumption
The structure of table view buyers is as follows:
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| user_pri_id | int(15)     |      | PRI | NULL    | auto_increment |
| userid      | varchar(10) | YES  |     | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+
The value of user_pri_id of the last row is 2345. What will happen in the following conditions?
Condition 1: Delete all the rows and insert another row. What is the starting value for this auto incremented field user_pri_id?
Condition 2: Delete the last row (having the field value 2345) and insert another row. What is the value for this auto incremented field user_pri_id?
In both conditions, the value of this auto incremented field user_pri_id is 2346.
What is the difference between CHAR and VARCHAR data types?
CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, “Hello!” will be stored as “Hello! ” in CHAR(10) column.
VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, “Hello!” will be stored as “Hello!” in VARCHAR(10) column.
How can we encrypt and decrypt a data present in a mysql table using mysql?
AES_ENCRYPT() and AES_DECRYPT()
Will comparison of string “10″ and integer 11 work in PHP?
Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.
What is the functionality of MD5 function in PHP?
string md5(string)
It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number.
How can I load data from a text file into a table?
The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that:
a) Data must be delimited
b) Data fields must match table columns correctly
How can we know the number of days between two given dates using MySQL?
Use DATEDIFF()
SELECT DATEDIFF(NOW(),’2006-07-01′);
How can we change the name of a column of a table?
This will change the name of column:
ALTER TABLE table_name CHANGE old_colm_name new_colm_name
How can we change the data type of a column of a table?
This will change the data type of a column:
ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]
What is the difference between GROUP BY and ORDER BY in SQL?
To sort a result, use an ORDER BY clause.
The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any).
ORDER BY [col1],[col2],…[coln]; Tells 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]; Tells DBMS to group (aggregate) 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 meant by MIME?
Answer 1:
MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail. However browsers also uses MIME standard to transmit files. MIME has a header which is added to a beginning of the data. When browser sees such header it shows the data as it would be a file (for example image)
Some examples of MIME types:
audio/x-ms-wmp
image/png
aplication/x-shockwave-flash
Answer 2:
Multipurpose Internet Mail Extensions.
WWW’s ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types. …
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()?
Answer 1:
mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array.
mysql_fetch_object() -> Fetch a result row as an object.
mysql_fetch_row() -> Fetch a result set as a regular array().
Answer 2:
The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row[0], $row[1], etc.), while the latter returns a the results an array containing both numeric and associative keys ($row['name'], $row['email'], etc.). mysql_fetch_object() returns an object ($row->name, $row->email, etc.).
If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? 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 you recreate connection, then session will continue in the browser.
What are the MySQL database files stored in system ?
Data is stored in name.myd
Table structure is stored in name.frm
Index is stored in name.myi
What is the difference between PHP4 and PHP5?
PHP4 cannot support oops concepts and Zend engine 1 is used.
PHP5 supports oops concepts and Zend engine 2 is used.
Error supporting is increased in PHP5.
XML and SQLLite will is increased in PHP5.
Can we use include(abc.PHP) two times in a PHP page makeit.PHP”?
Yes we can include that many times we want, but here are some things to make sure of:
(including abc.PHP, the file names are case-sensitive)
there shouldn’t be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php
What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
mysql_fetch_array – Fetch a result row as an associative array and a numeric array.
mysql_fetch_object – Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
mysql_fetch_row() – Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
What is meant by nl2br()?
Anwser1:
nl2br() inserts a HTML tag <br> before all new line characters \n in a string.
echo nl2br(”god bless \n you”);
output:
god bless<br>
you
How can we encrypt and decrypt a data presented in a table using MySQL?
You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:
AES_ENCRYPT(str, key_str)
AES_DECRYPT(crypt_str, key_str)
How can I retrieve values from one database server and store them in other database server using PHP?
For this purpose, you can first read the data from one server into session variables. Then connect to other server and simply insert the data into the database.
WHO IS THE FATHER OF PHP AND WHAT IS THE CURRENT VERSION OF PHP AND MYSQL?
Rasmus Lerdorf.
PHP 5.1. Beta
MySQL 5.0
IN HOW MANY WAYS WE CAN RETRIEVE DATA IN THE RESULT SET OF MYSQL USING PHP?
mysql_fetch_array – Fetch a result row as an associative array, a numeric array, or both
mysql_fetch_assoc – Fetch a result row as an associative array
mysql_fetch_object – Fetch a result row as an object
mysql_fetch_row —- Get a result row as an enumerated array
What are the functions for IMAP?
imap_body – Read the message body
imap_check – Check current mailbox
imap_delete – Mark a message for deletion from current mailbox
imap_mail – Send an email message
What are encryption functions in PHP?
CRYPT()
MD5()
What is the difference between htmlentities() and htmlspecialchars()?
htmlspecialchars() – Convert some special characters to HTML entities (Only the most widely used)
htmlentities() – Convert ALL special characters to HTML entities
What is the functionality of the function htmlentities?
htmlentities() – Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
How can we get the properties (size, type, width, height) of an image using php image functions?
To know the image size use getimagesize() function
To know the image width use imagesx() function
To know the image height use imagesy() function
How can we increase the execution time of a php script?
By the use of void set_time_limit(int seconds)
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.
HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE RESTORE IT?
Answer 1:
Create a full backup of your database: shell> mysqldump tab=/path/to/some/dir opt db_name
Or: shell> mysqlhotcopy db_name /path/to/some/dir
The full backup file is just a set of SQL statements, so restoring it is very easy:
shell> mysql “.”Executed”;
Answer 2:
To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory
’ To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory
mysqldump: Dumping Table Structure and Data
Utility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table.
-t, no-create-info
Don’t write table creation information (the CREATE TABLE statement).
-d, no-data
Don’t write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!
How to set cookies?
setcookie(’variable’,’value’,’time’)
;
variable – name of the cookie variable
value – value of the cookie variable
time – expiry time
Example: setcookie(’Test’,$i,time()+3600);
Test – cookie variable name
$i – value of the variable ‘Test’
time()+3600 – denotes that the cookie will expire after an one hour
How to reset/destroy a cookie
Reset a cookie by specifying expire time in the past:
Example: setcookie(’Test’,$i,time()-3600); // already expired time
Reset a cookie by specifying its name only
Example: setcookie(’Test’);
WHAT TYPES OF IMAGES THAT PHP SUPPORTS?
Using imagetypes() function to find out what types of images are supported in your PHP engine.
imagetypes() – Returns the image types supported.
This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM.
CHECK IF A VARIABLE IS AN INTEGER IN JAVASCRIPT
var myValue =9.8;
if(parseInt(myValue)== myValue)
alert(’Integer’);
else
alert(’Not an integer’);
Tools used for drawing ER diagrams.
Case Studio
Smart Draw
How can I know that a variable is a number or not using a JavaScript?
Answer 1:
bool is_numeric( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.
Answer 2:
Definition and Usage
The isNaN() function is used to check if a value is not a number.
Syntax
isNaN(number)
Parameter Description
number Required. The value to be tested
How can we submit from without a submit button?
Trigger the JavaScript code on any event ( like onSelect of drop down list box, onfocus, etc ) document.myform.submit(); This will submit the form.
How many ways can we get the value of current session id?
session_id() returns the session id for the current session.
How can we destroy the cookie?
Set the cookie with a past expiration time.
What are the current versions of Apache, PHP, and MySQL?
PHP: PHP 5.1.2
MySQL: MySQL 5.1
Apache: Apache 2.1
What are the reasons for selecting LAMP (Linux, Apache, MySQL, Php) instead of combination of other software programs, servers and operating systems?
All of those are open source resource. Security of linux is very very more than windows. Apache is a better server that IIS both in functionality and security. Mysql is world most popular open source database. Php is more faster that asp or any other scripting language.
What are the features and advantages of OBJECT ORIENTED PROGRAMMING?
One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system.
What is the use of friend function?
Friend functions
Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class.
A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.
class mylinkage
{
private:
mylinkage * prev;
mylinkage * next;
protected:
friend void set_prev(mylinkage* L, mylinkage* N);
void set_next(mylinkage* L);
public:
mylinkage * succ();
mylinkage * pred();
mylinkage();
};
void mylinkage::set_next(mylinkage* L) { next = L; }
void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }
Friends in other classes
It is possible to specify a member function of another class as a friend as follows:
class C
{
friend int B::f1();
};
class B
{
int f1();
};
It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.
class A
{
friend class B;
};
Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading.
How can we get second of the current time using date function?
$second = date(”s”);
What is the maximum size of a file that can be uploaded using PHP and how can we change this?
You can change maximum size of a file set upload_max_filesize variable in php.ini file
How can I make a script that can be bilingual (supports English, German)?
You can change charset variable in above line in the script to support bilanguage.
What are the difference between abstract class and interface?
Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.
Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.
What are the advantages of stored procedures, triggers, indexes?
A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.
CREATE PROCEDURE simpleproc (OUT param1 INT)
-> BEGIN
-> SELECT COUNT(*) INTO param1 FROM t;
-> END//
CALL sp_name([parameter[,...]])
CALL sp_name[()]
The CALL statement invokes a stored procedure that was defined previously
Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.
CREATE
[DEFINER = { user | CURRENT_USER }]
TRIGGER trigger_name trigger_time trigger_event
ON tbl_name FOR EACH ROW trigger_body
mysql> delimiter //
mysql> CREATE TRIGGER ins_trig BEFORE INSERT ON Emp
-> FOR EACH ROW
-> BEGIN
-> UPDATE Employee SET Salary=Salary-300 WHERE Perks>500;
-> END;
-> //
The general syntax of DROP TRIGGER is :
DROP TRIGGER trigger_name
Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.
CREATE TABLE employee_records (
name VARCHAR(50),
employeeID INT, INDEX (employeeID)
)
CREATE INDEX id_index ON employee_records2(employeeID)
What is MYSQL Injection?
SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.
What is maximum size of a database in mysql?
If the operating system or filesystem places a limit on the number of files in a directory, MySQL is bound by that constraint. The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory increases significantly as the number of files increases, database performance can be adversely affected.
The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes (2567 – 1 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.
The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB.
The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation specific to your operating system.
Operating System File-size Limit
Linux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB
Explain normalization concept?
The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).
First Normal Form
The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic).
Second Normal Form
Where the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.
Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key, but dependant on another value in the table
What’s the difference between accessing a class method via -> and via ::?
:: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.
What are the advantages and disadvantages of CASCADE STYLE SHEETS?
External Style Sheets
Advantages
Can control styles for multiple documents at once Classes can be created for use on multiple HTML element types in many documents Selector and grouping methods can be used to apply styles under complex contexts
Disadvantages
An extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities of style definitions
Embedded Style Sheets
Advantages
Classes can be created for use on multiple tag types in the document Selector and grouping methods can be used to apply styles under complex contexts No additional downloads necessary to receive style information
Disadvantage
This method can not control styles for multiple documents at once
Inline Styles
Advantages
Useful for small quantities of style definitions Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods
Disadvantages
Does not distance style information from content (a main goal of SGML/HTML) Can not control styles for multiple documents at once Author can not create or control classes of elements to control multiple element types within the document Selector grouping methods can not be used to create complex element addressing scenarios
What type of inheritance that php supports?
In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword ‘extends’.
How can increase the performance of MySQL select query?
We can use LIMIT to stop MySql for further search in table after we have received our required no. of records, also we can use LEFT JOIN or RIGHT JOIN instead of full join in cases we have related data in two or more tables.
How can we change the name of a column of a table?
MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_name
or,
ALTER TABLE tableName CHANGE OldName newName.
When you want to show some part of a text displayed on an HTML page in red font color? What different possibilities are there to do this? What are the advantages/disadvantages of these methods?
There are 2 ways to show some part of a text in red:
1. Using HTML tag <font color=”red”>
2. Using HTML tag <span style=”color: red”>
When viewing an HTML page in a Browser, the Browser often keeps this page in its cache. What can be possible advantages/disadvantages of page caching? How can you prevent caching of a certain page (please give several alternate solutions)?
When you use the metatag in the header section at the beginning of an HTML Web page, the Web page may still be cached in the Temporary Internet Files folder.
A page that Internet Explorer is browsing is not cached until half of the 64 KB buffer is filled. Usually, metatags are inserted in the header section of an HTML document, which appears at the beginning of the document. When the HTML code is parsed, it is read from top to bottom. When the metatag is read, Internet Explorer looks for the existence of the page in cache at that exact moment. If it is there, it is removed. To properly prevent the Web page from appearing in the cache, place another header section at the end of the HTML document. For example:
What are the different ways to login to a remote server? Explain the means, advantages and disadvantages?
There is at least 3 ways to logon to a remote server:
Use ssh or telnet if you concern with security
You can also use rlogin to logon to a remote server.
Please give a regular expression (preferably Perl/PREG style), which can be used to identify the URL from within a HTML link tag.
Try this: /href=”([^"]*)”/i
How can I use the COM components in php?
The COM class provides a framework to integrate (D)COM components into your PHP scripts.
string COM::COM( string module_name [, string server_name [, int codepage]]) – COM class constructor.
Parameters:
module_name: name or class-id of the requested component.
server_name: name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com, allow_dcom has to be set to TRUE in php.ini.
codepage – specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.
Usage:
$word->Visible = 1; //open an empty document
$word->Documents->Add(); //do some weird stuff
$word->Selection->TypeText(”This is a test…”);
$word->Documents[1]->SaveAs(”Useless test.doc”); //closing word
$word->Quit(); //free the object
$word->Release();
$word = null;
How many ways we can give the output to a browser?
HTML output
PHP, ASP, JSP, Servlet Function
Script Language output Function
Different Type of embedded Package to output to a browser
What is the default session time in php and how can I change it?
The default session time in php is until closing of browser
What changes I have to do in php.ini file for file uploading?
Make the following line uncomment like:
; Whether to allow HTTP file uploads.
file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = C:\apache2triad\temp
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M
How can I set a cron and how can I execute it in Unix, Linux, and windows?
Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals. In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from which we get the word chronology, which means order of time.
The easiest way to use crontab is via the crontab command.
# crontab
This command ‘edits’ the crontab. Upon employing this command, you will be able to enter the commands that you wish to run. My version of
Linux uses the text editor vi. You can find information on using vi here.
The syntax of this file is very important – if you get it wrong, your crontab will not function properly. The syntax of the file should be as follows:
minutes hours day_of_month month day_of_week command
All the variables, with the exception of the command itself, are numerical constants. In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each field are as follows:
Minutes: 0-59
Hours: 0-23
Day_of_month: 1-31
Month: 1-12
Weekday: 0-6
We can also include multiple values for each entry, simply by separating each value with a comma.
command can be any shell command and, as we will see momentarily, can also be used to execute a Web document such as a PHP file.
So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will contain the following content on a single line:
15 8 * * 2 /path/to/scriptname
This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will happen (barring very special configurations that have PHP compiled as an executable, as opposed to an Apache module). The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other words, the page needs to be called via a browser or other means of retrieving
Web content. For our purposes, I’ll assume that your server configuration includes wget, as is the case with most default configurations. To test your configuration, log in to shell. If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following:
# wget help
If you are greeted with a wget package identification, it is installed in your system.
You could execute the PHP by invoking wget on the URL to the page, like so:
# wget http://www.example.com/file.php
Now, let’s go back to the mailstock.php file we created in the first part of this article. We saved it in our document root, so it should be accessible via the Internet. Remember that we wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might have to compensate for the time difference when setting this value.
This is what my crontab will look like:
0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php
Steps for the payment gateway processing?
An online payment gateway is the interface between your merchant account and your Web site. The online payment gateway allows you to immediately verify credit card transactions and authorize funds on a customer’s credit card directly from your Web site. It then passes the transaction off to your merchant bank for processing, commonly referred to as transaction batching
How many ways I can redirect a PHP page?
Here are the possible ways of php page redirection.
1. Using Java script:
‘; echo ‘window.location.href=”‘.$filename.’”;’; echo ”; echo ”; echo ”; echo ”; } } redirect(’http://maosjb.com’); ?>
2. Using php function: header(”Location:http://maosjb.com “);
List out different arguments in PHP header function?
void header ( string string [, bool replace [, int http_response_code]])
What type of headers have to be added in the mail function to attach a file?
$boundary = ‘–’ . md5( uniqid ( rand() ) );
$headers = “From: \”Me\”\n”;
$headers .= “MIME-Version: 1.0\n”;
$headers .= “Content-Type: multipart/mixed; boundary=\”$boundary\””;
How to store the uploaded file to the final location?
move_uploaded_file ( string filename, string destination)
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.
What is the difference between Reply-to and Return-path in the headers of a mail function?
Reply-to: Reply-to is where to delivery the reply of the mail.
Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.
Explain about Type Juggling in php?
PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.
An example of PHP’s automatic type conversion is the addition operator ‘+’. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.
$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
$foo = 5 + “10 Little Piggies”; // $foo is integer (15)
$foo = 5 + “10 Small Pigs”; // $foo is integer (15)
If the last two examples above seem odd, see String conversion to numbers.
If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can use the var_dump() function.
Note: The behavior of an automatic conversion to array is currently undefined.
Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being “f”, or should “f” become the first character of the string $a? The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes “f”, the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:
How can I embed a java programme in php file and what changes have to be done in php.ini file?
There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.
The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.
Example Code:
getProperty(’java.version’) . ”; echo ‘Java vendor=’ . $system->getProperty(’java.vendor’) . ”; echo ‘OS=’ . $system->getProperty(’os.name’) . ‘ ‘ . $system->getProperty(’os.version’) . ‘ on ‘ . $system->getProperty(’os.arch’) . ‘ ‘; // java.util.Date example $formatter = new Java(’java.text.SimpleDateFormat’, “EEEE, MMMM dd, yyyy ‘at’ h:mm:ss a zzzz”); echo $formatter->format(new Java(’java.util.Date’)); ?>
The behaviour of these functions is affected by settings in php.ini.
Table 1. Java configuration options
Name
Default
Changeable
java.class.path
NULL
PHP_INI_ALL
Name Default Changeable
java.home
NULL
PHP_INI_ALL
java.library.path
NULL
PHP_INI_ALL
java.library
JAVALIB
PHP_INI_ALL
How To Turn On the Session Support?
The session support can be turned on automatically at the site level, or manually in each PHP page script:
  • Turning on session support automatically at the site level: Set session.auto_start = 1 in php.ini.
  • Turning on session support manually in each page script: Call session_start() funtion.
Explain the ternary conditional operator in PHP?
Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.
What’s the difference between include and require?
It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
How many ways can we get the value of current session id?
session_id() returns the session id for the current session.
How can we destroy the cookie?
Set the cookie in past.
How To Read the Entire File into a Single String?
If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It opens the specified file, reads all characters in the file, and returns them in a single string. Here is a PHP script example on how to file_get_contents():
<?php
$file = file_get_contents(”/windows/system32/drivers/etc/services”);
print(”Size of the file: “.strlen($file).”\n”);
?>
This script will print:
Size of the file: 7116
1.    How do you start and stop MySQL on Windows? – net start MySQL, net stop MySQL
2.    How do you start MySQL on Linux? – /etc/init.d/mysql start
3.    Explain the difference between mysql and mysqli interfaces in PHP? – mysqli is the object-oriented version of mysql library functions.
4.    What’s the default port for MySQL Server? – 3306
5.    What does tee command do in MySQL? – tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command notee.
6.    Can you save your connection settings to a conf file? – Yes, and name it ~/.my.conf. You might want to change the permissions on the file to 600, so that it’s not readable by others.
7.    How do you change a password for an existing user via mysqladmin? – mysqladmin -u root -p password “newpassword”
8.    Use mysqldump to create a copy of the database? – mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
9.    Have you ever used MySQL Administrator and MySQL Query Browser? Describe the tasks you accomplished with these tools.
10.    What are some good ideas regarding user security in MySQL? – There is no user without a password. There is no user without a user name. There is no user whose Host column contains % (which here indicates that the user can log in from anywhere in the network or the Internet). There are as few users as possible (in the ideal case only root) who have unrestricted access.
11.    Explain the difference between MyISAM Static and MyISAM Dynamic. – In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.
12.    What does myisamchk do? – It compressed the MyISAM tables, which reduces their disk usage.
13.    Explain advantages of InnoDB over MyISAM? – Row-level locking, transactions, foreign key constraints and crash recovery.
14.    Explain advantages of MyISAM over InnoDB? – Much more conservative approach to disk space management – each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity.
15.    What are HEAP tables in MySQL? – HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and <=>. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.
16.    How do you control the max size of a HEAP table? – MySQL config variable max_heap_table_size.
17.    What are CSV tables? – Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.
18.    Explain federated tables. – Introduced in MySQL 5.0, federated tables allow access to the tables located on other databases on other servers.
19.    What is SERIAL data type in MySQL? – BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
20.    What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table? – It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
21.    Explain the difference between BOOL, TINYINT and BIT. – Prior to MySQL 5.0.3: those are all synonyms. After MySQL 5.0.3: BIT data type can store 8 bytes of data and should be used for binary data.
22.    Explain the difference between FLOAT, DOUBLE and REAL. – FLOATs store floating point numbers with 8 place accuracy and take up 4 bytes. DOUBLEs store floating point numbers with 16 place accuracy and take up 8 bytes. REAL is a synonym of FLOAT for now.
23.    If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this table? – 999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits.
24.    What happens if a table has one column defined as TIMESTAMP? – That field gets the current timestamp whenever the row gets altered.
25.    But what if you really want to store the timestamp data, such as the publication date of the article? – Create two columns of type TIMESTAMP and use the second one for your real data.
26.    Explain data type TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP – The column exhibits the same behavior as a single timestamp column in a table with no other timestamp columns.
27.    What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do? – On initialization places a zero in that column, on future updates puts the current value of the timestamp in.
28.    Explain TIMESTAMP DEFAULT ‘2006:09:02 17:38:44′ ON UPDATE CURRENT_TIMESTAMP. – A default value is used on initialization, a current timestamp is inserted on update of the row.
29.    If I created a column with data type VARCHAR(3), what would I expect to see in MySQL table? – CHAR(3), since MySQL automatically adjusted the data type.
Q 1- How to setup admin user for MYSQL ?
Ans:
Login as super user ‘root’ in mysql and execute the following commands.
mysql> use mysql;
mysql> create user ‘test’@’%’ identified by ‘test’;
mysql> grant all on *.* to ‘test’@’%’ with grant option;
mysql> flush privileges;
Q 2- What types of privileges are there in MySQL ?
Ans:
There are 4 types of privileges.
i). Global privileges like *.* (all hosts connecting to Mysql db server)
Example: GRANT SELECT, INSERT ON *.* TO ‘someuser’@’somehost’;
ii). Database privileges like .*
Example: GRANT SELECT, INSERT ON mydb.* TO ‘someuser’@’somehost’;
iii). Table privileges like SELECT, INSERT, UPDATE, DELETE
Example: GRANT SELECT, INSERT ON mydb.mytbl TO ‘someuser’@’somehost’;
iv). Column privileges like
Example: GRANT SELECT (col1), INSERT (col1,col2) ON mydb.mytbl TO ‘someuser’@’somehost’;
Q 3- How to find the version of MySQL ?
Ans:
mysql> select version();
Q 4- How do I limit the number of rows I get out of my database?
Ans:
SELECT name FROM table LIMIT [, ] ;
if you want to get the rows between 10 and 20 do the following:
SELECT name FROM table LIMIT 10, 20 ;
Q 5- Is it possible to insert multiple rows using single command in MySQL ?
Ans:
Yes. Please see below example.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9) ;
Q 6- I am getting the following error while logging into “mytest” database.
ERROR 1044 (42000): Access denied for user ‘phpzag’@’localhost’ to database ‘mytest’.
Ans:
Please refer the error to DBA asking for granting the privilege to “mytest” database.
mysql > grant all on test.* to ‘user_name’ @ ‘host_name’ ;
Q 7- What is null value in MySQL ?
Ans:
In MySQL NULL is only equal to NULL, but NULL is not equal to ‘ ‘ ( blank value ) or 0(zero).
Q 8- How can I check if a table in MySQL database already exists?
Ans:
Command : SHOW TABLES LIKE ‘%’;
Q 8- Convert datetime from MST (db servers timezone) into GMT returns NULL value, how to solve it?
Ans:
Database should be updated with timezone value from OS otherwise Mysq
1.    What is DDL, DML and DCL? – If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system.
2.    How do you get the number of rows affected by query? – SELECT COUNT (user_id) FROM users would only return the number of user_id’s.
3.    If the value in the column is repeatable, how do you find out the unique values? – Use DISTINCT in the query, such as SELECT DISTINCT user_firstname FROM users; You can also ask for a number of distinct values by saying SELECT COUNT (DISTINCT user_firstname) FROM users;
4.    How do you return the a hundred books starting from 25th? – SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.
5.    You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user? – SELECT SQL_CALC_FOUND_ROWS page_title FROM web_pages LIMIT 1,10; SELECT FOUND_ROWS(); The second query (not that COUNT() is never used) will tell you how many results there’re total, so you can display a phrase “Found 13,450,600 results, displaying 1-10″. Note that FOUND_ROWS does not pay attention to the LIMITs you specified and always returns the total number of rows affected by query.
6.    How would you write a query to select all teams that won either 2, 4, 6 or 8 games? – SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8)
7.    How would you select all the users, whose phone number is null? – SELECT user_name FROM users WHERE ISNULL(user_phonenumber);
8.    What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) – It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id
9.    How do you find out which auto increment was assigned on the last insert? – SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
10.    What does –i-am-a-dummy flag to do when starting MySQL? – Makes the MySQL  engine refuse UPDATE and DELETE commands where the WHERE clause is not present.
11.    On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do? – What it means is that so of the data that you’re trying to delete is still alive in another table. Like if you have a table for universities and a table for students, which contains the ID of the university they go to, running a delete on a university table will fail if the students table still contains people enrolled at that university. Proper way to do it would be to delete the offending data first, and then delete the university in question. Quick way would involve running SET foreign_key_checks=0 before the DELETE command, and setting the parameter back to 1 after the DELETE is done. If your foreign key was formulated with ON DELETE CASCADE, the data in dependent tables will be removed automatically.
12.    When would you use ORDER BY in DELETE statement? – When you’re not deleting by row ID. Such as in DELETE FROM techinterviews_com_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table techinterviews_com_questions.
13.    How can you see all indexes defined for a table? – SHOW INDEX FROM techinterviews_questions;
14.    How would you change a column from VARCHAR(10) to VARCHAR(50)? – ALTER TABLE techinterviews_questions CHANGE techinterviews_content techinterviews_CONTENT VARCHAR(50).
15.    How would you delete a column? – ALTER TABLE techinterviews_answers DROP answer_user_id.
16.    How would you change a table to InnoDB? – ALTER TABLE techinterviews_questions ENGINE innodb;
17.    When you create a table, and then run SHOW CREATE TABLE on it, you occasionally get different results than what you typed in. What does MySQL modify in your newly created tables? -
1.    VARCHARs with length less than 4 become CHARs
2.    CHARs with length more than 3 become VARCHARs.
3.    NOT NULL gets added to the columns declared as PRIMARY KEYs
4.    Default values such as NULL are specified for each column
18.    How do I find out all databases starting with ‘tech’ to which I have access to? – SHOW DATABASES LIKE ‘tech%’;
19.    How do you concatenate strings in MySQL? – CONCAT (string1, string2, string3)
20.    How do you get a portion of a string? – SELECT SUBSTR(title, 1, 10) from techinterviews_questions;
21.    What’s the difference between CHAR_LENGTH and LENGTH? – The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.
22.    How do you convert a string to UTF-8? – SELECT (techinterviews_question USING utf8);
23.    What do % and _ mean inside LIKE statement? – % corresponds to 0 or more characters, _ is exactly one character.
24.    What does + mean in REGEXP? – At least one character. Appendix G. Regular Expressions from MySQL manual is worth perusing before the interview.
25.    How do you get the month from a timestamp? – SELECT MONTH(techinterviews_timestamp) from techinterviews_questions;
26.    How do you offload the time/date handling to MySQL? – SELECT DATE_FORMAT(techinterviews_timestamp, ‘%Y-%m-%d’) from techinterviews_questions; A similar TIME_FORMAT function deals with time.
27.    How do you add three minutes to a date? – ADDDATE(techinterviews_publication_date, INTERVAL 3 MINUTE)
28.    What’s the difference between Unix timestamps and MySQL timestamps? – Internally Unix timestamps are stored as 32-bit integers, while MySQL timestamps are stored in a similar manner, but represented in readable YYYY-MM-DD HH:MM:SS format.
29.    How do you convert between Unix timestamps and MySQL timestamps? – UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp, FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp.
30.    What are ENUMs used for in MySQL? – You can limit the possible values that go into the table. CREATE TABLE months (month ENUM ‘January’, ‘February’, ‘March’,…); INSERT months VALUES (’April’);
31.    How are ENUMs and SETs represented internally? – As unique integers representing the powers of two, due to storage optimizations.
Content
•    Search with special characters
•    Why is InnoDB disabled?
•    How to find MySQL system information?
•    What is the difference between MySQL certified server and community server?
•    MySQL monitoring
•    MySQL backup
•    Corrupt MyISAM table
•    How to compile MySQL
•    Test restore procedure
•    Reset a MySQL user password
•    Reset the MySQL root user password
•    How to enable the InnoDB plug-in
•    Storage Engines shipped with MariaDB / MySQL
•    Compiling MySQL Cluster ndb-test fails
•    NDB information schema does not show up
•    Hyper Threading (HT) enabled?
•    How to make a patch for MariaDB?
•    Where does the InnoDB AUTO-INC waiting come from?
•    My character encoding seems to be wrong. How can I fix it?
•    I think my Slave is not consistent to its Master anymore. How can I check this?
•    My MySQL Server is swapping from time to time. This gives hick-ups in MySQL. How can I avoid this?
Search with special characters
Question: How can I search the following string in a text field: ‘%newline,tabluator,b)%’?
Answer:
CREATE TABLE spec(txt VARCHAR(255));
INSERT INTO spec values (‘bla\tbla\nbla’);
INSERT INTO spec values (‘\n\tb)’);
INSERT INTO spec values (‘abc\n\tb)xyz’);
SELECT * FROM spec;
SELECT * FROM spec WHERE txt LIKE ‘\n\tb)’;
SELECT * FROM spec WHERE txt LIKE ‘%\n\tb)%’;
SELECT * FROM spec WHERE txt REGEXP ‘^\n\tb)$’;
SELECT * FROM spec WHERE txt REGEXP ‘\n\tb)’;
Why is InnoDB disabled?
Question: After reconfiguring the my.conf InnoDB was disabled. Why?
Answer: This can happen when the InnoDB logfile size (innodb_log_file_size) was set to an new value which is not compatible with the old value.
To avoid this problem shut-down MySQL properly (mysqladmin –user=root shutdown). Then backup and after remove the logfiles, configure the my.cnf with the new logfile size. Start MySQL again and check the error.log.
How to find MySQL system information?
Question: How can I find MySQL stytem information?
Answer:
Operating System
Linux:
$ uname -a
$ cat /etc/SuSE-release
$ cat /proc/version
MySQL libraries
$ ldconfig -p | grep -i mysql
MySQL client
$ mysql –version
MySQL server
mysql> STATUS;
mysql> SELECT VERSION();
mysql> SHOW VARIABLES LIKE ‘version%’;
$ mysqladmin version -p
MySQL Table versions
SELECT table_schema, table_name, engine, version, row_format
FROM information_schema.tables
WHERE table_type = ‘BASE TABLE’
ORDER BY table_schema, table_name
;
What is the difference between MySQL certified server and community server?
Question: What is the difference between MySQL certified server and community server?
Answer:
MySQL certified server    MySQL community server
•    Chosen software by MySQL
•    Based on internal quality/feature completeness    •    Serves as base for Certified Server
•    New MySQL Forge helps get contributions!
•    Profits from community testing
•    Receives additional internal/external testing    •    Receives community and basic internal testing
•    Contains no untested/certified feature    •    May contain features for community testing
•    Infrequent major releases    •    Frequent releases (early and often)
•    Under active development
•    Tiered patch releases (every month to once/qtr)    •    Contains patches plus new features
•    Recommended to partners, ISV’s, Enterprise deployment    •    Not recommended to partners, ISV’s
•    Certified on most popular platforms    •    Offered on over two dozen platforms
•    Formal support through MySQL AB    •    Informal support via forums, etc.
MySQL monitoring
Question: How can I monitor MySQL related system information, status and activities?
Answer: MySQL monitoring solutions
MySQL backup
Question: How to do backup?
Answer:
# for both
cp /etc/my.cnf $BACKUP_DIR/my_$BACKUP_TIMESTAMP.cnf
# for MyISAM
BACKUP_TIMESTAMP=`date ‘+%Y-%m-%d_%H-%M-%S’`
BACKUP_DIR=’/mybackupdir’
mysqldump –user=root –all-databases –flush-privileges –lock-all-tables –master-data=1 –quick \
–flush-logs –triggers –routines –events > $BACKUP_DIR/full_dump_$BACKUP_TIMESTAMP.sql
# for InnoDB
BACKUP_TIMESTAMP=`date ‘+%Y-%m-%d_%H-%M-%S’`
BACKUP_DIR=’/mybackupdir’
mysqldump –user=root –all-databases –flush-privileges –single-transaction –master-data=1 –quick \
–flush-logs –triggers –routines –events > $BACKUP_DIR/full_dump_$BACKUP_TIMESTAMP.sql
* –flush-privileges works since 5.1.12
Caution: If you have a mixed environment (MyISAM AND InnoDB) it becomes a little bit more complicated!
Question: Is LVM snapshot a feasible way to take MySQL/InnoDB backups?
Answer: It depends! If you stop MySQL it should work well. If you have MyISAM tables only, then FLUSH TABLES WITH READ LOCK should guarantee a consistent backup. With InnoDB a LVM snapshot should work as well because it is the same situation as in a sever crash. It becomes a problem when the InnoDB log files are located on a different disk than the data files. FLUSH TABLES WITH READ LOCK is in this situation not sufficient for InnoDB because InnoDB still may write some data in the background which can corrupt your LVM snapshot over 2 devices.
There were some cases reported where MySQL/InnoDB refused to recover from a LVM snapshot backup with core dump:
InnoDB: Progress in percents: 0 1 2 3 mysqld got signal 11;
Innobase never approved LVM snapshots as valid way of taking backups! If these are technical or marketing reasons I do not know.
If you choose LVM snapshot as a backup method we recommend to do a restore-test of the backup and restart the database to see if it recovers successfully. Then you are sure your backup is a valid one.
Literature
[1] MySQL Backups using LVM Snapshots
[2] MySQL Server Backup, Restoration, And Disaster Recovery Planning Presentation
[3] Using LVM for MySQL Backup and Replication Setup
[4] Logical volume management
[5] Backup of MySQL Databases on Logical Volumes
Corrupt MyISAM table
Question: How does a corrupt MyISAM table look like?
Answer: InnoDB tables should not get corrupted at all. MyISAM tables can get courrupted after system failure. You should NEVER run corrupted MyISAM tables. I can even get worse! Do always a check after a crash. How you can find if a table got corrupted and how you can repare it again is shown below:
mysql> CHECK TABLE test;
+———–+——-+———-+——————————————————-+
| Table     | Op    | Msg_type | Msg_text                                              |
+———–+——-+———-+——————————————————-+
| test.test | check | warning  | 1 client is using or hasn’t closed the table properly |
| test.test | check | error    | Key in wrong position at page 3072                    |
| test.test | check | error    | Corrupt                                               |
+———–+——-+———-+——————————————————-+
3 rows in set (0.05 sec)
mysql> SELECT COUNT(*) FROM test;
ERROR 145 (HY000): Table ‘./test/test’ is marked as crashed and should be repaired
mysql> REPAIR TABLE test;
+———–+——–+———-+————————————————–+
| Table     | Op     | Msg_type | Msg_text                                         |
+———–+——–+———-+————————————————–+
| test.test | repair | warning  | Number of rows changed from 11000000 to 10000000 |
| test.test | repair | status   | OK                                               |
+———–+——–+———-+————————————————–+
2 rows in set (29 min 17.80 sec)
061004  9:43:50 [ERROR] /usr/local/bin/mysqld: Table ‘./test/test’ is marked as crashed and
should be repaired
061004 10:13:24 [Note] Found 10000000 of 11000000 rows when repairing ‘./test/test’
How to compile MySQL
Question: How do I compile MySQL on platforms were no binaries are provided?
Answer: Recently we wanted to run MySQL on a 64bit PPC Linux platform. We compiled it as follows:
CC=”gcc” CFLAGS=”-O3 -mpowerpc -m64 -mcpu=powerpc” CXX=”gcc” \
CXXFLAGS=”-O3 -m64 -mpowerpc -mcpu=powerpc” \
./configure –prefix=/app/mysql/5.0.37
make
make install
If you never compiled something on your Linux machine before maybe some necessary tools are missing:
•    gmake
•    autoconf
•    automake
•    libtool
•    m4
•    bison
Further very often there are some header files of standard libraries not installed:
•    libreadline-dev
•    libncurses5-dev
If you install all those it should work…
MySQL Documentation: Installing MySQL from a Standard Source Distribution
Test restore procedure
Question: Why should I regularly test my restore procedure?
Answer: You should test your restore procedure on a regular base to make sure it actually works, when you really need it.
See the following real life examples MySQL users were experiencing:
When I backup the database with the command:
shell> mysqldump –user=root -p –hex-blob –max_allowed_packet=128M -x -t test > test_dump.sql
everything works fine. But when I try to restore the database I get the following error:
mysql –user=root -p –max_allowed_packet=128M test < test_dump.sql
ERROR 1153 (08S01) at line 87: Got a packet bigger than ‘max_allowed_packet’ bytes
In this case you possibly would have found the problem already before you have to do the real emergency restore.
Reset a MySQL user password
Question: How do I reset a Password for a MySQL user?
Answer: For a regular MySQL or MariaDB user you can reset the Password with the SET PASSWORD command:
mysql> SET PASSWORD FOR ‘app_owner’@'%.mysite.com’ = PASSWORD(‘secret’);
Consider, that the user in MySQL always consist of a username AND a domain name.
Literature
[1] SET PASSWORD Syntax
Reset the MySQL root user password
Question: How do I reset the MySQL root user password?
Answer: To reset the MySQL or MariaDB root user password you have 2 possibilities:
1.    Restart the mysqld with an init-file where you reset the root password.
2.    Restart the mysqld with the skip-grant-tables option and then reset the root password.
Possibility one: Restart the mysqld with the init-file parameter:
1.    Create a file with the reset commands in a location where nobody else than the MySQL user has access to:
2.    – reset_root_user_password.sql
3.    UPDATE mysql.user SET password = PASSWORD(‘secret’) WHERE user = ‘root’;
FLUSH PRIVILEGES;
4.    Hook this reset command file into your my.cnf
5.    # my.cnf
6.    [mysqld]
init-file = /home/mysql/secret/reset_root_user_password.sql
7.    Stop or kill mysqld
shell> kill `cat <datadir>/<host_name>.pid`
8.    Verify that mysqld was stopped properly:
shell> pgrep mysqld
9.    Start mysqld
shell> /etc/init.d/mysql start
Now you should be capable to use the new root user password.
10.    Remove the init-file parameter again from the my.cnf and delete the reset_root_user_password.sql script.
This methode requires only one database restart.
Possibility two: Restart the mysqld with the skip-grant-tables parameter:
1.    Add the skip-grant-tables parameter to your my.cnf:
2.    # my.cnf
3.    [mysqld]
skip-grant-tables = 1
4.    Stop or kill mysqld
shell> kill `cat <datadir>/host_name.pid`
5.    Verify that mysqld was stopped properly:
shell> pgrep mysqld
6.    Start mysqld
shell> /etc/init.d/mysql start
7.    Now you can login without any password:
shell> mysql –user=root
8.    Reset the root user password:
9.    mysql> UPDATE mysql.user SET password = PASSWORD(‘secret’) WHERE user = ‘root’;
mysql> FLUSH PRIVILEGES;
10.    Remove the skip-grant-tables parameter from the my.cnf.
11.    Restart the mysqld again to protect its security.
shell> /etc/init.d/mysql restart
This methtode requires for security reasons two database restarts.
You can use both methods with mysqld command options as well.
Literature
[1] How to Reset the Root Password
[2] MySQL Server Command Option init-file
[3] MySQL Server Comand Option skip-grant-tables
How to enable the InnoDB plug-in
Question: How do I enable the InnoDB plug-in?
Answer: You can enable the InnoDB plug-in in 3 different ways:
•    In the MySQL Client with the INSTALL PLUGIN command.
•    When starting the mysqld with command line parameters.
•    In the MySQL configuration file:
# my.cnf
[mysqld]
ignore_builtin_innodb
plugin-load=innodb=ha_innodb_plugin.so;innodb_trx=ha_innodb_plugin.so;innodb_locks=ha_innodb_plugin.so;\
innodb_lock_waits=ha_innodb_plugin.so;innodb_cmp=ha_innodb_plugin.so;innodb_cmp_reset=ha_innodb_plugin.so;\
innodb_cmpmem=ha_innodb_plugin.so;innodb_cmpmem_reset=ha_innodb_plugin.so
Pleased make sure that the plugin-load parameter is a one-liner.
You get the following possibilities:
Distribution    Version    Type    Maker    Version
MySQL    5.0    built-in only    Innobase    ?
MariaDB    5.1    built-in only    Percona    1.0
MySQL    5.1    built-in and plug-in    Innobase    ? / 1.0
MariaDB    5.2    built-in only    Percona    1.0
MySQL    5.5    built-in only    Innobase    1.1
Storage Engines shipped with MariaDB / MySQL
Question: What storage engines do I get with MySQL and MariaDB?
Answer: Depending on the release and the distribution you are using you get different Storage Engines. The details you can find in the following matrix:
mysql> SHOW ENGINES;
MySQL
Engine     5.0     5.1     5.5
ARCHIVE     YES     YES     YES
BerkeleyDB    NO
BLACKHOLE     YES     YES     YES
CSV     YES     YES     YES
EXAMPLE     NO     NO
FEDERATED     YES     NO     NO
InnoDB     YES     YES     DEFAULT
ISAM     NO
MEMORY     YES     YES     YES
MRG_MYISAM    YES     YES     YES
MyISAM     DEFAULT     DEFAULT    YES
ndbcluster    DISABLED    NO
Remarks:
•    From MySQL 5.0 to 5.1 BerkleyDB (BDB) and ISAM Storage Engines were removed and Federated Storage Engine was disabled.
•    In 5.5 it looks like the EXAMPLE and the FEDEREATED Storage Engines are not included any more.
•    With 5.5 InnoDB is the new default Storage Engine.
•    The NDB Storage Engine is not support with MySQL 5.5 yet.
MariaDB
Engine     5.1     5.2     5.3
ARCHIVE     YES     YES     YES
Aria         YES     YES
BLACKHOLE     YES     YES     YES
CSV     YES     YES     YES
EXAMPLE     YES     YES     YES
FEDERATED     YES     YES     YES
InnoDB         YES     YES
MARIA     YES
MEMORY     YES     YES     YES
MRG_MYISAM    YES     YES     YES
MyISAM     DEFAULT    DEFAULT    DEFAULT
OQGRAPH         YES
PBXT     YES     YES     YES
SPHINX         YES     YES
Remarks:
•    In MariaDB 5.1 the FEDERATED Storage Engine is integraded in the form of the FederatedX Storage Engine.
•    InnoDB was not taken into MariaDB 5.1. PBXT acts as a substitue for InnoDB.
•    In MariaDB 5.2 the Maria Storage Engine was renamed into Aria and InnoDB comes back in form of XtraDB.
•    The new OQGraph Storage Engine was added with MariaDB 5.2 as well.
•    OQGraph did not build with MariaDB 5.3.0 any more but it is still included in the source code. So I assume this is a bug of this early alpha release.
For more information about the different Storage Engines available see also MySQL Pluggable Storage Engines
Compiling MySQL Cluster ndb-test fails
Question: When I want to compile flexAsynch I get some odd compiling errors.
Answer: We had a similar problem, when we added one include directive the problem disappeared.
When we compiled MySQL Cluster 7.1.9a as follows:
./configure –with-plugins=max –with-ndb-test ; make -j 4
we got the following error message:
g++ -DHAVE_CONFIG_H -DNDEBUG   -I. -I../../../../include -I../../../../storage/ndb/test/include -I. \
-I../../../../include -I../../../../storage/ndb/include -I../../../../include -I../../../../mysys \
-I../../../../storage/ndb/include -I../../../../storage/ndb/include/util \
-I../../../../storage/ndb/include/portlib -I../../../../storage/ndb/include/logger \
-I../../../../storage/ndb/include/mgmapi -I. -I../../../../include \
-I../../../../storage/ndb/include -I../../../../include -I../../../../storage/ndb/include \
-I../../../../storage/ndb/include/ndbapi -I../../../../storage/ndb/include/util \
-I../../../../storage/ndb/include/portlib -I../../../../storage/ndb/test/include \
-I../../../../storage/ndb/include/mgmapi -I../../../../storage/ndb/include/kernel \
-I../../../../storage/ndb/src/ndbapi -I../../../../storage/ndb/include/debugger \
-I../../../../ndb/src/mgmapi -I../../../../ndb/src/mgmsrv -I../../../../ndb/include/mgmcommon \
-DDEFAULT_PREFIX=”\”/usr/local\”" -O3 -fno-implicit-templates -fno-exceptions -fno-rtti -MT atrt-db.o \
-MD -MP -MF .deps/atrt-db.Tpo -c -o atrt-db.o `test -f ‘db.cpp’ || echo ‘./’`db.cpp
main.cpp: In function ‘bool parse_args(int, char**)’:
main.cpp:560: error: ‘lstat’ was not declared in this scope
main.cpp:741: error: ‘lstat’ was not declared in this scope
main.cpp:749: error: ‘S_ISREG’ was not declared in this scope
560   if (argc > 1 && lstat(argv[argc-1], &sbuf) == 0)
741     if (lstat(tmp.c_str(), &sbuf) != 0)
749     if (!S_ISREG(sbuf.st_mode))
This only happens with the –with-ndb-test directive but NOT without! So we assume, that there must be something wrong in the sources, which does not show up on the developers machines…
By just adding the following line to all failing parts (there were 2 or 3 of them):
#include <sys/stat.h>
it worked out for us.
NDB information schema does not show up
Question: When I start my MySQL 7.1 Cluster the NDB information schema does not show up. What can I do?
Answer: This happens in some cases. The reason is not known to us. Seems something like a bug.
When you look at the log MySQL seems to be aware of the NDB information schema:
110125  9:00:24 [Note] NDB: Creating mysql.ndb_schema
110125  9:00:24 [Note] NDB: Flushing mysql.ndb_schema
110125  9:00:24 [Note] NDB Binlog: CREATE TABLE Event: REPL$mysql/ndb_schema
110125  9:00:24 [Note] NDB Binlog: logging ./mysql/ndb_schema (UPDATED,USE_WRITE)
mysql> SHOW DATABASES;
+——————–+
| Database           |
+——————–+
| information_schema |
| mysql              |
| test               |
+——————–+
As mentioned in Bug #54552 ndbinfo missing although activated after online upgrade a mysql_upgrade will help to solve the problem:
shell> mysql_upgrade
mysql> SHOW PLUGINS;
+————+———-+—————-+———+———+
| Name       | Status   | Type           | Library | License |
+————+———-+—————-+———+———+
| ndbcluster | ACTIVE   | STORAGE ENGINE | NULL    | GPL     |
| ndbinfo    | ACTIVE   | STORAGE ENGINE | NULL    | GPL     |
+————+———-+—————-+———+———+
mysql> SHOW DATABASES;
+——————–+
| Database           |
+——————–+
| information_schema |
| mysql              |
| ndbinfo            |
| test               |
+——————–+
Hyper Threading (HT) enabled?
Question: How can I find if Hyper Threading (HT) is enable on my machine?
Answer: /proc/cpuinfo will tell you if Hyper Threading (HT) is enabled on your machine or not:
# cat /proc/cpuinfo | egrep ‘siblings|cpu cores’ | sort | uniq
cpu cores       : 2
siblings        : 4
If the values of cpu cores and siblings are equal, then hyper threading is DISABLED otherwise ENABLED.
On some Linux distributions (RedHat, CentOS) you can even set Hyper Threading online: Is hyper-threading enabled on a Linux system?
How to make a patch for MariaDB?
Question: I have found a bug for MariaDB and have fixed it. How do I make a patch for it?
Answer: I was told by the MariaDB developers that they would like to have it like this:
diff -up orig.cc new.cc
Where does the InnoDB AUTO-INC waiting come from?
Question: With SHOW INNODB STATUS we have seen under high load a lot of transactions waiting on AUTO_INC. Where does it come from?
Answer: This is a bug in MySQL. It looks as follows:
——- TRX HAS BEEN WAITING 10 SEC FOR THIS LOCK TO BE GRANTED:
TABLE LOCK table `test/test` trx id 0 447488123 lock mode AUTO-INC waiting
This bug will be fixed in newer MySQL 5.1 releases (>= 5.1.47) but not in MySQL 5.0.
For more details refer to:
InnoDB auto-inc scalability fixed
Bug #16979: AUTO_INC lock in InnoDB works a table level lock
My character encoding seems to be wrong. How can I fix it?
Question: It looks like my data are somehow wrong in my MySQL database. I get some strange characters. How can I fix those?
Answer: This happens when you use the wrong encoding to fill in your data in the database. How this happens and how to fix it again you can find in the following lines:
mysql> CREATE TABLE `test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`data` varchar(64) DEFAULT NULL,
`ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=PBXT DEFAULT CHARSET=latin1
# Wrong encoding!!!
mysql> SET NAMES latin1;
mysql> INSERT INTO test VALUES (NULL, ‘äöü’, NULL);
# Data seems to be correct but are not:
mysql> SELECT data, HEX(data) FROM test;
+——–+————–+
| data   | HEX(data)    |
+——–+————–+
| äöü    | C3A4C3B6C3BC |
+——–+————–+
# Set right enconding:
mysql> SET NAMES utf8;
# Wrong umlaut encoding for latin1 column:
mysql> SELECT data, HEX(data) FROM test;
+————–+————–+
| data         | hex(data)    |
+————–+————–+
| äöü       | C3A4C3B6C3BC |
+————–+————–+
# Fix encoding
mysql> ALTER TABLE test MODIFY data VARBINARY(64);
mysql> ALTER TABLE test MODIFY data VARCHAR(64) CHARACTER SET utf8;
mysql> SHOW CREATE TABLE test\G
CREATE TABLE `test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`data` varchar(64) CHARACTER SET utf8 DEFAULT NULL,
`ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=PBXT DEFAULT CHARSET=latin1
# Now the data are displayed correctly and encoding matches the CHARACTERSET defintion of the column
mysql> SELECT data, HEX(data) FROM test;
+——–+————–+
| data   | hex(data)    |
+——–+————–+
| äöü    | C3A4C3B6C3BC |
+——–+————–+
# Convert encoding now to latin1
mysql> ALTER TABLE test MODIFY data VARCHAR(64) CHARACTER SET latin1;
# Now the data are displayed correctly and encoding matches the CHARACTERSET defintion of the column
mysql> SELECT data, HEX(data) FROM test;
+——–+———–+
| data   | hex(data) |
+——–+———–+
| äöü    | E4F6FC    |
+——–+———–+
mysql> SHOW CREATE TABLE test\G
CREATE TABLE `test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`data` varchar(64) DEFAULT NULL,
`ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=PBXT DEFAULT CHARSET=latin1
If the table was created with utf8 character set the procedure is as follows:
ALTER TABLE test MODIFY data VARCHAR(64) CHARACTER SET latin1;
ALTER TABLE test MODIFY data VARBINARY(64);
ALTER TABLE test MODIFY data VARCHAR(64);
I think my Slave is not consistent to its Master anymore. How can I check this?
Question: I think my Slave is not consistent to its Master anymore. How can I check this?
Answer: The best way to do it is using the Maatkit-Tools.
In the Maatkit-toolbox there is mk-table-checksum and mk-table-sync. How to use it you can find as follows:
Check
On Master:
mk-table-checksum –create-replicate-table –empty-replicate-table –replicate=test.checksum \
u=root,h=127.0.0.1 \
–tables=test.test
On Slave:
mk-table-checksum –replicate=test.checksum \
–replicate-check=1 \
u=root,h=127.0.0.1 \
–tables=test.test
Sync
On Slave:
mk-table-sync –sync-to-master  –print \
h=127.0.0.1,u=root,D=test,t=test
Then run the queries on the master…
My MySQL Server is swapping from time to time. This gives hick-ups in MySQL. How can I avoid this?
Question: My MySQL Server is swapping from time to time. This gives hick-ups in MySQL. How can I avoid this?
Answer: First of all you have to make sure, that MySQL does not over-allocate memory:
# free
total       used       free     shared    buffers     cached
Mem:      16431968    5736652   10695316          0     127876    2449008
-/+ buffers/cache:    3159768   13272200
Swap:     19802108          0   19802108
# ps aux | grep -e ‘mysqld ‘ -e ‘VSZ’ | cut -b-120
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
mysql     2020  1.8  6.1 3166896 1010840 ?     Sl   08:06  11:09 /home/mysql/product/mysql-5.6.2/bin/mysqld
If you checked this and it looks OK you can check the swappiness of your system:
# cat /proc/sys/vm/swappiness
60
# sysctl -a
# sysctl vm.swappiness
If the value is bigger than 0 you can set it either on the fly or make it permanent:
# sysctl -n vm.swappiness=0
or
#
# /etc/sysctl.conf
#
vm.swappiness=0
# sysctl -p /etc/sysctl.conf
»
•    Login or register to post comments
MySQL Doubts
Submitted by vishnuraj on Wed, 2011-04-13 08:51.
Hi everybody
Please rectify my doubts.
In my database i have three fields as id,medicinename,quantity.
In medicine name i have many different names.Many names comes twice or thrice.Now i need to fetch the data from database for particular medicine name only(this medicine name comes nearly 10 times)say for example if the medicinename is “A” it comes in id 1,4,9,12,25.Now i want to fetch the data from id 1 only.Whent the quantity comes to “0″ in id “1″,i want to fetch the datas from next id.Also when the quantity comes to “0″ the row shold be deleted automatically.Please help me to do this.
»
•    Login or register to post comments
Medicine table
Submitted by oli on Thu, 2011-04-21 15:19.
Hi vishnuraj
Simple examples are always good to explain or to try to understand. So I created the following table:
In my database I have 3 fields as id,medicinename,quantity.
In medicinename I have many different names. Many names comes twice or thrice.
+——+———————-+———+
| id   | medicinename         | quantiy |
+——+———————-+———+
|    1 | Trifolium arvense L. |      25 |
|    2 | Agave americana      |     120 |
|    3 | Hypericum perforatum |      12 |
|    4 | Trifolium arvense L. |      35 |
|    5 | Agave americana      |     120 |
|    6 | Trifolium arvense L. |     120 |
+——+———————-+———+
Now I need to fetch the data from database for particular medicine name only (this medicine name comes nearly 10 times) say for example if the medicinename is “A” it comes in id 1,4,9,12,25.
SELECT * FROM medicine WHERE medicinename = ‘Trifolium arvense L.’;
+——+———————-+———+
| id   | medicinename         | quantiy |
+——+———————-+———+
|    1 | Trifolium arvense L. |      25 |
|    4 | Trifolium arvense L. |      35 |
|    6 | Trifolium arvense L. |     120 |
+——+———————-+———+
So far so good. Up to here I could follow you but then I loose you:
Now I want to fetch the data from id 1 only. When the quantity comes to “0″ in id “1″, I want to fetch the data from next id. Also when the quantity comes to “0″ the row should be deleted automatically.
I think there is some missing business logic information in your explanation. What is meant with “when the quantity comes to 0″? Further “I want to fetch the data from next id” and “the row should deleted automatically” sounds like you mix data with business logic.
Could you please explain more in detail, what you want to achieve?
General Information About MySQL
MySQL is a very fast, multi-threaded, multi-user, and robust SQL (Structured Query Language) database server.
MySQL is free software. It is licensed with the GNU GENERAL PUBLIC LICENSE http://www.gnu.org/.
What Is MySQL
MySQL, the most popular Open Source SQL database, is provided by MySQL AB. MySQL AB is a commercial company that builds is business providing services around the MySQL database. See section 1.2 What Is MySQL AB.
ySQL is a database management system.
A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL. Since computers are very good at handling large amounts of data, database management plays a central role in computing, as stand-alone utilities, or as parts of other applications.
MySQL is a relational database management system.
A relational database stores data in separate tables rather than putting all the data in one big storeroom. This adds speed and flexibility. The tables are linked by defined relations making it possible to combine data from several tables on request. The SQL part of MySQL stands for “Structured Query Language” – the most common standardized language used to access databases.
MySQL is Open Source Software.
Open source means that it is possible for anyone to use and modify. Anybody can download MySQL from the Internet and use it without paying anything. Anybody so inclined can study the source code and change it to fit their needs. MySQL uses the GPL (GNU General Public License) http://www.gnu.org, to define what you may and may not do with the software in different situations. If you feel uncomfortable with the GPL or need to embed MySQL into a commercial application you can buy a commercially licensed version from us.
Why use MySQL?
MySQL is very fast, reliable, and easy to use. If that is what you are looking for, you should give it a try. MySQL also has a very practical set of features developed in very close cooperation with our users. You can find a performance comparison of MySQL to some other database managers on our benchmark page. See section 12.7 Using Your Own Benchmarks. MySQL was originally developed to handle very large databases much faster than existing solutions and has been successfully used in highly demanding production environments for several years. Though under constant development, MySQL today offers a rich and very useful set of functions. The connectivity, speed, and security make MySQL highly suited for accessing databases on the Internet.
The technical features of MySQL
For advanced technical information, see section 7 MySQL Language Reference. MySQL is a client/server system that consists of a multi-threaded SQL server that supports different backends, several different client programs and libraries, administrative tools, and a programming interface. We also provide MySQL as a multi-threaded library which you can link into your application to get a smaller, faster, easier to manage product. MySQL has a lot of contributed software available.
It is very likely that you will find that your favorite application/language already supports MySQL. The official way to pronounce MySQL is “My Ess Que Ell” (not MY-SEQUEL). But we try to avoid correcting people who say MY-SEQUEL.
The Main Features of MySQL
The following list describes some of the important characteristics of MySQL:
Fully multi-threaded using kernel threads. That means it can easily use multiple CPUs if available.
C, C++, Eiffel, Java, Perl, PHP, Python and Tcl APIs.
Works on many different platforms.
Many column types: signed/unsigned integers 1, 2, 3, 4, and 8 bytes long, FLOAT, DOUBLE, CHAR, VARCHAR, TEXT, BLOB, DATE, TIME, DATETIME, TIMESTAMP, YEAR, SET, and ENUM types.
Very fast joins using an optimized one-sweep multi-join.
Full operator and function support in the SELECT and WHERE parts of queries. Example:
mysql> SELECT CONCAT(first_name, ” “, last_name) FROM tbl_name
WHERE income/dependents > 10000 AND age > 30;
1 What Is MySQL?
2 What Is mSQL?
3 What Is SQL?
4 What Is Table?
5 What Is Column?
6 What Is Row?
7 What Is Primary Key?
8 What Is Foreign Key?
9 What Is Index?
10 What Is View?
11 What Is Join?
12 What Is Union?
13 What Is ISAM?
14 What Is MyISAM?
15 What Is InnoDB?
16 What Is BDB (BerkeleyDB)?
17 What Is CSV?
18 What Is Transaction?
19 What Is Commit?
20 What Is Rollback?
21 Explain what Is MySQL?
22 How To Install MySQL?
23 How To Start MySQL Server?
24 How Do You Know If Your MySQL Server Is Alive?
25 How Do You Know the Version of Your MySQL Server?
26 How To Create a Test Table in Your MySQL Server?
27 How To Shutdown MySQL Server?
28 What Tools Available for Managing MySQL Server?
29 What Is “mysqld”?
30 What Is “mysqladmin” in MySQL?
31 How To Check Server Status with “mysqladmin”?
32 How To Shut Down the Server with “mysqladmin”?
33 How To Use “mysql” to Run SQL Statements?
34 How To Show All Tables with “mysql”?
35 What Is “mysqlcheck”?
36 How To Analyze Tables with “mysqlcheck”?
37 What Is “mysqlshow”?
38 How To Show Table Names with “mysqlshow”?
39 What Is “mysqldump”?
40 How To Dump a Table to a File with “mysqldump”?
41 What Is “mysqlimport”?
42 How To Load Data Files into Tables with “mysqlimport”?
43 What Is the Command Line End User Interface – mysql?
44 What Are the “mysql” Command Line Options?
45 What Are the “mysql” Command Line Arguments?
46 How Many SQL DDL Commands Are Supported by “mysql”?
47 How Many SQL DML Commands Are Supported by “mysql”?
48 What Are the Non-Standard SQL Commands Supported by “mysql”?
49 How To Get Help Information from the Server?
50 How To Run “mysql” Commands from a Batch File?
51 How To Return Query Output in HTML Format?
52 How To Return Query Output in XML Format?
53 What Is SQL in MySQL?
54 How Many Groups of Data Types?
55 What Are String Data Types?
56 What Are the Differences between CHAR and NCHAR?
57 What Are the Differences between CHAR and VARCHAR?
58 What Are the Differences between BINARY and VARBINARY?
59 What Are Numeric Data Types?
60 What Are Date and Time Data Types?
61 How To Calculate Expressions with SQL Statements?
62 How To Include Comments in SQL Statements?
63 How To Include Character Strings in SQL statements?
64 How To Escape Special Characters in SQL statements?
65 How To Concatenate Two Character Strings?
66 How To Include Numeric Values in SQL statements?
67 How To Enter Characters as HEX Numbers?
68 How To Enter Numeric Values as HEX Numbers?
69 How To Enter Binary Numbers in SQL Statements?
70 How To Enter Boolean Values in SQL Statements?
71 What Are NULL Values?
72 What Happens If NULL Values Are Involved in Expressions?
73 How To Convert Numeric Values to Character Strings?
74 How To Convert Character Strings to Numeric Values?
75 How To Use IN Conditions?
76 How To Use LIKE Conditions?
77 How To Use Regular Expression in Pattern Match Conditions?
78 How To Use CASE Expression?
79 What Are Date and Time Data Types in MySQL?
80 How To Write Date and Time Literals?
81 How To Enter Microseconds in SQL Statements?
82 How To Convert Dates to Character Strings?
83 How To Convert Character Strings to Dates?
84 What Are Date and Time Intervals?
85 How To Increment Dates by 1 in MySQL?
86 How To Decrement Dates by 1 in MySQL?
87 How To Calculate the Difference between Two Dates?
88 How To Calculate the Difference between Two Time Values?
89 How To Present a Past Time in Hours, Minutes and Seconds?
90 How To Extract a Unit Value from a Date and Time?
91 What Are Date and Time Functions in MySQL?
92 What Is TIMESTAMP in MySQL?
93 How Many Ways to Get the Current Time?
94 What Are DDL Statements in MySQL?
95 How To Create a New Table in MySQL?
96 What Happens If You No CREATE Privilege in a Database?
97 How To Get a List of All Tables in a Database?
98 How To Get a List of Columns in an Existing Table?
99 How To See the CREATE TABLE Statement of an Existing Table?
100 How To Create a New Table by Selecting Rows from Another Table in MySQL?
101 How To Add a New Column to an Existing Table in MySQL?
102 How To Delete an Existing Column in a Table?
103 How To Rename an Existing Column in a Table?
104 How To Rename an Existing Table in MySQL?
105 How To Drop an Existing Table in MySQL?
106 How To Create a Table Index in MySQL?
107 How To Get a List of Indexes of an Existing Table?
108 How To Drop an Existing Index in MySQL?
109 How To Create a New View in MySQL?
110 How To Drop an Existing View in MySQL?
——————————————————————————–
Sort By :   Latest First  |  Oldest First  |  By Rating
Question    Rating
What is SERIAL data type in MySQL?
What?s the default port for MySQL Server?
What does “tee” command do in MySQL?
Explain about database design?
What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
How to connect mysql from jsp(Java Server Page)?
Explain the difference between MyISAM Static and MyISAM Dynamic
How will retrieve nth level categories from one query in mysql ?
What does myisamchk do?
what is difference between candidate key and primary key
Which version of MySQL supports Subquery?
Describe the use of PL/SQL tables
Can you save your connection settings to a conf file?
How to display nth highest record in a table for example?How to display 4th highest (salary) record from customer table?
How do you use Outer Join in MySQL
What are some good ideas regarding user security in MySQL?
Explain the difference between mysql and mysqli interfaces in PHP?
How do you change a password for an existing user via mysqladmin?
What is the Oracle rowid counterpart in MySQL?
Describe the use of %ROWTYPE and %TYPE in PL/SQL
Previous 1 2 3 4 5 6 7 8 9 Next
Sort By :   Latest First  |  Oldest First  |  By Rating
Question    Rating
State some security recommendations while using MYSQL?
When is a declare statement needed ?
Explain the difference between BOOL, TINYINT and BIT.
Explain data type TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do?
Explain about MYSQL and its features?
How do you start and stop MySQL on Windows?
State two considerations which can improve the performance of MYSQL?
How to see the database architecture in MySQL??
What are the advantages of mysql comparing with oracle?
Use mysqldump to create a copy of the database?
What are the advantages of Mysql comparing with oracle?
Explain about the rules which should be followed while assigning a username?
What Is “mysqladmin” in MySQL?
How To Create a New View in MySQL?
State some of the features of MYSQL?
How to create MYSQL new users?
How we can count duplicate entery in particular table against Primary Key ? What are constraints?
how to add video or audio file database
Explain about normalization?
Question    Rating
How do you control the max size of a HEAP table?
What are HEAP tables in MySQL?
Explain some of the uses of MYSQL?
How To Drop an Existing View in MySQL
What happens when we don?t use Console option?
What packages (if any) has Oracle provided for use by developers?
What happens if a table has one column defined as TIMESTAMP?
Explain federated tables
Explain about HEAP table?
How MySQL is different from SQL?
How do you configure mysql on linux
Explain about MyISAM table?
How do you start MySQL on Linux?
Explain about the time stamp field?
Explain about creating database?
How many drivers in MYSQL?
Explain about primary keys?