Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, 29 May 2013

Episode 23: Form validation using PHP



In this episode, I am trying to show how we can validate html form using PHP script. Form validation is very much important for web developed because without validation, an empty cell will be added to database and it is waste of memory in database. For this reason we construct validation to prevent add empty content to our database. Many times we need to create a login or registration page for the user and we need to all value of the form. In case users forgets or not fill up the field then there is a mistake of data which is needed. So we need to prevent that. Let do that,

At first we need a form like that,

          <form method=”post”>
          <input type=”text’ value=”” name = “first name” />
<input type=”text’ value=”” name = “last name” />
<input type=”submit’ value=”Ok” name = “Ok” />
</form>

Now create an php script for validation,

          <?php
         
if($_POST[‘Ok’])
{
          if(empty($_POST[‘first name’]))
          {
                   $msg = “Insert First Name !”;
}
if(empty($_POST[‘last name’]))
          {
                   $msg2 = “Insert Last Name !”;
}

Else
{
          Connect your database
And Store the value of field in database using Insert query.
}

}

?>

Here use a function empty ( ) which is building function of PHP for check that the field is empty or not. You can also use Javascript or Jquery for validation. Enjoy it.


Written by “Shojib”

Thursday, 16 May 2013

Episode 22: Password Encryption in PHP



In this tutorial, we are trying to encrypt our password using PHP.

At first we need a form for input our password and we create form in HTML is very easily and passing the form value to the PHP script with the POST or GET method.

Then stored this value in a variable like this
          $pass = $_POST[‘password’]

Now we can encrypted our password is very easily. PHP provides a powerful function for encryption is md5(). This function converts any length data to 32 character long encrypted data. The process is

          $en_pass = md5($pass);

If you use this function for your login or sing up activity then store this value in database. When you build an login procedure then you need do this again because the encrypted form is store in your database table and must be to match the value neither  you can’t login.

So it is very simple and easy to encrypt our data using this powerful function of PHP.


Written by ‘Shojib’

Wednesday, 1 May 2013

Episode 21 : Login and LogOut process in PHP MySQL



When you logged in your account then the environment of your account is starting which is called session. When session is started then you can access your account. So, when we create an login process, must be create an session for accessing your account. Let’s do it.

At first create a database table for holding user information. The database structure is following :

-- Table structure for table `member`
--

CREATE TABLE IF NOT EXISTS `member` (
  `name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `position` varchar(10) NOT NULL,
  `varify` varchar(100) DEFAULT NULL,
  `status` tinyint(2) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--

Now creating a form for login and save it.

<?php
session_start();
session_destroy();
?> 
<html>
<form id="form1" name="login_form" method="POST" action="login.php">
                 
                  <div align="center">
                    <table width="433" height="169" border="0">
                      <tr>
                        <td height="36" colspan="2" valign="top"><h2 style="text-shadow: 5px 5px 5px red;"><strong>Login :</strong></h2></td>
        </tr>
                      <tr>
                        <td width="148">Username : </td>
        <td width="275" valign="top">
          <input type="text" name="username" value='' />    </td>
      </tr>
                      <tr>
                        <td>Password : </td>
        <td valign="top"><input type="password" name="password" value='' /></td>
      </tr>
                      <tr>
                        <td>&nbsp;</td>
        <td><input type="submit" value="Login" /></td>
      </tr>
                    </table>
          </div>
                </form>
    </div></td>
  </tr>
</table>
</html>


Now Create the processing code for login.

<?php
session_start();
session_destroy();

$user = "";
$pass = "";
$msg = "";

if($_SERVER['REQUEST_METHOD']=='POST')
{
include 'connection.php';

$user = $_POST['username'];
$pass = $_POST['password'];

$user = htmlspecialchars($user);
$pass = htmlspecialchars($pass);

$sql = "SELECT * FROM info";
$result = mysql_query($sql);
while($db_field = mysql_fetch_assoc($result))
{
          $a = $db_field['username'];
          $b = $db_field['password'];
          $pos = $db_field['position'];
          if(($user == $a) AND ($pass == $b)){
                  
          if($pos == "admin"){
          session_start();
          $_SESSION['username'] = $user;
          $_SESSION['admin'] = "log";
          mysql_close($connection);
          header("Location: admin.php");
          break;
          }
          else if($pos == "member"){
          session_start();
          $_SESSION['username'] = $user;
          $_SESSION['member'] = "log";
          mysql_close($connection);
          header("Location: member.php");
          break;
         
          }
          else if($pos == "Leader"){
          session_start();
          $_SESSION['username'] = $user;
          $_SESSION['Leader'] = "log";
          mysql_close($connection);
          header("Location: leader_home.php");
          break;
         
          }
}

}
$msg = "Check username and password !";
mysql_close($connection);
          }

?>


Now set following code in the first account for entering your account.

<?php
session_start();
$user = $_SESSION['username'];
$log = $_SESSION['admin'];
if($log != "log"){
header("Location: login.php");

}
?>


LogOut

You can logout your account simply destroy the session. Indicate the page first and link that page and set,

session_start();
session_destroy();





Written by ‘Shojib’.

Saturday, 5 January 2013

Episode 19: WHERE Clause



The beast clause called WHERE deserves its own little section because it’s really the meat of the query. (No offense to the other guys, but they are pretty much “no brainers.”) WHERE is like a cool big brother that can really do some interesting stuff. While SELECT tells MySQL which fields you want to see, WHERE tells it which records you want to see. It is used as follows:

SELECT * FROM customers
//retrieves all information about all customers
SELECT * FROM customers WHERE gender = “Male”
//retrieves all information about male customers

Let’s look at the WHERE clause a little more in-depth:

Comparison operators are the heart of the WHERE clause, and they include the following:
=, <, >, <=, >=, !=

LIKE and %: Oh how we like LIKE. LIKE lets you compare a piece of text or number and gives you the % as a wildcard. The wildcard allows you to search even if you only know a piece of what’s in the field, but you don’t want an exact match.
Example:

SELECT * FROM products WHERE description LIKE “%shirt%”

This gives you any records that have the word or text pattern of “shirt” in the description,
such as “t-shirt,” “blue shirts,” or “no shirts here.” Without the %s you would get
only those products that have a description of “shirt” and nothing else.

Logical operators are also accepted in the WHERE clause:

SELECT * FROM products WHERE description LIKE “%shirt%” AND price < 25

This gives you all the products that have the word or text pattern of “shirt” in the description and that have a price of less than $25.


Written by ‘Shojib’.

Episode 18: Querying the Database



Now that you have some data in the database, you probably want to retrieve it. You use the SELECT statement to choose data that fits your criteria.

Typical syntax for this command is as follows:

SELECT [fieldnames]
AS [alias]
FROM [tablename]
WHERE [criteria]
ORDER BY [fieldname to sort on] [DESC]
LIMIT [offset, maxrows]

You can set numerous other parameters, but these are the most commonly used:

SELECT [fieldnames]: First decide what specific fieldnames you want to retrieve; if you want to see them all, you simply insert *.

AS: You use the alias to group two or more fieldnames together so that you can reference them later as one giant variable. An example would be:

SELECT first_name, last_name AS full_name. . . ORDER BY full_name . . .

You cannot use the AS parameter with the WHERE parameter, because this is a limitation of MySQL. When the WHERE clause is executed, the column value may not be known.

FROM: This is pretty self-explanatory: You just need to name the table or tables you are pulling the data from.

WHERE: List your criteria for filtering out the data, as described in the following section.
ORDER BY: Use this parameter if you want the data sorted on a particular field; if you want the results returned in descending order, add DESC.

LIMIT: This enables you to limit the number of results returned and offset the first record returned to whatever number you choose. An example would be:

LIMIT 9, 10

This would show records 10 through 19. This is a useful feature for showing only a certain number of records on a page, and then allowing the user to click a “next page” link to see more.
For a complete reference, you are advised to—yet again—visit the source at www.mysql.com.


Written by 'Shojib'.

Wednesday, 26 December 2012

Episode 17: Connecting to the MySQL Server

Before you can do anything with MySQL, you must first connect to the MySQL server using your specific connection variables. Connection variables consist of the following parameters:

Host name: In your case, it’s the local host because you’ve installed everything locally. You will need to change this to whatever host is acting as your MySQL server.
Username and password:  The user name is root and no need password

You issue this connection command with the PHP function called mysql_connect. As with all of your PHP/MySQL statements, you can either put the information into variables, or leave them as text in your MySQL query.

Here’s how you would do it with variables:

$host = “localhost”;
$user = “root”;
$pass = “”;
$connect = mysql_connect($host, $user, $pass);

The following statement has the same effect:

$connect = mysql_connect(“localhost”, “bp5am”, “”);

Written by ‘Shojib’.

Episode 16: How PHP Fits with MySQL



With the onset of PHP5, you need to take a few extra steps to convince PHP and MySQL to play well with each other. Before your MySQL functions will be recognizable by PHP, make sure to enable MySQL in your php.ini file.
You can use MySQL commands within PHP code almost as seamlessly as you do with HTML.

Some of the more commonly used functions are:

mysql_connect ("hostname", "user", "pass"): Connects to the MySQL server.
mysql_select_db("database name"): Equivalent to the MySQL command USE; makes the selected database the active one.
mysql_query("query"): Used to send any type of MySQL command to the server.
mysql_fetch_rows("results variable from query"): Used to return a row of the entire
results of a database query.
mysql_fetch_array("results variable from query"): Used to return several rows of
the entire results of a database query.
mysql_error(): Shows the error message that has been returned directly from the MySQL server.

You will most likely become very familiar with these commands, and many more.
You can also send any MySQL command to the server through PHP and the mysql_query command, as in the preceding example. You do this by sending the straight text through PHP either through a variable or through the mysql_query command directly, like this:

$query = “SELECT * from TABLE”;
$results = mysql_query($query);
You can also do it like this:
$results = mysql_query(“SELECT * from TABLE”);

The results of your query are then put into a temporary array known as $results.

Written by ‘Shojib’.

Thursday, 20 December 2012

Episode 15: Arrays of PHP



You’ve learned about variables and how they are used, but what if you need to have more than one value assigned to that variable? That, my friend, is a good old-fashioned array. Arrays are nothing more than lists of information mapped with keys and stored under one variable name. For example, you can store a person’s name and address or a list of states in one variable.

Array Syntax
With an array, you can store a person’s name and age under one variable name, like this:

<?php
$husband = array(“firstname”=>”Albert”,
“lastname”=>”Einstein”,
“age”=>”124”);
echo $husband[“firstname”];
?>

Notice how you use => instead of = when assigning values to keys of arrays. This gives you an output of “Albert” and all the values are still stored in the variable name husband. You can also see how you keep track of the information inside the variable with the use of keys such as “firstname” and “lastname.” You can also set an array value in the following way:

<?php
$husband[“firstname”] = “Albert”;
$husband[“lastname”] = “Einstein”;
$husband[“age”] = 124;
?>

This is the equivalent of the previous example.

If you want to simply store a list and not worry about the particular order, or what each value should be mapped to you don’t need to explicitly name the keys; PHP will assign invisible internal keys for processing; numeric integers starting with 0. This would be
set up as follows:

<?php
$flavor[] = “blue raspberry”;
$flavor[] = “root beer”;
$flavor[] = “pineapple”;
?>
These would then be referenced like this:

echo $flavor[0]; //outputs “blue raspberry”
echo $flavor[1]; //outputs “root beer”
echo $flavor[2]; //outputs “pineapple”


            Written by “Shojib”.

Episode 14: Using Includes for Efficient Code



Are you getting sick of typing the same things over and over again? The makers of PHP have blessed us frustrated developers with a little time-saving device called “includes” that save you from reentering frequently used text over and over. Suppose that you want to type the same message on every page of your site. Perhaps it is your company’s
name and address, or maybe today’s date. If you are coding each page of your site from scratch, this is not very efficient for a couple of reasons:

You are typing the same information over and over again, which is never good.
In the case of an update or a change, you have to make the change in every single page of your site. Again, this is redundant and time consuming, and it elevates the potential for human error.

A solution to this problem is to use an include. Includes are PHP files tucked into other PHP files. You take commonly used information and put it in a separate file. For example, if you have a set of defined variables that need to be referenced in every page on your site, you could define them once, in a single PHP script. Then, on each of your pages where you want the variables to appear, you use an include statement that specifies the file that defines the variables. When your script is parsed, the parser inserts the code from the include file into your page, just as if you’d typed it there yourself. The final output is then sent to the browser. Includes can use any extension, but are sometimes referenced as .inc files. If you are adding potentially sensitive information, for example, server variables such as passwords, then it is advisable to save these in .php files so they are never accessible to anyone because the information is parsed before it is sent to the browser. You can add an include in any other file, and if you place the include statement in an if statement, you can control when the include is inserted.

Try It Out Adding a Welcome Message

Suppose you want every page in the movie review site to show a welcome message and perhaps today’s date. You want to create a file that includes this information, so follow these steps:

1. Open your text editor and type the following:
<div align=”center”><font size=”4”>Welcome to my movie review site!</font>
<br>
<?php
echo “Today is “;
echo date(“F d”);
echo “, “;
echo date(“Y”);
?>
</div>
2. Save this file as header.php.
3. To include this file in the three existing movie Web site files, add the following line immediately after the <body> tag to login.php :

<?php include “header.php”; ?>

4. Save your files.
5. Take a look at the files again. If you open login.php  and You will see the same two lines on every page where you have included the header.php file.

Written by “Shojib”.

Tuesday, 18 December 2012

Episode 13: Passing values to a function





You pass values to a function by putting the values between the parentheses when you call the function, as follows:

functionname(value,value,...);

Of course, the variables can’t just show up. The function must be expecting them. The function statement includes variables names for the values it’s expecting, as follows:

function functionname($varname1,$varname2,...)
{
statements
return;
}
For example, the following function computes the sales tax:
function compute_salestax($amount,$custState)
{
switch ( $custState )
{
case “OR” :
$salestaxrate = 0;
break;
case “CA” :
$salestaxrate = 1.0;
break;
default:
$salestaxrate = .5;
break;
}
$salestax = $amount * $salestaxrate;
echo “$salestax<br />”;
}

The first line shows that the function expects two values — $amount and $custState. When you call the function, you pass it two values, as follows:

$amount = 2000.00;
$custState = “CA”;
compute_salestax($amount,$custState);

In this case, the amount passed in is 2000.00 and the state is CA. The output is 2000, because the salestaxrate for CA is 1.0.


Written by “Shojib”.