Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Tuesday, October 20, 2009

Building a Java Desktop Database Application



This tutorial shows how to create a desktop Java application through which you canaccess and update a database. The tutorial takes advantage of support inNetBeans IDE for the following technologies:

  • The Java Persistence API (JPA), which helps you use Java code to interact with databases.

  • Beans Binding (JSR-295), which provides a way for different JavaBeans components
    to have property values that are synchronized with each other. For example, you can use beans
    binding to keep the values of cells in a JTable visual component in
    synch with the values of fields in an entity class. (In turn, the entity class
    represents the database table.)

  • The Swing Application Framework (JSR-296), which provides some useful
    building blocks for quickly creating desktop applications.



We will create a database CRUD (create, read, update, delete)
application with a custom component used for visualizing the data (car design preview).



This tutorial is largely based on a screencast that was based on a development build.
Some of the user interface has changed since that demo
was made, so you might notice some differences between this tutorial and the demo.
You can view the demo (about 9 minutes) now
or download a zip
of the demo
.


Setting Up the Database


Before you begin creating a desktop CRUD (create, read, update, delete) application
in the IDE, you should already have the IDE connected to the database that
your application will use. Having this connection set up in advance will
allow you to take advantage of IDE features that automate the binding of the
database to your application.



In this tutorial, we provide instructions for using a Java DB database, since
there is a convenient interface for starting and stop the Java DB database server from the IDE.
However, you can use a different database server without too much difficulty.


First verify that you have Java DB registered in the IDE.
Java DB is
automatically registered in the IDE in a number of cases, such as when
you have Sun Java System Application Server registered in the IDE
or when you are running on JDK 6. If Java DB is not registered in the IDE,
register it manually.



To verify whether Java DB is registered in NetBeans IDE 6.1:



  1. Open the Services window.

  2. Right-click the Databases > Java DB node and choose Properties.

    If Java DB is registered, the Java DB Installation and Database Location
    fields will be filled in.



    If Java DB is not registered, fill in the following two fields:



    • Java DB Installation. Enter the path to the database server.

    • Database Location. Enter the folder where you want the databases to be stored.


  3. Click OK.


To verify whether Java DB is registered in NetBeans IDE 6.0:



  1. Choose Tools > Java DB Database > Settings.

  2. If Java DB is registered, the Java DB Installation and Database Location
    fields will be filled in.


    If Java DB is not registered, fill in the following two fields:




    • Java DB Installation. Enter the path to the database server.

    • Database Location. Enter the folder where you want the databases to be stored.


  3. Click OK.



Starting the Server and Creating a Database



Once Java DB is registered with the IDE, you can easily start and stop
the database server, as well as create a new database.


To start the database server in NetBeans IDE 6.1:



  • In the Services window, right-click Databases > Java DB and
    choose Start Server.

    If you do not already have a location set for the database, the Set Database Location
    dialog box appears. Enter a location for the database server to store the databases. You can create
    a new folder there if you wish.





To start the database server in NetBeans IDE 6.0:



  • Choose Tools > Java DB Database > Start Server.

    If you do not already have a location set for the database, the Set Database Location
    dialog box appears. Enter a location for the database server to store the databases. You can create
    a new folder there if you wish.





Once the server is started, Java DB Database Process tab opens in the
Output window and displays a message similar the following:


Apache Derby Network Server - 10.2.2.0 - (485682) started and ready
to accept connections on port 1527 at 2007-09-05 10:26:25.424 GMT




To create the database in NetBeans IDE 6.1:




  1. In the Services window, right-click Databases > Java DB and
    choose Create Database.

  2. For the Database Name text field, type car_database. Also set the User Name and
    Password to nbuser.

  3. Click OK.



To create the database in NetBeans IDE 6.0:



  1. Choose Tools > Java DB Database > Create Database. The
    Create Java DB Database dialog opens.

  2. For the Database Name text field, type car_database. Also set the User Name and
    Password to nbuser.


  3. Click OK.



Connecting to the Database



So far, we have successfully started the the database server and created a database.
However, we still need to connect to the new database before we can
start working with it in the IDE. To connect to the car_database database:




  1. Switch to the Services window (Ctrl+5) and expand the Databases node to see
    your new database.


  2. Right-click the database connection node
    (jdbc:derby://localhost:1527/car_database[nbuser on NBUSER]) and choose
    Connect.

    The connection node icon should now appear whole (connection node icon), which signifies that the connection was successful.






  3. Expand the connection node, right-click its Tables subnode, and choose Execute Command.

  4. Copy the contents of the
    car.sql file
    and paste them into the SQL Command 1 tab of the Source Editor.

    This is the SQL script which will populate the database with data about cars.



  5. Click the Run SQL button (Run SQL button)in
    the toolbar of the Source Editor to run the script.




Creating the Application



  1. Choose File > New Project.

  2. In the first panel of the wizard, expand the Java category and select the Java Desktop Application template. Click Next.

    The Java Desktop Application template provides many basics of a visual application, including basic menu items and commands.



  3. In the Name and Location page of the wizard, do the following things:

    1. In the Project Name field, type CarsApp. The value of this field sets the display name for the project in the Projects window.

    2. Select the Set As Main Project checkbox.

    3. Optionally, edit the Project Location field to change the location of your project metadata.

    4. In the Choose Application Shell field, select Database Application.


    5. Click Next.


  4. In the Master Table page of the wizard, select the database connection for the CAR database.
    The listing for the database should look something like the following: jdbc:derby://localhost:1527/car_database[nbuser on NBUSER]

  5. Fill in the password (nbuser) for the database and select the
    Remember Password During This Session checkbox.

    After the connection to the database is established, the Database Table field
    should display CAR and
    the Columns to Include list should include the names of
    10 columns for the CAR database. For now, we will use only five of them in the application.

  6. Select the bottom five column names (beginning with
    SUN_ROOF and ending with MODERNNESS) and click the < button
    to move them to the left column. Click Next.

  7. In the Detail Options panel, click Finish.

    The wizard then generates the a basic user interface with a table and a
    database connection. This might take a few seconds as the IDE generates the
    project and the code..







Running the Generated Application


At this point, you have a basic running application with a
graphical user interface (GUI) that has the following features:



  • Ability to view and modify values in five columns of the CAR database.

  • Basic menu items.


  • Persistence of its window state between sessions. When you
    close the application, the window position and size are remembered. So
    when you reopen the application, the window opens in the same position as
    it was when you closed it.

  • An About dialog box, which you can easily customize.

  • .properties files containing the labels in the user interface. Using
    .properties files is a good way to keep the logic of your code separate from the
    text that appears in the user interface of your application. Such separation is useful
    for making it easier to localize your program, among other reasons.



To see some of the features that are already built into the application, follow these steps:



  1. Right-click the project's node and choose Run.

    After a few seconds, the application stars and a window called Database Application Example appears.
    This window contains a table and several controls that enable you to edit the CARS database.


  2. Select the first record in the table (for the Acura).

  3. Select the Price text field and replace the existing value with 46999. Then press Enter.

    The value should appear updated in the table. (However, that value will
    not be reflected in the database until you click Save.)



    Similarly, you can update any other values in the table.


  4. Click New to create a new record. Then fill in values for each of the fields (Make, Model, Price, Body Style, Color). For example, you can fill in
    Trabant, Classic, 1000, wagon, and blue. Click Save to
    save the entry in the database.

  5. Click the Database Application Example title bar and drag the application to a different place on your screen.


  6. Click the left border of the Database Application Example window and drag to the left to increase the size of the window.

  7. In the Database Application Example menu bar, choose File > Exit.

  8. In the IDE, right-click the project's node and choose Run Project.

    The Database Application Example window will open in the same size and position it was in when you
    closed the application.





Reviewing the Generated Parts of the Application



The connection between the master table (a JTable component) and the database is
handled with a combination of the following mechanisms, all of which have been
generated by the IDE:




  • The Car.java entity class, which is used to read and write data to
    the CAR database table. Entity classes are a special type of class
    that enable you to interact with databases through Java code.
    Entity classes use Java annotations to map class fields to database columns. .

  • The META-INF/persistence.xml file, which defines a connection between
    the database and the entity class. This file is also known as the persistence unit.


  • Using beans binding to connect the properties of the entity class
    with the properties of the JTable component. Beans binding is a new technology
    based on JSR 295 and which will probably be included in a future Java SE release.

  • The entityManager, query, and list
    objects, which are defined in the CarsAppFrame class and
    which are listed in the Inspector window.


    • The entity manager object is used to retrieve and commit data
      within the defined persistence unit scope.

    • The query object defines how the particular data collection is retrieved from
      the entity manager. (You can change the way that the query object works by selecting the
      query object in the Inspectory window and changing the query property in the property sheet.
      The query property uses JPA query language.

    • The list object is an observable collection that holds the data from the query. An
      observable collection is a special kind of collection on which you can place a listener to
      find out when changes to the collection have been made.






Using the Inspector window and the property sheet, you can follow these steps to see how
the JTable is bound to data:



  1. In the Inspector window, select the
    mainPanel[JPanel] > masterScrollPane [ScrollPane] > masterTable [JTable]
    node.
    Then click the Binding tab in the Properties window.


  2. Look at the elements property to confirm that it is bound to a list.

  3. Click the ellipsis [...] button to open the Bind masterTable.elements customizer, where you can
    further customize the binding between the table and the database. For example, you can see that the
    customizer enables you to specify which table columns are bound.


Besides the Binding category in property sheet you can also use the
Bind menu in context menu.





Adding More Controls



We will now add controls to the form for some of the attributes we initially excluded.
Instead of using a table, we will add JSlider components (for the tire size and
modernness attributes) and JCheckbox components (for the sun roof and the spoiler).

Follow these steps to add the additional components:


  1. Add the first slider by clicking the Slider button in the Palette window and
    then clicking in the form just above the New button. Before clicking in the form
    to insert the slider, make sure that no horizontal slotted guiding lines are shown.
    These lines indicate that the slider will be inserted in the same line as the
    fields or the buttons. See the figure below to see where you should drop the
    slider into the form.

    Note: If you drop the component in a place you do not want and thus
    cause several undesired layout changes, you can use the Undo command
    to reverse the changes. Choose Edit > Undo or press Ctrl-Z.




  2. If necessary, stretch the slider to the left to align it with the left side of the text field components.

  3. Stretch the slider to the
    right to span the whole form width.

  4. Add a label to the left of the slider and set its text to Tire Size.
    (Click the label to make it editable.)

  5. Add another slider below the first slider, and adjust its width and alignment where necessary.

  6. Add another label below the Tire Size label and set its text to Modernness.


  7. Add two checkboxes below the sliders. Set their text to Spoiler and Sun Roof.
    (Make the display text editable by clicking the checkbox once, pausing, and then clicking
    the checkbox again. You can also right-click the checkbox and choose Edit Text.)


The form should look like the screenshot shown below.



A screenshot of the design area with all controls added"

Binding Controls to Values in the Table



We will now use beans binding features to tie the values shown in table cells to
the state of the controls we have added. This will allow you to change the values
of cells in the table by using the sliders and checkboxes.



To bind the sliders to their corresponding table elements:



  1. In the form, right-click the Tire Size slider and choose Bind > value.

  2. In the Binding Source drop-down list of the Binding dialog box, select masterTable.


  3. In the Binding Expression drop-down list, select the selectedElement > tiresize node.



    "

  1. In the form, right-click the Modernness slider and choose Bind > value.

  2. In the Binding Source drop-down list of the Binding dialog box, select masterTable.


  3. In the Binding Expression drop-down list, select selectedElement > modernness.



To bind the checkboxes to their corresponding table elements:



  1. In the form, right-click the Spoiler checkbox and choose Bind > selected.


  2. In the Binding Source drop-down list of the Binding dialog box, select masterTable.

  3. In the Binding Expression drop-down list, select selectedElement > spoiler.

  4. Click OK to exit the Bind dialog box.


  5. In the form, right-click the Sun Roof checkbox and choose Bind > selected.


  6. In the Binding Source drop-down list of the Binding dialog box, select masterTable.

  7. In the Binding Expression drop-down list, select selectedRow > sunRoof.

  8. Click OK.




You should now be able to change database entries using the slider and
checkboxes.



To verify that the sliders and checkboxes work:



  1. Open the Services window.

  2. Make sure the IDE has a connection to the database by right-clicking
    Databases > jdbc:derby;//localhost:1527/car_database and choosing Connect.

  3. Right-click the Databases > jdbc:derby;//localhost:1527/car_database > Tables > node
    and choose View Data.


  4. Look at the SUN_ROOF, SPOILER, TIRE_SIZE, and MODERNNESS values
    for the first record.

  5. Choose Run > Run Main Project to execute the application.

    The running application should look similar to the screenshot shown below.



    "

  6. In the running application, select the first record.

  7. Move the sliders and change the checkbox selections.


  8. Click Save to save the changes into the database.

  9. In the Services window, use the View Data command again.

    The values in the database should reflect changes that you have made.




Wednesday, September 23, 2009

Hide .php extension with url rewriting using .htaccess

Using this technique you will see product.html in the address bar of the browser but the actual file name remains product.php and you don’t need to rename the file extension. Furthermore you can rewrite the URL like product.php?id=5 to product-5.html.

what is the benefits of rewriting URL?

When a search engine visits the dynamic url like product.php?id=5 it does not give much importance to that URL as search engine sees “?” sign treat it as a url which keeps on changing. so we’re converting the dynamic URL like the product.php?id=5 to static url format like product-5.html. We’ll rewrite the url in such a way that in browser’s address bar it will display as a product-5.html but it actually calls the file product.php?id=5. So that why these kind of URL also named as SEO friendly URL.

what is required for URL rewriting ??

To rewrite the URL you must have the mod_rewrite module must be loaded in apache server. And furthermore, FollowSymLinks options also need to be enabled otherwise you may encounter 500 Internal Sever Error. If you don’t know much about mod_rewrite module then please check this post to know how to check and enable mod_rewrite module in apache?
Examples of url rewriting for seo friendly URL

For rewriting the URL, you should create a .htaccess file in the root folder of your web directory. And have to put the following codes as your requirement.

1)Rewriting product.php?id=12 to product-12.html

It is a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.

RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1

2) Rewriting product.php?id=12 to product/ipod-nano/12.html

SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.

RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2

3) Redirecting non www URL to www URL

If you type yahoo.com in browser it will be redirected to www.yahoo.com. If you want to do same with your website then put the following code to .htaccess file. What is benefit of this kind of redirection?? Please check the post about SEO friendly redirect (301) redirect in php and .htaccess.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^optimaxwebsolutions\.com$
RewriteRule (.*) http://www.optimaxwebsolutions.com/$1 [R=301,L]

4) Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz

Have you checked zorpia.com.If you type http://zorpia.com/roshanbh233 in browser you can see my profile over there. If you want to do the same kind of redirection i.e http://yoursite.com/xyz to http://yoursite.com/user.php?username=xyz then you can add the following code to the .htaccess file.

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1

5) Redirecting the domain to a new subfolder of inside public_html.

Suppose the you’ve redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “test.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, www.test.com point out to the files inside “new” folder.

Saturday, August 15, 2009

A simple code to handle Time



$time="08:05:00"; //for sake of example .initial time
$curtime="01:05:00";//end time

$t=explode(':',$time);
$h=intval($t[0]);
$m=intval($t[1]);

$add=1;

while($ntime!=$curtime)
{
$h=intval($h);
$m=intval($m);
$m+=$add;

if($m>=60)
{
$h++;
$m=$m-60;
}
if($h>23)
$h=0;

if($h<10)
{
$h="0".$h;
}
if($m<10)
{
$m="0".$m;
}

$ntime=$h.":".$m.":00";
echo $ntime."
"; //it will echo each minute
}

Friday, July 31, 2009

How to Create a Wordpress Theme



This tutorial is especially for:

1. People interested in learning how to build a Wordpress theme from scratch or, more specifically, for those interested in taking an existing design and converting it into a beautifully working Wordpress theme.

2. People interested in integrating Wordpress with their existing website. As touched on lightly in my first tutorial, the best way to go about integration, in my experience, is to take your existing website and build a Wordpress theme out of it, then apply that theme to your Wordpress blog and voila, if all has gone well you have a perfect integration. It can require some handiness with CSS, but the principles covered in this tutorial will get you well on your way.

Sunday, July 19, 2009

How To Use PHP to Interact with MySQL

1. Introduction. This article will discuss how to connect PHP and MySQL, to create a dynamic database-driven website. I will assume that you already have a PHP and MySQL copy installed on your system and they all work. I will also assume that you have basic knowledge about PHP including PHP syntax and how to run a PHP script.

2. PHP and MySQL. PHP already includes a MySQL module in its distribution, so you won't need to install an additional software module.

3. Create MySQL user.

To create a username and password for your script execute the MySQL console application. You must login as root, then execute this SQL statement:

CREATE DATABASE db_test;
USE db_test;
CREATE TABLE tbl_phonebook
(
phone_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
phone_name VARCHAR(40),
phone_number VARCHAR(40),
INDEX phone_name_idx (phone_name),
INDEX phone_number_idx (phone_number)
);
GRANT SELECT,UPDATE,DELETE,INSERT TO db_test.*
TO 'test_user' IDENTIFIED BY 'test_user';

After you execute those SQL commands, MySQL will create a database called db_test which contains one table called tbl_phonebook. We will use this table for our sample web application.

4. Connecting to MySQL database.

To establish connection to a MySQL database, you need to call mysql_connect() or mysql_pconnect(). Basically they're all similar except the second one will create a persistent connection. A persistent connection is a connection that persists even if connection is closed.

$link=mysql_connect('localhost','test_user','test_user');
$persist_link=mysql_pconnect('localhost','test_user','test_user');
?>

mysql_pconnect() is faster than mysql_connect() because it eliminates overhead to establish a connection to the MySQL database. If mysql_pconnect() finds that a persistent connection is already available for a user, it will use it, otherwise it creates new connection.

Upon connection completion, mysql_connect() and mysql_pconnect() returns a handle to connection.


5. Selecting a database to use. To select database to use, use must call mysql_select_db(). This function requires a database name and optional handle of database connection. If you omit the handle of connection, it will use the currently open connection.

$link=mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test',$link);
?>

Selecting a database is an optional step, which you can skip. However, if you do skip it, you must include the database name and table name to access a table. For example, to access tbl_phonebook you must provide the complete name db_test.tbl_phonebook instead of tbl_phonebook. Please note, you must use a period to separate the database name and table name.

6. Execute SQL statement. After you have a valid connection and have selected an active database, you are ready to execute the SQL statement to do some data manipulation. To execute the SQL statement, use mysql_query() function.

This function requires at least one parameter, which is the SQL command you want to execute. The second paramater is the connection you want to use. This parameter is optional. If you omit it, the currently open connection is used. If there is no open connection, this function will try to establish a new connection.

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
mysql_query($sql);
?>

7. Inserting new data into the database. To insert a new record into the database, you must execute the INSERT statement. For example:

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="INSERT INTO tbl_phonebook
(
phone_name,
phone_number
)
VALUES
(
'Johny Greenwood' ,
'+6281455632112'
) ";
mysql_query($sql);
?>

For the INSERT operation, to know whether the execution succeeded or failed, we use value return by mysql_query(). It returns boolean value, i.e, TRUE if it succeeded or FALSE if it failed.

To know how what records were affected by the execution of this SQL command, we call mysql_affected_rows(). This function needs one optional connection parameter. If it is omitted then the curently open connection will be used. This function returns the number of rows affected.

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="INSERT INTO tbl_phonebook
(
phone_name,
phone_number
)
VALUES
(
'Johny Greenwood' ,
'+6281455632112'
) ";
mysql_query($sql);
print('Number of rows affected : '.mysql_affected_rows());
?>

8. Retrieving data from a database. To retrieve data from a database, we use SELECT command. This example was displayed previously. Here, we show it again.

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
mysql_query($sql);
?>

The above piece of code did nothing useful. To make data available for viewing, we must fetch rows. If we use mysql_query() for the SELECT operation, it will return resources to rows by the SELECT statement. To fetch data from this resource we use mysql_fetch_row(), mysql_fetch_assoc(), mysql_fetch_array() or mysql_fetch_object. Everytime mysql_fetch_***() is called, the database cursor is increment to the next data. If these return NULL, the cursor is at the end of file (EOF), so there is no more data to return.

mysql_fetch_rows() will fetch data and return data as a numeric array. For example:

Use of mysql_fetch_rows():

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
$res=mysql_query($sql);
if ($res)
{
while ($data=mysql_fetch_row($res))
{
print("

Name : ".$data[1]);
print("Phone : ".$data[2]."

");
}
mysql_free_result($res);
}
?>

Data from the phone_name field is returned in index number 1, because we selected all fields. So index 0 will contain data of phone_id field whereas phone_number field will be returned in index 2.

mysql_free_result() frees resources returned by mysql_query(). PHP automatically frees all resources when the script is finished, so calling mysql_free_result() is optional, but surely a good programming habit.

mysql_fetch_row() will fetch data and return data as an associative array. For example:

Use of mysql_fetch_assoc():

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
$res=mysql_query($sql);
if ($res)
{
while ($data=mysql_fetch_assoc($res))
{
print("

Name : ".$data['phone_name']);
print("Phone : ".$data['phone_number']."

");
}
mysql_free_result($res);
}
?>

Note that the name of the field is used to index the array.

mysql_fetch_array() is a combination of mysql_fetch_row() and mysql_fecth_assoc(). It returns a numeric array as well as an associative array.

mysql_fetch_object() fetches rows and returns data as an object. For example:

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="SELECT * FROM tbl_phonebook";
$res=mysql_query($sql);
if ($res)
{
while ($data=mysql_fetch_object($res))
{
print("

Name : ".$data->phone_name);
print("Phone : ".$data->phone_number."

");
}
mysql_free_result($res);
}
?>

To know how many rows have been returned by mysql_query(), you call mysql_num_rows(). It requires one parameter, i.e, resource returned by mysql_query().

$tot_record=mysql_num_rows($res);

9. Updating data. To update data you execute the UPDATE command.

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="UPDATE tbl_phonebook SET phone_number='0135928549' WHERE phone_id=1";
$res=mysql_query($sql);
if ($res)
{
print('Update succeed');
} else
print('Update failed');
?>

Similar to INSERT, the UPDATE command doesn't generate a result set but only the boolean value; TRUE if it succeeds of FALSE otherwise. To find out how many rows are affecteded by the UPDATE command, use mysql_affected_rows().


10. Removing data. To remove a record you can use the DELETE command:

mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test');
$sql="DELETE FROM tbl_phonebook WHERE phone_id=1";
$res=mysql_query($sql);
if ($res)
{
print('Phone ID =1 deleted');
} else
print('Unable to delete');
?>


11. Closing connection. To close what we have opened, we call mysql_close(). It requires an optional parameter, i.e. a connection to close. If we wanto to close the currently open connection, omit the optional parameter.

$link=mysql_connect('localhost','test_user','test_user');
mysql_select_db('db_test',$link);
$sql="SELECT * FROM tbl_phonebook";
$res=mysql_query($sql,$link);
if ($res)
{
while ($data=mysql_fetch_object($res))
{
print("

Name : ".$data->phone_name);
print("Phone : ".$data->phone_number."

");
}
mysql_free_result($res);
}
mysql_close($link);
?>


12. Conclusion. We have discussed basic steps to let PHP interact with MySQL, including how to establish a database connection, how to select an active database, and how to execute an SQL command.

Learn PHP on 15 Minutes

Step 1:

To be able to execute PHP scripts, you need at least a working PHP installation+ web server. Linux, Apache, MySQL and PHP are the best combinations. PHP also can run under Microsoft Windows, too.

PHP installation and configuration can be made easy with tools such as Apache2Triad or XAMPP which automate web server and PHP installation.

PHP script is stored in text format file so you need text editor. Notepad and Notepad++ are enough for your PHP development needs. However, you may opt to invest in more advanced tools such Dreamweaver or Eclipse.
Step 2:

PHP script is anything between pair. You can also use . The first is most widely used.




print '

Hello this is my first script

';
?>



Output of the following code will be same as the previous code:

print '


Hello this is my first script

';
?>

Step 3:

The power of PHP lies on the capability to change how HTML code will output. The following code will output different HTML codes when you change the name.




$aname=$_GET['name'];
print '

Hello '.$name.' this is my first script

'; ?>




Save this script as welcome.php in the document root directory (for Apache web server, this is usually htdocs directory). Open your web browser and type http://localhost/welcome.php?name=Zamrony

Step 4:

$_GET is a predefined variable which stores lists of parameters passed to the script. It is an array. If you change http://localhost/welcome.php?name=zamrony&country=Indonesia, $_GET will contain more items.




$aname=$_GET['name'];
$acountry=$_GET['country'];
print '

Hello '.$name.' from '.$acountry.' .
this is my first PHP script

';
?>



It will print Hello Zamrony from Indonesia. This is my first PHP script.

Step 5:

$aname, $acountry and $_GET are all variables in PHP. Any variables in PHP should be prefixed with dollar sign. Variable names must only contain alphanumeric and underscore characters where the first character in variable names should be alphabet characters or underscores.

This is invalid variable name:

$123
$1aname
$*jskk

This is valid variable name:

$k123
$j
$_
$_test
$k123k
$KK


PHP is case sensitive. Variable $kk is not $KK.

Tuesday, July 14, 2009

Quick C# in 20 mins




Introduction

C# is a language with the features of C++, programming style like Java and rapid application model of BASIC. If you already know the C++ language, it will take you less than an hour to quickly go through the syntax of C#. Familiarity with Java will be a plus, as Java program structure, the concept of packages and garbage collection will definitely help you learn C# more quickly. So while discussing C# language constructs, I will assume, you know C++.
This article discusses the C# language constructs and features using code examples, in a brief and comprehensive way, so that you just by having a glance at the code, can understand the concepts.

Note: This article is not for C# gurus. There must be some other beginner's articles on C#, but this is yet another one.

Following topics of C# language are discussed:

• Program structure
• Namespaces
• Data types
• Variables
• Operators and expressions
• Enumerations
• Statements
• Classes and structs
• Modifiers
• Properties
• Interfaces
• Function parameters
• Arrays
• Indexers
• Boxing and unboxing
• Delegates
• Inheritance and polymorphism


Following are not discussed:

• Things which are common in C++ and C#.
• Concepts like garbage collection, threading, file processing etc.
• Data type conversions
• Exception handling
• .NET library

Program structure

Like C++, C# is case-sensitive. Semi colon (;) is the statement separator. Unlike C++, there are no separate declaration (header) and implementation (CPP) files in C#. All code (class declaration and implementation) is placed in one file with extension cs.
Have a look at this Hello world program in C#.


using System;

namespace MyNameSpace

{

class HelloWorld

{
static void Main(string[] args)
{
Console.WriteLine ("Hello World");
}
}

}

Everything in C# is packed into a class and classes in C# are packed into namespaces (just like files in a folder). Like C++, a main method is the entry point of your program. C++'s main function is called main whereas C#'s main function starts with capital M and is named as Main.
No need to put a semi colon after a class block or struct definition. It was in C++, C# doesn't require that.

Namespace

Every class is packaged into a namespace. Namespaces are exactly the same concept as in C++, but in C# we use namespaces more frequently than in C++. You can access a class in a namespace using dot (.) qualifier. MyNameSpace is the namespace in hello world program above.
Now consider you want to access the HelloWorld class from some other class in some other namespace.

using System;
namespace AnotherNameSpace
{
class AnotherClass
{
public void Func()
{
Console.WriteLine ("Hello World");
}
}
}

Now from your HelloWorld class you can access it as:

using System;
using AnotherNameSpace; // you will add this using statement
namespace MyNameSpace
{
class HelloWorld
{
static void Main(string[] args)
{
AnotherClass obj = new AnotherClass();
obj.Func();
}
}
}

In .NET library, System is the top level namespace in which other namespaces exist. By default there exists a global namespace, so a class defined outside a namespace goes directly into this global namespace and hence you can access this class without any qualifier.
You can also define nested namespaces.
Using

The #include directive is replaced with using keyword, which is followed by a namespace name. Just as using System as above. System is the base level namespace in which all other namespaces and classes are packed. The base class for all objects is Object in the System namespace.


Variables

Variables in C# are almost the same as in C++ except for these differences:

1. Variables in C# (unlike C++), always need to be initialized before you access them, otherwise you will get compile time error. Hence, it's impossible to access an un-initialized variable.
2. You can't access a “dangling” pointer in C#.
3. An expression that indexes an array beyond its bounds is also not accessible.
4. There are no global variables or functions in C# and the behavior of globals is achieved through static functions and static variables.

Data types

All types of C# are derived from a base class object. There are two types of data types:

1. Basic/ built-in types
2. User-defined types

Following is a table which lists built-in C# types:

Type Bytes Description
byte 1 unsigned byte
sbyte 1 signed byte
short 2 signed short
ushort 2 unsigned short
int 4 signed integer
uint 4 unsigned integer
long 8 signed long
ulong 8 unsigned long
float 4 floating point number
double 8 double precision number
decimal 8 fixed precision number
string Unicode string
char Unicode char
bool true, false boolean

Note: Type range in C# and C++ are different, example, long in C++ is 4 bytes, and in C# it is 8 bytes. Also the bool and string types are different than those in C++. bool accepts only true and false and not any integer.

User defined types includes:

1. Classes
2. Structs
3. Interfaces

Memory allocation of the data types divides them into two types:

1. Value types
2. Reference types

Value types

Values types are those data types which are allocated in stack. They include:
• All basic or built-in types except strings
• Structs
• Enum types

Reference types

Reference types are allocated on heap and are garbage collected when they are no longer being used. They are created using new operator, and there is no delete operator for these types unlike C++ where user has to explicitly delete the types created using delete operator. In C#, they are automatically collected by garbage collector.
Reference types include:
• Classes
• Interfaces
• Collection types like Arrays
• String

Enumeration

Enumerations in C# are exactly like C++. Defined through a keyword enum.
Example:

enum Weekdays
{
Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
}

Classes and structs

Classes and structs are same as in C++, except the difference of their memory allocation. Objects of classes are allocated in heap, and are created using new, where as structs are allocated in stack. Structs in C# are very light and fast data types. For heavy data types, you should create classes.
Examples:

struct Date
{
int day;
int month;
int year;
}

class Date
{
int day;
int month;
int year;
string weekday;
string monthName;
public int GetDay()
{
return day;
}
public int GetMonth()
{
return month;
}
public int GetYear()
{
return year;
}
public void SetDay(int Day)
{
day = Day ;
}
public void SetMonth(int Month)
{
month = Month;
}
public void SetYear(int Year)
{
year = Year;
}
public bool IsLeapYear()
{
return (year/4 == 0);
}
public void SetDate (int day, int month, int year)
{
}
...
}

Properties

If you are familiar with the object oriented way of C++, you must have an idea of properties. Properties in above example of Date class are day, month and year for which in C++, you write Get and Set methods. C# provides a more convenient, simple and straight forward way of accessing properties.
So above class can be written as:

using System;
class Date
{
public int Day{
get {
return day;
}
set {
day = value;
}
}
int day;

public int Month{
get {
return month;
}
set {
month = value;
}
}
int month;

public int Year{
get {
return year;
}
set {
year = value;
}
}
int year;

public bool IsLeapYear(int year)
{
return year%4== 0 ? true: false;
}
public void SetDate (int day, int month, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
}

Here is the way you will get and set these properties:
class User
{
public static void Main()
{
Date date = new Date();
date.Day = 27;
date.Month = 6;
date.Year = 2003;
Console.WriteLine
("Date: {0}/{1}/{2}", date.Day, date.Month, date.Year);
}
}

Modifiers

You must be aware of public, private and protected modifiers that are commonly used in C++. I will here discuss some new modifiers introduced by C#.
readonly
readonly modifier is used only for the class data members. As the name indicates, the readonly data members can only be read, once they are written either by directly initializing them or assigning values to them in constructor. The difference between the readonly and const data members is that const requires you to initialize with the declaration, that is directly. See example code:

class MyClass
{
const int constInt = 100; //directly
readonly int myInt = 5; //directly
readonly int myInt2;

public MyClass()
{
myInt2 = 8; //Indirectly
}
public Func()
{
myInt = 7; //Illegal
Console.WriteLine(myInt2.ToString());
}

}

sealed
sealed modifier with a class don't let you derive any class from it. So you use this sealed keyword for the classes which you don't want to be inherited from.
Collapse Copy Code
sealed class CanNotbeTheParent
{
int a = 5;
}


unsafe

You can define an unsafe context in C# using unsafe modifier. In unsafe context, you can write an unsafe code, example: C++ pointers etc. See the following code:
Collapse Copy Code
public unsafe MyFunction( int * pInt, double* pDouble)
{
int* pAnotherInt = new int;
*pAnotherInt = 10;
pInt = pAnotherInt;
...
*pDouble = 8.9;
}

Interfaces
If you have an idea of COM, you will immediately know what I am talking about. An interface is the abstract base class containing only the function signatures whose implementation is provided by the child class. In C#, you define such classes as interfaces using the interface keyword. .NET is based on such interfaces. In C#, where you can't use multiple class inheritance, which was previously allowed in C++, the essence of multiple inheritance is achieved through interfaces. That's your child class may implement multiple interfaces.

using System;
interface myDrawing
{
int originx
{
get;
set;
}
int originy
{
get;
set;
}
void Draw(object shape);
}

class Shape: myDrawing
{
int OriX;
int OriY;

public int originx
{
get{
return OriX;
}
set{
OriX = value;
}
}
public int originy
{
get{
return OriY;
}
set{
OriY = value;
}
}
public void Draw(object shape)
{
... // do something
}

// class's own method
public void MoveShape(int newX, int newY)
{
.....
}

}


Arrays

Arrays in C# are much better than C++. Arrays are allocated in heap and thus are reference types. You can't access an out of bound element in an array. So C# prevents you from that type of bugs. Also some helper functions to iterate array elements are provided. foreach is the statement for such iteration. The difference between the syntax of C++ and C# array is:
• The square brackets are placed after the type and not after the variable name
• You create element locations using new operator.
C# supports single dimensional, multi dimensional, and jagged arrays (array of array).
Examples:

int[] array = new int[10]; // single-dimensional array of int
for (int i = 0; i < array2 =" new" array3 =" new" arrayofarray =" new" style="font-weight: bold;">Indexers

Indexer is used to write a method to access an element from a collection, by straight way of using [], like an array. All you need is to specify the index to access an instance or element. Syntax of Indexer is same as that of class properties, except they take the input parameter, that is the index of the element.
Example:
Note: CollectionBase is the library class used for making collections. List is the protected member of CollectionBase which stores the collection list.

class Shapes: CollectionBase
{
public void add(Shape shp)
{
List.Add(shp);
}

//indexer
public Shape this[int index]
{
get {
return (Shape) List[index];
}
set {
List[index] = value ;
}
}
}

Boxing/Unboxing

The idea of boxing is new in C#. As mentioned above, all data types, built-in or user defined, are derived from a base class object in the System namespace. So the packing of basic or primitive type into an object is called boxing, whereas the reverse of this known as unboxing.
Example:

class Test
{
static void Main()
{
int myInt = 12;
object obj = myInt ; // boxing
int myInt2 = (int) obj; // unboxing
}
}

Example shows both boxing and unboxing. An int value can be converted to object and back again to int. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box. Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.

Function parameters

Parameters in C# are of three types:
1. By-Value/In parameters
2. By-Reference/In-Out parameters
3. Out parameters

If you have an idea of COM interface and it's parameters types, you will easily understand the C# parameter types.

By-Value/In parameters

The concept of value parameters is same as in C++. The value of the passed value is copied into a location and is passed to the function.
Example:

SetDay(5);
...
void SetDay(int day)
{
....
}

By-Reference/In-Out parameters

The reference parameters in C++ are passed either through pointers or reference operator &. In C# reference parameters are less error prone. Reference parameters are also called In-Out parameters because you pass a reference address of the location, so you pass an input value and get an output value from that function.
You can not pass an un-initialized reference parameter into a function. C# uses a keyword ref for the reference parameters. You also have to use keyword ref with an argument while passing it to a function demanding reference parameter.

Example:

int a= 5;
FunctionA(ref a); // use ref with argument or you will get compiler error
Console.WriteLine(a); // prints 20

void FunctionA(ref int Val)
{
int x= Val;
Val = x* 4;
}

Out parameter

Out parameter is the parameter which only returns value from the function. The input value is not required. C# uses a keyword out for the out parameters
Example:

int Val;
GetNodeValue(Val);
Collapse Copy Code
bool GetNodeValue(out int Val)
{
Val = value;
return true;
}

Variable number of parameters and arrays

Arrays in C# are passed through a keyword params. An array type parameter should always be the right most argument of the function. Only one parameter can be of array type. You can pass any number of elements as an argument of type of that array. You can better understand it from example below:

Note: This is the only way C# provides for optional or variable number of parameters, that is using array.

Example:

void Func(params int[] array)
{
Console.WriteLine("number of elements {0}", array.Length);
}

Collapse Copy Code
Func(); // prints 0
Func(5); // prints 1
Func(7,9); // prints 2
Func(new int[] {3,8,10}); // prints 3
int[] array = new int[8] {1,3,4,5,5,6,7,5};
Func(array); // prints 8

Operators and expressions

Operators are exactly the same as of C++ and thus the expression also. However some new and useful operators are also added. Some of them are discussed here.

is operator
is operator is used to check whether the operand types are equal or convert-able. The is operator is particularly useful in the polymorphism scenarios. is operator takes two operands and the result is a boolean. See the example:

void function(object param)
{
if(param is ClassA)
//do something
else if(param is MyStruct)
//do something
}
}

as operator
as operator checks if the type of the operands are convert-able or equal (as is done by is operator) and if it is, the result is a converted or boxed object (if the operand can be boxed into the target type, see boxing/unboxing). If the objects are not convert-able or box-able, the return is a null. Have a look at the example below to better understand the concept.

Shape shp = new Shape();
Vehicle veh = shp as Vehicle; // result is null, types are not convertable

Circle cir = new Circle();
Shape shp = cir;
Circle cir2 = shp as Circle; //will be converted

object[] objects = new object[2];
objects[0] = "Aisha";
object[1] = new Shape();

string str;
for(int i=0; i&< str =" objects[i]" str ="="" style="font-weight: bold;">Output:

Aisha
can not be converted
Statements
Statements in C# are just like in C++ except some additions of new statements and modifications in some statements.
Followings are new statements:
foreach
For iteration of collections like arrays etc.
Example:

foreach (string s in array)
Console.WriteLine(s);

lock
Used in threads for locking a block of code making it a critical section.
checked/unchecked
The statements are for overflow checking in numeric operations.
Example:

int x = Int32.MaxValue; x++; // Overflow checked
{
x++; // Exception
}
unchecked
{
x++; // Overflow}
}

Following statements are modified:
Switch

Switch statement is modified in C#.
1. Now after executing a case statement, program flow can not jump to next case which was previously allowed in C++.
Example:

int var = 100;
switch (var)
{
case 100: Console.WriteLine(""); // No break here
case 200: Console.WriteLine(""); break;
}

Output in C++:


In C# you get compile time error:

error CS0163: Control cannot fall through
from one case label ('case 100:') to another

2. However you can do this similar to how you do it in C++:

switch (var)
{
case 100:
case 200: Console.WriteLine("100 or 200"); break;
}

3. You can also use constant variables for case values:
Example:

const string WeekEnd = "Sunday";
const string WeekDay1 = "Monday";

....

string WeekDay = Console.ReadLine();
switch (WeekDay )
{
case WeekEnd: Console.WriteLine("It's weekend!!"); break;
case WeekDay1: Console.WriteLine("It's Monday"); break;

}

Delegates

Delegates let us store function references into a variable. In C++, this is like using and storing function pointer for which we usually use typedef.
Delegates are declared using a keyword delegate. Have a look at this example, and you will understand what delegates are:
Example:

delegate int Operation(int val1, int val2);
public int Add(int val1, int val2)
{
return val1 + val2;
}
public int Subtract (int val1, int val2)
{
return val1- val2;
}

public void Perform()
{
Operation Oper;
Console.WriteLine("Enter + or - ");
string optor = Console.ReadLine();
Console.WriteLine("Enter 2 operands");

string opnd1 = Console.ReadLine();
string opnd2 = Console.ReadLine();

int val1 = Convert.ToInt32 (opnd1);
int val2 = Convert.ToInt32 (opnd2);

if (optor == "+")
Oper = new Operation(Add);
else
Oper = new Operation(Subtract);

Console.WriteLine(" Result = {0}", Oper(val1, val2));
}

Inheritance and polymorphism

Only single inheritance is allowed in C#. Multiple inheritance can be achieved using interfaces.
Example:
Collapse Copy Code
class Parent{
}

class Child : Parent

Virtual functions

Virtual functions to implement the concept of polymorphism are same in C#, except you use the override keyword with the virtual function implementation in the child class. The parent class uses the same virtual keyword. Every class which overrides the virtual method will use override keyword.

class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}

class Rectangle : Shape

{
public override void Draw()
{
Console.WriteLine("Rectangle.Draw");
}
}

class Square : Rectangle
{
public override void Draw()
{
Console.WriteLine("Square.Draw");
}
}
class MainClass
{
static void Main(string[] args)
{
Shape[] shp = new Shape[3];
Rectangle rect = new Rectangle();

shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();

shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
}
}

Output:
Shape.Draw
Rectangle.Draw
Square.Draw
Hiding parent functions using "new"
You can define in a child class a new version of a function, hiding the one which is in base class. A keyword new is used to define a new version. Consider the example below, which is a modified version of above example and note the output this time, when I replace the keyword override with a keyword new in Rectangle class.

class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}

class Rectangle : Shape
{
public new void Draw()
{
Console.WriteLine("Rectangle.Draw");
}
}
class Square : Rectangle
{
//wouldn't let u override it here
public new void Draw()
{
Console.WriteLine("Square.Draw");
}
}
class MainClass
{
static void Main(string[] args)
{
Console.WriteLine("Using Polymorphism:");
Shape[] shp = new Shape[3];
Rectangle rect = new Rectangle();

shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();

shp[0].Draw();
shp[1].Draw();
shp[2].Draw();

Console.WriteLine("Using without Polymorphism:");
rect.Draw();
Square sqr = new Square();
sqr.Draw();
}
}

Output:
Using Polymorphism
Shape.Draw
Shape.Draw
Shape.Draw
Using without Polymorphism:
Rectangle.Draw
Square.Draw

See how the polymorphism doesn't take the Rectangle class's Draw method as a polymorphic form of the Shape's Draw method, instead it considers it a different method. So in order to avoid the naming conflict between parent and child, we have used new modifier.
Note: you can not use in the same class the two versions of a method, one with new modifier and other with override or virtual. Like in above example, I can not add another method named Draw in Rectangle class which is a virtual or override method. Also in the Square class, I can't override the virtual Draw method of Shape class.
Calling base class members
If the child class has the data members with same name as that of base class, in order to avoid naming conflicts, base class data members and functions are accessed using a keyword base. See in examples how the base class constructors are called and how the data members are used.

public Child(int val) :base(val)
{
myVar = 5;
base.myVar;
}

OR

public Child(int val)
{
base(val);
myVar = 5 ;
base.myVar;
}

Future additions

This article is just a quick overview of the C# language so that you can just become familiar with the language features. Although I have tried to discuss almost all the major concepts in C# in a brief and comprehensive way with code examples, yet I think there is lot much to be added and discussed.

In future, I would like to add more commands and concepts not yet discussed, including events etc. I would also like to write for beginners, about Windows programming using C#.

References:

• Our most commonly known MSDN
• Inside C# by Tom Archer
• A Programmer's Introduction to C# by Eric Gunnerson
• Beginning C# by Karli Watson
• Programming C# (O'Reilly)