Powered By Blogger

Sunday, 31 July 2011

How i can get ip address?

We can use SERVER var $_SERVER['SERVER_ADDR'] and getenv("REMOTE_ADDR") and $_SERVER['REMOTE_ADDR'] functions to get the IP address.


<?php
echo $_SERVER['SERVER_ADDR'];
echo $_SERVER['REMOTE_ADDR'];
echo getenv("REMOTE_ADDR");
?>


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



<?php
$str = "A 'quote' is <b>bold</b>";
echo htmlentities($str);
echo htmlentities($str, ENT_QUOTES);
?>


htmlspecialchars — Convert special characters to HTML entities

htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand.

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new;
?> 

functions to sorting an array elements

The following functions are used sorting an array elements
Sort(),          arsort(),
asort(),          ksort(),
rsort(),          usort()
array_multisort() & uksort()

What are the differences between public, private, protected, static, transient, final and volatile?

Public: Public declared items can be accessed everywhere.
 
Protected: Protected limits access to inherited and parent classes (and to the class that defines the item).

Private: Private limits visibility only to the class that defines the item.
 
Static: A static variable exists only in a local function scope,but it does not lose its value when program execution leaves this scope.

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

transient: A transient variable is a variable that may not be serialized.

volatile:
a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time.

What is meant by nl2br()?

Inserts HTML line breaks (<BR />) before all newlines in a string
string nl2br (string); Returns string with ” inserted before all
newlines.
For example: 

echo nl2br(“god bless\n you”);

will output “god
bless <br /> you” to your browser

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?

When to use GET or POST

The HTML 2.0 specification says, in section Form
Submission (and the HTML 4.0 specification repeats this with minor
stylistic changes):
–>If the processing of a form is idempotent
(i.e. it has no lasting observable effect on the state of the
world), then the form method should be GET. Many database searches
have no visible side-effects and make ideal applications of query
forms.

–>If the service associated with the processing of a form has side
effects (for example, modification of a database or subscription to
a service), the method should be POST.

How the form data is transmitted?

quotation from the HTML 4.0 specification
–> If the method is “get” – -, the user agent
takes the value of action, appends a ? to it, then appends the form
data set, encoded using the application/x-www-form-urlencoded
content type. The user agent then traverses the link to this URI. In
this scenario, form data are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post
transaction using the value of the action attribute and a message
created according to the content type specified by the enctype
attribute.

Quote from CGI FAQ

Firstly, the the HTTP protocol specifies
differing usages for the two methods. GET requests should always be
idempotent on the server. This means that whereas one GET request
might (rarely) change some state on the Server, two or more
identical requests will have no further effect.
This is a theoretical point which is also good
advice in practice. If a user hits “reload” on his/her browser, an
identical request will be sent to the server, potentially resulting
in two identical database or
guestbook entries, counter increments, etc. Browsers may reload a
GET URL automatically, particularly if cacheing is disabled (as is
usually the case with CGI output), but will typically prompt the
user before
re-submitting a POST request. This means you’re far less likely to
get inadvertently-repeated entries from POST.
GET is (in theory) the preferred method for
idempotent operations, such as querying a database, though it
matters little if you’re using a form. There is a further practical
constraint that many systems have built-in limits to the length of a
GET request they can handle: when the total size of a request (URL+params)
approaches or exceeds 1Kb, you are well-advised to use POST in any
case.
I would prefer POST when I don’t want the status to
be change when user resubmits. And GET
when it does not matter.

display PHP errors in My Script Code When display_errors is Disabled

ometimes, your head turns trying to figure out what the problem is with your script. many times when the display_errors if off, you won't have a clue as to what the problem is unless you display the php errors.

this is how the php.ini file would look like:



     Quote:
; - display_errors = Off [Security]
; With this directive set to off, errors that occur during the execution of
; scripts will no longer be displayed as a part of the script output, and thus,
; will no longer be exposed to remote users. With some errors, the error message
; content may expose information about your script, web server, or database
; server that may be exploitable for hacking. Production sites should have this
; directive set to off.

; Print out errors (as a part of the output). For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below). Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
display_errors = On





copy and paste this code


ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);

mysql_connect or mysql_pconnect

If you're connecting to a MySQL database in your PHP application, you'll find that there are two alternative connections - mysql_connect which establishes a new connection "each time" and mysql_pconnect which uses persistent connections. Which should you use?

Mysql_connect opens a new connection each time a PHP page is called up, and closes the connection down again at the end of the request. It's ideal for pages that don't have a heavy usage - doesn't need tuning, is straightforward internally. If you compare MySQL to a shop, this is the connection that you would use for a small shop where the door is opened each time a new customer wishes to enter.

Mysql_pconnect will also open a new connection when a PHP page is called up (at any rate, it will the first time after a server reboot), but it will NOT close the connection at the end of the request - instead, it will save it in a connection pool so that a subsequent request can continue to use the same connection. It's intended for pages that do have a heavy usage - where the resources burn up by opening and closing connections every time might have a severe effect on performance. If your local supermarket had a door that was opened each time someone went in and out, there would be a lot of needless opening and closing going on - better to leave it open and let a whole lot of people in and out at the same time.

But mysql_pconnect does require some tuning of the servers and you may need to limit the numbers of connections / children and configure timeouts and how to deal with idle children. The PHP website includes an overview of this to get you started.

Finally, it is worth stressing what a persistent connect does NOT give you. It does NOT give you sessions. It does NOT give you a per-site-visitor login. It does NOT give you any extra functionality. What it does give you - in the right circumstances - is an efficiency improvement.

"this" or "self" keyword

Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

<?phpclass X {
    
private $non_static_member = 1;
    
private static $static_member = 2;

    function
__construct() {
        echo
$this->non_static_member . ' '
           
. self::$static_member;
    }
}

new
X();?> 

What is difference between require_once(), require(),include(),include_once()

require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page).
So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.


Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING.

There is also include_once() which is the same as include(), but the difference between them is the same as the difference between require() and require_once().

Saturday, 30 July 2011

Difference between mysql_fetch_assoc, mysql_fetch_row,mysql_fetch_object and mysql_fetch_array

  • mysql_fetch_array():- Fetch a result row as an associative array, a numeric array, or both by         default it fetches both.
  • mysql_fetch_row() :- Get a result row as an numeric array
  • mysql_fetch_object() :- Fetch a result row as an object
  • mysql_fetch_assoc() :- Fetch a result row as an associative array.


Suppose we have a database called 'test' and it has a table called 'members' which stores some members' information. The goal is to fetch all the members' information. Consider such code below:
$conn=mysql_connect('localhost','root','');
$mysql_select_db('test');
$rs=mysql_query('SELECT * FROM members');


Then $rs is an array that stores all personal information. You can use mysql_fetch_array() or mysql_fetch_assoc() to fetch each row by calling the function repeatedly. Consider:
while ($row=mysql_fetch_array($rs,MYSQL_NUM)){
  // ...
}

Here $row is a normal array (integer-indexed array). You cannot get data with $row['name'], $row['birthday'], etc. You must use integer as the index, e.g. $row[0], $row[1]... How to get an associative array? You need to set the second parameter of mysql_fetch_array(). MYSQL_ASSOC tells mysql_fetch_array() to return an associative array. See below:
while ($row=mysql_fetch_array($rs,MYSQL_ASSOC)){
  // ... here you can use $row['name'], $row['birthday']...
}


mysql_fetch_array($rs,MYSQL_BOTH) equals to mysql_fetch_array($rs). There's no need to use MYSQL_BOTH, so we often omit it.

So you can use two methods to fetch data by specifying the second parameter to MYSQL_BOTH or omitting the second parameter. Then both of the styles, $row[0] and $row['name'], are available.

But where's mysql_fetch_assoc()? It seems not useful. Right. mysql_fetch_assoc($rs) is equivalent to mysql_fetch_array($rs,MYSQL_ASSOC). Obviously, when you need to an associated array (string-indexed array) only, mysql_fetch_assoc() is more convenient. By the way, mysql_fetch_assoc doesn't have the second parameter. It can only return associative array so it needs less memory space to store the result array.


$rows = mysql_fetch_object( "select name, address from people" );
Means you then get each of the row results using the object notation.
foreach( $rows as $row )
echo $row->name . ' lives at ' . $row->address ;

What is form validation?

orm validation is the process of checking that a form has been filled in correctly before it is processed. For example, if your form has a box for the user to type their email address, you might want your form handler to check that they've filled in their address before you deal with the rest of the form.
There are two main methods for validating forms: server-side (using CGI scripts, ASP, etc), and client-side (usually done using JavaScript). Server-side validation is more secure but often more tricky to code, whereas client-side (JavaScript) validation is easier to do and quicker too (the browser doesn't have to connect to the server to validate the form, so the user finds out instantly if they've missed out that required field!).
Client-side validation
Client-side form validation (usually with JavaScript embedded in the Web page)
Server-side validation
Server-side form validation (usually performed by a CGI or ASP script)
In this tutorial we'll build a simple form with client-side JavaScript validation. You can then adapt this form to your own requirements.

A simple form with validation

Let's build a simple form with a validation script. The form will include one text field called "Your Name", and a submit button. Our validation script will ensure that the user enters their name before the form is sent to the server.
Open this page to see it in action. Try pressing the Send Details button without filling anything in the "Your Name" field.
You might like to open the source code for this form in a separate window, so that you can refer to it throughout the tutorial.
You can see that the page consists of a JavaScript function called validate_form() that performs the form validation, followed by the form itself. Let's look at the form first.

The form

The first part of the form is the form tag:

<form name="contact_form" method="post"
action="/cgi-bin/articles/development/
  javascript/form-validation-with-javascript/contact_simple.cgi"
onsubmit="return validate_form ( );">
The form is given a name of "contact_form". This is so that we can reference the form by name from our JavaScript validation function.
The form uses the post method to send the data off to a dummy CGI script on ELATED.com's server that thanks the user. In reality, you would of course send the data to your own CGI script, ASP page, etc. (e.g. a form mailer).
Finally, the form tag includes an onsubmit attribute to call our JavaScript validation function, validate_form(), when the "Send Details" button is pressed. The return allows us to return the value true or false from our function to the browser, where true means "carry on and send the form to the server", and false means "don't send the form". This means that we can prevent the form from being sent if the user hasn't filled it in properly.
The rest of the form prompts the user to enter their name into a form field called contact_name, and adds a "Send Details" submit button:

<h1>Please Enter Your Name</h1>

<p>Your Name: <input type="text" name="contact_name"></p>
<p><input type="submit" name="send" value="Send Details"></p>

</form>
Now let's take a look at the JavaScript form validation function that does the actual work of checking our form.

The validate_form() function

The form validation function, validate_form(), is embedded in the head element near the top of the page:

<script type="text/javascript">
<!--

function validate_form ( )
{
    valid = true;

    if ( document.contact_form.contact_name.value == "" )
    {
        alert ( "Please fill in the 'Your Name' box." );
        valid = false;
    }

    return valid;
}

//-->
</script>
The first line (<script type="text/javascript">) tells the browser that we are writing some JavaScript, and the HTML comment (<!--) in the second line hides the script from older browsers that don't understand JavaScript.
Next we start our validate_form() function, then set a variable called valid to the value true:

function validate_form ( )
{
    valid = true;
We use this valid variable to keep track of whether our form has been filled out correctly. If one of our checks fails, we'll set valid to false so that the form won't be sent.
The next 5 lines check the value of our contact_name field to make sure it has been filled in:

    if ( document.contact_form.contact_name.value == "" )
    {
        alert ( "Please fill in the 'Your Name' box." );
        valid = false;
    }
If the field is empty, the user is warned with an alert box, and the variable valid is set to false.
Next, we return the value of our valid variable to the onSubmit event handler (described above). If the value is true then the form will be sent to the server; if it's false then the form will not be sent:

    return valid;
Finally, we finish our validate_form() function with a closing brace, and end our HTML comment and script element:

}

//-->

</script>
That's all there is to simple JavaScript form validation! Our example is very simple as it only checks one field. Let's expand this example with a more complex function that checks lots of form fields. We'll also look at how to check other types of fields, such as checkboxes, radio buttons and drop-down lists.

A more complex form

Let's look at a more complex validated form with some different types of form fields.
Open this page to see it in action. Try pressing the Send Details button without filling in the form and see what happens.
Again, you might like to open the source code for this form in a separate window, so that you can refer to it as we talk you through.
Like our previous example, this page has a form called contact_form and a function called validate_form(). In addition to the previous text field, the form has radio buttons, a drop-down list and a checkbox.
The validate_form() function now has 3 extra checks, one for each of our new fields.

Validating radio buttons

After the contact_name text box has been checked, the gender radio buttons are validated:

    if ( ( document.contact_form.gender[0].checked == false )
    && ( document.contact_form.gender[1].checked == false ) )
    {
        alert ( "Please choose your Gender: Male or Female" );
        valid = false;
    }
This code checks to see whether either of the radio buttons ("Male" or "Female") have been clicked. If neither have been clicked (checked == false), the user is alerted and valid is set to false.

Validating drop-down lists

Next the "Age" drop-down list is checked to see if the user has selected an option. In the form, we named the first option in the drop-down list "Please Select an Option". Our JavaScript can then check which option was selected when the user submitted the form. If the first option is selected, we know the user has not selected a "real" option and can alert them:

    if ( document.contact_form.age.selectedIndex == 0 )
    {
        alert ( "Please select your Age." );
        valid = false;
    }
Note that the values for selectedIndex start at zero (for the first option).

Validating checkboxes

Finally, the "Terms and Conditions" checkbox is validated. We want to the user to agree to our imaginary Terms and Conditions before they send the form, so we'll check to make sure they've clicked the checkbox:

    if ( document.contact_form.terms.checked == false )
    {
        alert ( "Please check the Terms & Conditions box." );
        valid = false;
    }

Because we set our valid variable to false in any one of the above cases, if one or more of our checks fail, the form will not be sent to the server. If the user has not completed more than one field, then they will see an alert box appear for each field that is missing.
Now you know how to write a form validation script that can handle multiple form fields, including text boxes, radio buttons, drop-down lists and check boxes!
One point to note about JavaScript validation is that it can always be circumvented by the user disabling JavaScript in their browser, so for secure validation you'll need to write your validating code in your server-side scripts. However, for day-to-day use JavaScript is a quick and easy way to check over your forms before they're sent to your server.

Friday, 29 July 2011

Installing PHP On Windows

There are several different installation methods for PHP, though we strongly recommend you follow the manual installation process. At the time of publication, the automated installer is not complete, secure or intended for use on live servers. Follow these steps to install PHP on your system:

1. Go to the PHP web site at www.php.net .

2. Click on the Download link to go to the site ’ s downloads page.

3. Scroll down to the Windows Binary section, and click on the appropriate link to download the
latest PHP .zip package.

4. Click any of the mirror sites to begin the download. If you have difficulties downloading from
one mirror, then try a different mirror that may be closer to you.

5. Once the Zip file has been downloaded, extract its contents using any standard unzip program
and save it to the directory of your choice. We recommend a directory named C:\PHP .
Both Windows XP and Windows Vista have built - in capabilities to extract files from Zip
archives. If you are on a different version of Windows or prefer to use a dedicated compression
tool, we recommend 7 - Zip available at www.7 - zip.org . It is a free application that can work
with many different compression formats, including Zip.

6. It is advised to run PHP with a php.ini file. By default, the PHP installation provides
two copies of the file with common configuration values: php.ini - dist and
php.ini - recommended . Rename the configuration file of your choice to php.ini .
The php.ini - dist file is meant to be used for development purposes while
php.ini - recommended has additional security measures and should be used when your site
goes live. Depending on your reason for using PHP, choose the php.ini file that best suits your
needs. For the purposes of this book, we are going to be using the php.ini - dist . Feel free to
switch to the php.ini - recommended file as your default once you are more familiar with how
PHP behaves.

7. Bring up the System Properties window. In Windows XP, this is done by right - clicking on the
My Computer icon on your desktop and selecting Properties. In Windows Vista, this is done by
right - clicking on the Computer icon on your desktop, selecting Properties and then Advanced
System Settings.

8.Select the Advanced tab, and then click the Environment Variables button. Add the directory to
which you extracted PHP to your System ’ s PATH variable ( C:\PHP in our configuration). Also
create a new System variable PHPRC with the same directory as its value. This allows other
applications (such as Apache) to find PHP without your having to copy files into your System
directory.

Installing Apache On WIndows

As your web server, Apache ’ s main job is to listen to any incoming requests from a browser and return
an appropriate response. Apache is quite powerful and can accomplish virtually any task that you as a
webmaster require.


According to the Netcraft web site ( www.netcraft.com ), Apache is running over 83.5 million Internet
servers, more than Microsoft, Sun ONE, and Zeus combined at the time of this writing. Its flexibility,
power, and, of course, price make it a popular choice. It can be used to host a web site for the general
public, a company - wide intranet or for simply testing your pages before they are uploaded to a secure
server on another machine.


Follow these steps to download and install Apache on your Windows machine 
 
1. Go to www.apache.org , and click the HTTP Server link in the Apache Projects list. The Apache
Software Foundation offers many different software packages, though the HTTP Server is the
only one we are concerned with.

2. Click the Download link under the most recent version of Apache.

3. Click the Win 32 Binary (MSI Installer) link to download the installation package. Whether you
choose the download without mod_ssl or the one that includes OpenSLL depends on your local
laws, needs and personal preferences. We do not use any of the functionality offered by mod_ssl
in this book, so if you want to lean towards the safe side feel free to download the package
without mod_ssl .
If you experience problems downloading this file, you can try downloading from a
different mirror site. Select an available mirror from the drop - down box near the top of the
download page.

4. You should be able to double - click the MSI file to initiate the installation wizard for Apache once
it has finished downloading, but you may experience some issues depending on what security
policies Windows has in effect. We recommend running the installer with administrative
privileges from within a console window.
To open a console as an Administrator in Windows XP, navigate through Start All Programs
Accessories, right - click on Command Prompt and select the Run As option. In Windows Vista,
navigate through Start All Programs Accessories, right - click on Command Prompt, and
select the Run as Administrator option.

5. Use the cd command to navigate to where you downloaded the installer file, and then run the
installer using msiexec - i . The Installation Wizard will open.
cd C:\Users\Timothy\Downloads\
msiexec -i apache_2.2.9-win32-x86-no_ssl-r2.msi

6. After accepting the installation agreement, you will see a screen that is equivalent to a
readme.txt file — it gives basic information about the Apache software and where to go to
find more information. We highly recommend that you read this.

7. Enter the following information on the Server Information screen:
❑ Domain name: For example, example.com
❑ Server name: For example, www.example.com
❑ Net administrator ’ s e - mail address
❑ Whether to install Apache for all users or only the current user.
We recommend the default option, which is to install Apache for all users on port 80 as a service

To test the installation of your Apache server, open a web browser and type the following URL:
http://localhost/



Basic MySQL command

To login (from unix shell) use -h only if needed.

# [mysql dir]/bin/mysql -h hostname -u root -p

Create a database on the sql server.

mysql> create database [databasename];

List all databases on the sql server.

mysql> show databases;

Switch to a database.

mysql> use [db name];

To see all the tables in the db.

mysql> show tables;

To see database's field formats.

mysql> describe [table name];

To delete a db.

mysql> drop database [database name];

To delete a table.

mysql> drop table [table name];

Show all data in a table.

mysql> SELECT * FROM [table name];

Returns the columns and column information pertaining to the designated table.

mysql> show columns from [table name];

Show certain selected rows with the value "whatever".

mysql> SELECT * FROM [table name] WHERE [field name] = "whatever";

Show all records containing the name "Bob" AND the phone number '3444444'.

mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';

Show all records not containing the name "Bob" AND the phone number '3444444' order by the phone_number field.

mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number;

Show all records starting with the letters 'bob' AND the phone number '3444444'.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444';

Show all records starting with the letters 'bob' AND the phone number '3444444' limit to records 1 through 5.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444' limit 1,5;

Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with a.

mysql> SELECT * FROM [table name] WHERE rec RLIKE "^a";

Show unique records.

mysql> SELECT DISTINCT [column name] FROM [table name];

Show selected records sorted in an ascending (asc) or descending (desc).

mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;

Return number of rows.

mysql> SELECT COUNT(*) FROM [table name];

Sum column.

mysql> SELECT SUM(*) FROM [table name];

Join tables on common columns.

mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;

Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));
mysql> flush privileges;

Change a users password from unix shell.

# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'

Change a users password from MySQL prompt. Login as root. Set the password. Update privs.

# mysql -u root -p
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
mysql> flush privileges;

Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.

# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start

Set a root password if there is on root password.

# mysqladmin -u root password newpassword

Update a root password.

# mysqladmin -u root -p oldpassword newpassword

Allow the user "bob" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to bob@localhost identified by 'passwd';
mysql> flush privileges;

Give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;

or

mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;

To update info already in a table.

mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';

Delete a row(s) from a table.

mysql> DELETE from [table name] where [field name] = 'whatever';

Update database permissions/privilages.

mysql> flush privileges;

Delete a column.

mysql> alter table [table name] drop column [column name];

Add a new column to db.

mysql> alter table [table name] add column [new column name] varchar (20);

Change column name.

mysql> alter table [table name] change [old column name] [new column name] varchar (50);

Make a unique column so you get no dupes.

mysql> alter table [table name] add unique ([column name]);

Make a column bigger.

mysql> alter table [table name] modify [column name] VARCHAR(3);

Delete unique from table.

mysql> alter table [table name] drop index [colmn name];

Load a CSV file into a table.

mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);

Dump all databases for backup. Backup file is sql commands to recreate all db's.

# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql

Dump one database for backup.

# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql

Dump a table from a database.

# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql

Restore database (or database table) from backup.

# [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql

Create Table Example 1.

mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));

Create Table Example 2.

mysql> create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastnamevarchar(50) default 'bato');
l>

Error Handling

When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.
This tutorial contains some of the most common error checking methods in PHP.
We will show different error handling methods:
  • Simple "die()" statements
  • Custom errors and error triggers
  • Error reporting 
    Basic Error Handling: Using the die() function
    The first example shows a simple script that opens a text file:
    <?php
    $file=fopen("welcome.txt","r");
    ?>
    If the file does not exist you might get an error like this:
    Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
    No such file or directory in C:\webfolder\test.php on line 2
    To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:
    <?php
    if(!file_exists("welcome.txt"))
      {
      die("File not found");
      }
    else
      {
      $file=fopen("welcome.txt","r");
      }
    ?>
    Now if the file does not exist you get an error like this:
    File not found
    The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.
    However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors.

    Creating a Custom Error Handler
    Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.
    This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):
    Syntax
    error_function(error_level,error_message,
    error_file,error_line,error_context)

    Parameter
    Description
    error_level
    Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels
    error_message
    Required. Specifies the error message for the user-defined error
    error_file
    Optional. Specifies the filename in which the error occurred
    error_line
    Optional. Specifies the line number in which the error occurred
    error_context
    Optional. Specifies an array containing every variable, and their values, in use when the error occurred
    Error Report levels
    These error report levels are the different types of error the user-defined error handler can be used for:
    Value
    Constant
    Description
    2
    E_WARNING
    Non-fatal run-time errors. Execution of the script is not halted
    8
    E_NOTICE
    Run-time notices. The script found something that might be an error, but could also happen when running a script normally
    256
    E_USER_ERROR
    Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
    512
    E_USER_WARNING
    Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
    1024
    E_USER_NOTICE
    User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
    4096
    E_RECOVERABLE_ERROR
    Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
    8191
    E_ALL
    All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)
    Now lets create a function to handle errors:
    function customError($errno, $errstr)
      {
      echo "<b>Error:</b> [$errno] $errstr<br />";
      echo "Ending Script";
      die();
      }
    The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.
    Now that we have created an error handling function we need to decide when it should be triggered.

    Set Error Handler
    The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script.
    It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways. However, in this example we are going to use our custom error handler for all errors:
    set_error_handler("customError");
    Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.
    Example
    Testing the error handler by trying to output variable that does not exist:
    <?php
    //error handler function
    function customError($errno, $errstr)
      {
      echo "<b>Error:</b> [$errno] $errstr";
      }

    //set error handler
    set_error_handler("customError");

    //trigger error
    echo($test);
    ?>
    The output of the code above should be something like this:
    Error: [8] Undefined variable: test


    Trigger an Error
    In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.
    Example
    In this example an error occurs if the "test" variable is bigger than "1":
    <?php
    $test=2;
    if ($test>1)
    {
    trigger_error("Value must be 1 or below");
    }
    ?>
    The output of the code above should be something like this:
    Notice: Value must be 1 or below
    in C:\webfolder\test.php on line 6
    An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.
    Possible error types:
    • E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
    • E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted
    • E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally
    Example
    In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we will use our custom error handler and end the script:
    <?php
    //error handler function
    function customError($errno, $errstr)
      {
      echo "<b>Error:</b> [$errno] $errstr<br />";
      echo "Ending Script";
      die();
      }

    //set error handler
    set_error_handler("customError",E_USER_WARNING);

    //trigger error
    $test=2;
    if ($test>1)
      {
      trigger_error("Value must be 1 or below",E_USER_WARNING);
      }
    ?>
    The output of the code above should be something like this:
    Error: [512] Value must be 1 or below
    Ending Script
    Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.

    Error Logging
    By default, PHP sends an error log to the servers logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.
    Sending errors messages to yourself by e-mail can be a good way of getting notified of specific errors.
    Send an Error Message by E-Mail
    In the example below we will send an e-mail with an error message and end the script, if a specific error occurs:
    <?php
    //error handler function
    function customError($errno, $errstr)
      {
      echo "<b>Error:</b> [$errno] $errstr<br />";
      echo "Webmaster has been notified";
      error_log("Error: [$errno] $errstr",1,
      "someone@example.com","From: webmaster@example.com");
      }

    //set error handler
    set_error_handler("customError",E_USER_WARNING);

    //trigger error
    $test=2;
    if ($test>1)
      {
      trigger_error("Value must be 1 or below",E_USER_WARNING);
      }
    ?>
    The output of the code above should be something like this:
    Error: [512] Value must be 1 or below
    Webmaster has been notified
    And the mail received from the code above looks like this:
    Error: [512] Value must be 1 or below
    This should not be used with all errors. Regular errors should be logged on the server using the default PHP logging system.