Showing posts with label php for beginners. Show all posts
Showing posts with label php for beginners. Show all posts

02 June 2011

Creating a connection to MySQL in PHP - Php For Beginners - Lesson 11

Whenever we want to access the data in the mysql database using php, we have to create a connection to that particular database. Once the connection is establish we can insert and retrieve any data from the mysql database.

Creating a Mysql connection is quite simple in php, a simple built-in php function "mysql_connect()" is used for this purpose.

Syntax:
mysql_connect(servername,username,password); 
Where servername is the name of the server to connect, username and password are the credentials used to connect to the database.

Selecting a Database:
Once a connection is established to the database, we have to select the particular database that we want to use for inserting and fetching the data. This can be done by using another built-in php function "mysql_select_db()".
Syntax:
mysql_select_db(database,connection)
Where database is the name of the database and connection is the connection created in the earlier part of this article.

Working Example:
Since connecting and selecting the database is required each time we want to use a database. So we can save the code for creating the connection and selecting the database in a file and include it wherever we want to use the database. You can name that file as "connection.php" or whatever other name you want. Contents of this file are as follows:
<?php
$db_host="localhost";
$db_user="root";
$db_pass="";
$db_name="any_db";

$con=mysql_connect($db_host,$db_user,$db_pass) or die ('Can not connect to database');
mysql_select_db($db_name,$con) or die ('Can not Select Database');
?>
If you are using this code on the local server then the above mentioned configuration will work fine, as the default host/server name is always "localhost", user name is always "root" and password is always "" for the local server, but if you are using it on some web server then you have to change these settings to your web server's settings. The db_name is the name of the database that you want to select.

Well I guess this is all for this lesson, for any queries, should you have, feel free to comment and ask.

next Previous Lesson

26 May 2011

Mysql Introduction - Php For Beginners - Lesson 10

Databases are very important in the field of web development. A database is a collection of data in a very organized fashion. By organized fashion it is meant that the data will be stored in different tables. So that it will be easier to retrieve the date when needed. The most common database used with php is Mysql. Mysql is a relational database. A relational database is one in which tables are linked together.

What is a Table?
A table is an structure in which the datat is stored, It can contain rows and columns. Columns are used to categorize the data and rows contain the actual data. For example if a company contains its user's data in a table named 'Users' then the table structure may look like this:


User Id User Name Email Password
1 John john@example.com 123
2 Smith smith@example.com 456

In the above example, A company's users table is shown, it contains 4 columns and 2 rows. 4 columns are the categories and 2 rows are actual data. It is not mandatory that each row contains all the columns, some times rows can contain empty columns.

What is a Query?
A query is an statement used to manipulate the data in the database. You can write queries to Insert, retrieve, delete, and update the data and also to perform any action on the data present in the database.A sample query may look like this:
SELECT email FROM users
The above statement is used to retrieve all the emails from the users table. So the output of the above query will be like this:

Email
john@example.com
smith@example.com

Well I guess that's all for the introduction, further details will be discussed in the later lessons. For any queries or questions should you have, feel free to comment.

next Previous Lesson --- Next Lesson next

27 February 2011

Sessions in Php - Php For Beginners (Lesson 9)

What are sessions variables?
Session variables are just like normal variables except the fact that session variables are used to access some particular data across multiple pages. For example if you want to build a login system then in order to check whether the user is logged in or not you have to use session variables. You may store the user id in the session variable for each user at the time of signin/signup and then use the value of this session variable across different pages of members area.

How to use session variables in php?
In php if you want to use session variables then first of all you should start the session. This can be done by adding the following code at the start of each page where you want to use session variables:
<?php 
session_start(); 
?>
After adding the above mentioned code at the start of each page you are all set for using session variables. Session variables in php can be easily declared using the following code:
<?php
$_SESSION['user_id']=1234; 
?>
After the declaration of session variables you can access the value of these variables on any page using the following code:
<?php
echo $_SESSION['user_id']; 
?>
Now that you know how to declare and use session variables you should know how to remove values from session variables. Removing a value from any session variable is very simple, you can use following code:
<?php
unset($_SESSION['user_id']); 
?>
But the above code will only remove the value of one session variable, now if you have declared many session variables and you want to delete them all at once then you can do this by completely destroying the session. This can be done by using the following code:
<?php
session_destroy(); 
?>
Ok guyz I guess that is all about session variables in php. If you have any queries or suggestions then please feel free to comment.

Note: Dont forget to start the session at the beginning of each page.


next Previous Lesson --- Next Lesson next

13 January 2011

Php For Beginners (Lesson 8)

In this lesson we will discuss functions in php. A function is a block of code which is declared once on a page and then used each time it is needed in the script. For example if you are using some piece of code repetitively in your script then you can declare a function and place that code in the function. Now each time you need to use that code you don’t need to write the whole code again, instead you just call the function and your code will be called automatically.

There are two types of functions:

· Built-in Functions

· User Defined functions

Built-in Functions
Built-in Functions are those functions which are stored by default in php. Php has 700 built-in functions.

Example

  • strtolower(); Converts string to lowercase
  • strtoupper(); Converts string to upper case
  • exit(); Stops the execution of script

User Defined Functions
User defined functions are thoses functions which are declared by users for their own use.

Creating a function in php

A function should always be declared before it is going to be called.

Syntax

Function func_name (parameter1,parameter2,…..,parametern)

{ code to be executed. }

Example 1 (Function without parameters)

In this example we will create a function that takes no parameters and returns no value. This function will only prints our name on the screen.
<?php 
function display_name () 
{ 
   echo "Bill"; 
} 
echo "Hi there! My name is "; 
display_name(); 
?> 
The output of the above example will be “Hi there! My name is Bill”.

Example 2 (Function with parameters)

In this example we will create a function with a parameter. This function will take name as parameter when it is called an then display that name on the screen.
<?php 
function display_name ($name) 
{ 
   echo $name; 
} 
echo "Hi there! My name is "; 
display_name('Bill'); 
echo " and my brother's name is "; 
display_name('Jack'); 
?> 
The output of the above example will be “Hi there! My name is Bill and my brother's name is Jack”.

Example 3 (Function which returns value)

In this example we will create a function which returns some value. This function will take two numbers as parameter and returns the average.
<?php 
function average($num1,$num2) 
{ 
   $result=($num1 + $num2)/2; 
   return $result; 
} 
echo "The Average of 20 & 100 is ".average('20','100'); 
?> 
The output of this example will be “The Average of 20 & 100 is 60”.

Ok guys this is all about the functions in php. For any queries feel free to comment.


next Previous Lesson --- Next Lesson next

11 January 2011

Php For Beginners (Lesson 7)

In this lesson we will discuss loops in php. Loops are used to run a piece of code for a certain number of times. Php supports four types of loops:

  1. While Loop
  2. Do-While Loop
  3. For Loop
  4. Foreach Loop

While Loop

Syntax

While (condition)
{ code to be executed. }

Example
<?php 
$count=0; 
while ($count!=10) 
{ 
      echo $count."\n"; 
      $count++; 
} 
?>
The output of the above example will be counting from 0 to 9.

Do-While Loop

Syntax

Do
{ Code to be executed. }
While (condition)

Example
<?php 
$count=0; 
do 
{ 
      echo $count."\n"; 
      $count++; 
} 
while ($count!=10) 
?>
The output of the above example will be counting from 0 to 9.

For Loop

Syntax

for (initialize; condition; increment)
{ code to be executed. }

Example
<?php 
for ($i=0; $i<=10; $i++) 
{ 
      echo $count."\n"; 
} 
?>
The output of the above example will be counting from 0 to 10.

Foreach Loop

Syntax

foreach ($array as $value)
{ code to be executed. }

Example
<?php 
$count=array(0,1,2,3,4,5,6,7,8,9); 
foreach ($count as $value) 
{ 
   echo $value . "\n"; 
} 
?>
The output of the above example will be counting from 0 to 9.

References

http://www.php.net
http://www.w3schools.com

Ok guyz this is all for loops in php, keep practicing and for any queries don’t hesitate to comment and ask.


next Previous Lesson --- Next Lesson next

10 January 2011

Php For Beginners (Lesson 6)

In this lesson we will be discussing array variables, array variables are just like ordinary variables except that an array variable can store multiple values in one single variable.

For example if you want to store names of 5 students then you need to have 5 variables. What if students total exceeds 500? Then you will need 500+ variables to store those names. In such situations we will use a single array variable to store the names of all the students.

Array variables have indexes associated with each value, so that the values can be easily accessed using their respective indexes. These indexes can be numeric as well as strings.

Numeric Index Array

Example
<?php 
$student_name[0]=”Bill”; 
$student_name[1]=”Max”; 
$student_name[2]=”John”; 
$student_name[3]=”Smith”; 
echo $student_name[0].” And ”.$student_name[3].” Are good students”; 
?>
The output of above example will be “Bill and Smith Are good students”.

String Index Array

Example
<?php 
$marks[‘bill’]=”96”; 
$marks[‘max’]=”32”; 
$marks[‘john’]=”54”; 
$marks[‘smith’]=”78”; 
echo “Bill secured ”.$marks[‘bill’].” marks”; 
?>
The output of above example will be “Bill secured 96 marks”.

Multidimensional Array

In multidimensional array each element of the main array can also be an array and each element in that array may be an array too, and so on.

Example
<?php 
$students=Array
(
[‘Bill’] => Array
(
[0] => 78
[1] => 86
[2] => 92
)
[‘Max’] => Array
(
[0] => 45
)
[‘John’] => Array
(
[0] => 76
[1] => 63
[2] => 78
)
); 
echo “Bill secured ”.$students[‘Bill’][2].” marks”; 
?>
The output of the above example will be “Bill secured 92 marks”.

References

http://www.php.net
http://www.w3schools.com

I guess we have discussed all the fundamental concepts of array variables, in case of any queries please feel free to comment on this post.


next Previous Lesson --- Next Lesson next

09 January 2011

Php For Beginners (Lesson 5)

In this lesson we will be discussing conditional statements. Conditional statements are used when you want to relate an action with some condition. Php supports four types of conditional statements:

If Statement

Syntax

if (condition)
{ code to be executed }

Example
<?php
$a=5;
if ($a==5)
{
   echo “five”; // outputs “five”
} 
?>
If – else Statement

Syntax

if (condition)
{ code to be executed }
else { code to be executed }

Example
<?php
$a=5;
if ($a==5)
{
   echo “five”; // outputs “five”
}else
{ 
   echo “not five”;
}
?>
If – elseif – else Statement

Syntax

if (condition)
{ code to be executed }
elseif (condition)
   { code to be executed }
else { code to be executed }

Example
<?php
$a=2;
if ($a==5)
{
   echo “five”; 
}elseif ($a==6)
{
   echo “six”; 
}
else 
{ 
   echo “neither five nor six”;  // outputs “neither five nor six”
}
?>
Switch Statement

Syntax

switch (variable)
{
case test1:
  code to be executed if variable =test1;
  break;
case test2:
  code to be executed if variable =test2;
  break;
default:
  code to be executed if n is different from both test1 and test2;


Example
<?php
$a=2;
switch ($a)
{
case 5:
  echo “five”;
  break;
case 2:
  echo “two”; // outputs “two”
  break;
default:
  echo “neither five nor two”;
}  
?>
The switch statement takes variable as an argument and then code to be executed for each case. Whichever condition will be true it will execute its code and if no condition is true then it will execute the default code.

References

http://www.php.net
http://www.w3schools.com

This is all for the fifth lesson, now all you need to do is practice these concepts and if you have any queries then feel free to comment on this post.


next Previous Lesson --- Next Lesson next

08 January 2011

Php For Beginners (Lesson 4d)

If you are reading this lesson then I assume that you have read all of my previous lessons, so coming directly to the point, I will be discussing logical operators and their usage in php.

And Operator (&&)
"&&" operator is used to take the union of two or more conditions and returns true if and only if all the conditions are true.
<?php
$a=5;
$b=6;
if ($a==5 && $b==6)
    echo "true"; //Outputs true
?>
Or Operator (||)
"||" operator returns true if any of the condition is true.
<?php
$a=5;
$b=6;
if ($a==5 || $b==5)
   echo "true"; //Outputs true 
?>
Not Operator (!)
"!" operator returns true when no condition is true.
<?php
$a=5;
$b=6;
if !($a==$b)
   echo "true"; //Outputs true
?> 
Well that is all we need to know about Operators in php, keep reading and feel free to ask questions through comments.


next Previous Lesson --- Next Lesson next

07 January 2011

Php For Beginners (Lesson 4c)

In this lesson i will be discussing comparison operators and their applications in php.

== Operator

"==" operator is used for comparing two values or variables and return true if they are same.
<?php
$a=5;
if ($a==5)
   echo "Five";  //Outputs Five
?>
!= and <> Operator

"!=" and "<>" operators are also used for comparing two values or variables but they return true if the values are not same.
<?php
$a=5;
if ($a!=4)
   echo "Four";  //Outputs Four
if ($a<>4)
   echo "Four";  //Outputs Four
?>
> Operator

">" operator is used to check whether the first value is greater than second or not.
<?php
$a=5;
if ($a>4)
   echo "Greater";  //Outputs Greater 
?>
< Operator

"<" operator is used to check whether the first value is less than second or not.
<?php
$a=5;
if ($a<6)
   echo "Lesser";  //Outputs Lesser 
?>
>= Operator

">=" operator is used to check whether the first value is greater than or equal to the second value or not.
<?php
$a=5;
if ($a>=5)
   echo "Greater";  //Outputs Greater 
if ($a>=4)
   echo "Greater";  //Outputs Greater 
?>
<= Operator

"<=" operator is used to check whether the first value is less than or equal to the second value or not.
<?php
$a=5;
if ($a<=5)
   echo "Lesser";  //Outputs Lesser 
if ($a<=6)
   echo "Lesser";  //Outputs Lesser 
?>

Ok Guyz, that is all for this lesson, feel free to comment and ask any quries that you may have.


next Previous Lesson --- Next Lesson next

05 January 2011

Php For Beginners (Lesson 4b)

This lesson is in continuation with Php for Beginners lesson 4, so i will be continuing from where i left in lesson 4. Well in the last lesson, I was discussing php operators, and arithmetic operators were discussed in detail. In this lesson i will discuss Assignment operators and their usage in php.

Assignment Operators
Assignment operators are used to perform operations and assign values in variables. Basic assignment operators used in php are as follows:

= Operator
<?php
$a=5;
echo $a; // outputs 5
?>
+= Operator
<?php
$a=5;
$a+=6;
echo $a; // outputs 11
?>
$a+=6 is same as $a=$a+6.
-= Operator
<?php
$a=5;
$a-=4;
echo $a; // outputs 1
?>
$a-=6 is same as $a=$a-6.
*= Operator
<?php
$a=5;
$a*=6;
echo $a; // outputs 30
?>
$a*=6 is same as $a=$a*6.
/= Operator
<?php
$a=5;
$a/=2;
echo $a; // outputs 2.5
?>
$a/=6 is same as $a=$a/6.
.= Operator
<?php
$a=5;
$b=6;
$a.=$b;
echo $a; // outputs 56
?>
$a.=$b is same as $a=$a.$b.
%= Operator
<?php
$a=5;
$a%=2;
echo $a; // outputs 1
?>
$a%=6 is same as $a=$a%6.

This is all for assignment operators, feel free to comment and ask any questions that you may have.


next Previous Lesson --- Next Lesson next

04 January 2011

Php For Beginners (Lesson 4)

Overview

In this lesson we will be discussing operators in php. Operators are used to perform certain operations on some variables/operands. Example of operators includes mathematical operators such as “+”, “-”,”=” and etc.

Operators are divided into four categories:

• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• Logical Operators

In this lesson I will be discussing Arithmetic operators only, the rest of the operators will be discussed in the upcoming lectures.

Arithmatic Operators

Arithmetic operators are used to perform arithmetic operations such as addition, subtraction and etc.

Addition Operator (+)
< ?php
$a=5;
$b=6;
echo $a+$b; // outputs 11
?>

Subtraction Operator (-)
< ?php
$a=10;
$b=6;
echo $a-$b; // outputs 4
?>

Multiplication Operator (*)
< ?php
$a=5;
$b=6;
echo $a*$b; // outputs 30
?>

Division Operator (/)
< ?php
$a=30;
$b=6;
echo $a/$b; // outputs 5
?>

Modulus Operator (%)

Modulus operator returns the remainder of division.
< ?php
$a=5;
$b=2;
echo $a%$b; // outputs 1
?>

Increment Operator (++)
< ?php
$a=5;
$a++;
echo $a; // outputs 6
?>

Decrement Operator (--)
< ?php
$a=5;
$a—;
echo $a; // outputs 4
?>

Well thats all for the fourth lesson, I hope u guys are enjoying my lessons and learning some php and if you have any query then feel free to comment and ask, I will try my level best to answer your question.


next Previous Lesson --- Next Lesson next

03 January 2011

Php For Beginners (Lesson 3)

Overview

In this lesson we will be discussing strings in php and some common and useful functions and operations performed on strings. So what is a string variable? Basically a string variable is just an ordinary variable except that it stores text in it.

Example
< ?php
$test=”This is a test string variable which stores text values.”;
echo $test; // outputs “This is a test string variable which stores text values.”
?>

Concatenation

If you want to merge two string variables or you want to append some text in an existing variable then you need to use concatenation operator (.).

Example # 1
< ?php
$first_variable=”Hello ”;
$second_variable=”world”;
echo $first_variable.$second_variable; // outputs “Hello world”
?>

In Example 1 we are concatenating two string variables. So the output will be the concatenated value i.e “Hello world”.

Example # 2
< ?php
$first_variable=”Hello ”;
echo $first_variable.” world”; // outputs “Hello world”
?>

In example 2 we are appending some text in an existing variable. So the output will be “Hello world”.

Str_replace() Function

Str_replace() is one of the most important functions used in manipulating string variables. This function is used to find and replace any piece of text.

Syntax

str_replace(string to be searched ,string to be replaced with,subject variable);

Example
< ?php
$first_variable=”Hello world”;
str_replace(“world”,”guys”,$first_variable);
echo $first_variable; // outputs “Hello guys”
?>

In above example we replaced “world” with “guys” so the output was “Hello guys”.
Strstr() Function

Strstr() is another useful function for manipulating string variables. This function is used to check whether a piece of text exist in a string variable or not. Strstr() returns false if searched string is not fount and if it is found then it will return the rest of the string from the last occurrence of searched string.

Syntax

strstr(subject variable,string to be searched);

Example
< ?php
$first_variable=”My email address is test@example.com”;
$check=strstr($first_variable,”@”); // outputs “@example.com”
?>

Strlen() Function

Strlen() function returns the length of the given string variable or string. This function comes in handy in many situations where you need to find out exactly how many characters a string contains.

Syntax

Strlen(string str);

Example
< ?php
$first_variable=”My email address is test@example.com”;
echo strlen($first_variable); // outputs “36”
?>

In the above example we tried to find out the length of a string variable so the output was 36 i.e. number of characters in that variable including spaces were 36.
Strpos() Function

This function is used to find out the exact position at which a certain piece of text or a character is located in the given string variable or string.

Syntax

Strops(subject,string to be searched);

Example
< ?php
$first_variable=”My email address is test@example.com”;
echo strpos($first_variable,”@”); // outputs “24”
?>

In the above example we tried to find out the location of “@” in the given string. So the output was 24 i.e. exact position of “@” in the given string variable.

References

http://www.php.net
http://www.w3schools.com

next Previous Lesson --- Next Lesson next

02 January 2011

Php For Beginners (Lesson 2)

Overview

Since you are reading this article therefore I am assuming that you have read my first lesson (If not, I would recommend that you should read lesson 1 first). So I will be continuing from where I left in lesson 1 and in order to give you an idea what you are going to learn in this lesson, I am stating just the names of those

Topics:

• Comments
• Constants
• Variables

Comments

In php there are three ways to write comments. Two of them are used to comment only one line and the third one can be used to comment multiple lines. First method is to simply write “#” in the start of the line that you want to comment, in second method you need to write “//” in the start of the line you need to comment and in the third method you need to encapsulate multiple lines that are to be commented in between “/*” and “*/”. “/*” is used to start the comment and “*/” is used to end the comment.

Example
< ?php
echo “test line”; #This is a one line comment
echo “Another test line”; //This is also a one line comment
/*This is a multi line comment
Another line….. 
Another line…..
End of multi lines comment*/
?>

Constants

As the name suggests, Constants have a fixed value that once set cannot be changed or re-defined. In php if you need to set a constant then you have to use define() function, but remember once a constant is defined, it can never be changed or undefined.

Syntax

define(constant name,constant value,case_insensitive)

Example # 1
< ?php
define(“test_constant”,”Hey There!”);
echo test_constant; // outputs “Hey There!”
echo TEST_CONSTANT; // outputs “TEST_CONSTANT”
?>

In above mentioned example we used only two arguments (name & value) and constants are by default case sensitive so first line will give the write output but the second line will simply display the name of the constant.

Example # 2
< ?php
define(“test_constant”,”Hey There!”,TRUE);
echo test_constant; // outputs “Hey There!”
echo TEST_CONSTANT; // outputs “Hey There!”
?>

In this example as we have set the third argument (case insensitive) to TRUE so this constant is now case insensitive and both lines will output the right content.

Variables

Variables, as their name suggests, are used to store values that can be changed. In php variables names are case sensitive and are represented by a dollar sign followed by the name of the variable. In contrast to constants, variables don’t need define() function to store values, instead variables can be easily assigned values by using “=”.

Example
< ?php
$variable_name=”Test content”;
echo $variable_name; // outputs “Test Content”
$another_variable=85;
echo $another_variable; // outputs 85
?>

Well guys, I guess this is all for the second lesson now you guys should practice these concepts because “Practice Makes A Man Perfect”.

By the way I am deliberately going slow and covering fewer concepts in these lessons so that it will be easier for the beginners to digest them. ;)

References

http://www.php.net
http://www.w3schools.com

next Previous Lesson --- Next Lesson next

29 December 2010

Php For Beginners (Lesson 1)

Definition
PHP: Hypertext Preprocessor is a widely used, general-purpose server side scripting language that was originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document.

Installation
In order to run php on your own machine you need to install following three things:
  • Apache Server
  • Php
  • MySQL
But to make this lesson easier I will not discuss explicit installation of all the three things, rather I would tell you guys a simpler way of doing this. For this purpose we can simply use WAMP/XAMPP Server which is an all in one package of apache, php & MySQL.

WAMP Server can be downloaded from the link below:
http://sourceforge.net/projects/wampserver/files/WampServer%202/WampServer%202.0/WampServer2.0i.exe/download

Or you can download XAMPP Server for windows from the below mentioned link:
http://sourceforge.net/projects/xampp/files/XAMPP%20Windows/xampp-win32-1.7.3.exe/download

After downloading simply follow the steps to install WAMP/XAMPP server on your PC. Once the installation is complete you can test it by typing http://localhost/ in the explorer. This should open a default page for the WAMP/XAMPP Server. If the default page does not come up then try restarting the WAMP/XAMPP Server.

How to Start
Now that php is successfully installed on your PC, we need to know where you should type the php code. Well you can use Notepad, Dreamweaver or any other editor to write in the php code. I would recommend that you use Dreamweaver because it’s a lot easier to use.

After writing the code, you need to safe the file with a .php extension. For example you can save your file as test.php in the respective server folder.

In case of WAMP Server you need to save your php files in wamp > www directory. The exact path of this directory is:
C:\wamp\www\test.php

Whereas if you are using XAMPP Server then you need to safe your php files in the XAMPP > htdocs directory. The exact path should be:
C:\xampp\htdocs\test.php

Now you can run your php file by typing http://localhost/test.php in your browser.

Syntax
A Php code will always be encapsulated between "<?php " and "?>" each instruction will be terminated by semicolon (;).

Example
<?php
some php code....;
some php code....;
some php code....;
?>
Hello World Example
In php if you want to display something on the browser’s screen, you need to use “echo” function.

Syntax
echo “anything you like to display on the screen”;

Example
<?php 
echo "Hello World!";
?> 
Ok guys that is all for the first lesson now you should practice and play with this code to get used to with the php syntax.

References
http://www.wikipedia.com
http://www.w3schools.com 


Next Lesson next