Tuesday, May 1, 2012

PHP MySQL Basics

PHP MySQL Basics

(if you haven't installed PHP and Apache server see this Link - Installing and configuring PHP )

What is PHP?

    PHP stands for PHP: Hypertext Preprocessor
    PHP is a server-side scripting language, like ASP

What is a PHP File?

    PHP files can contain text, HTML tags and scripts
    PHP files are returned to the browser as plain HTML 

Variables in PHP

Variables are used for storing values, like text strings, numbers or arrays.
$txt="Hello World!";   (String Variables in PHP)
$x=16;

The Concatenation Operator .
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;

------------------------------------------------------------------------------------------------------------

PHP Array

 there are three kind of arrays:

    Numeric array - An array with a numeric index
    Associative array - An array where each ID key is associated with a value
    Multidimensional array - An array containing one or more arrays

Numeric array - $cars=array("Saab","Volvo","BMW","Toyota");  
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota"; 

associative array - $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);


$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34"; 

Multidimentional array

$families = array
 (
 "Griffin"=>array  (  "Peter", "Lois", "Megan"  ),
 "Quagmire"=>array (  "Glenn"  ),
 "Brown"=>array ( "Cleveland", "Loretta", "Junior" )
 ); 

Array
( [Griffin] => Array  (  [0] => Peter  [1] => Lois  [2] => Megan  )
  [Quagmire] => Array  (  [0] => Glenn  )
  [Brown] => Array ([0] => Cleveland[1] => Loretta [2] => Junior )

------------------------------------------------------------------------------------------------------------
Conditional Statements

if 

$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
if else

$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
else
  echo "Have a nice day!";
if...elseif....else

$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
elseif ($d=="Sun")
  echo "Have a nice Sunday!";
else
  echo "Have a nice day!";


------------------------------------------------------------------------------------------------------------

PHP Loops

while loop 

$i=1;
while($i<=5)
 {
 echo "The number is " . $i . "<br />";
  $i++;
   }
do while

$i=1;
do
 {
  $i++;
  echo "The number is " . $i . "<br />";
 }
while ($i<=5);
for loop

for ($i=1; $i<=5; $i++)
 {
 echo "The number is " . $i . "<br />";
  }
for each

$x=array("one","two","three");
foreach ($x as $value)
  {
  echo $value . "<br />";
 }
------------------------------------------------------------------------------------------------------------

PHP Function

function writeName()
{
echo "Kai Jim Refsnes";
}

echo "My name is ";
writeName();

PHP function with parameter

function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeName("Kai Jim");

PHP function Returens 

function add($x,$y)
{
$total=$x+$y;
return $total;
}

echo "1 + 16 = " . add(1,16);
------------------------------------------------------------------------------------------------------------

PHP Form Handling

<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

in welcome.php
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.


The $_GET Variable


The predefined $_GET variable is used to collect values in a form with method="get"

Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old! 
When using method="get" in HTML forms, all variable names and values are displayed in the URL.

The $_POST Variable


The predefined $_POST variable is used to collect values from a form sent with method="post".
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old. 

Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

PHP include() Function


The include() function takes all the content in a specified file and includes it in the current file.
<?php include("header.php"); ?>

------------------------------------------------------------------------------------------------------------

PHP File Handling



opening a file - $file=fopen("welcome.txt","r");
closing a file - $file = fopen("test.txt","r");

reading line by line - 
while(!feof($file))
  {
     echo fgets($file). "<br />";
  }
Reading a File Character by Character -  fgetc($file);

------------------------------------------------------------------------------------------------------------

What is a Cookie?


A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

setcookie(name, value, expire, path, domain); 

setcookie("user", "Alex Porter", time()+3600);

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.  echo $_COOKIE["user"];

PHP Sessions

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.


session_start();
$_SESSION['views']=1;
echo "Pageviews=". $_SESSION['views'];

Destroying a Session

unset($_SESSION['views']);

session_destroy();

What is an Exception


Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception

function checkNum($number)
  {
  if($number>1)
    {
    throw new Exception("Value must be 1 or below");
    }
  return true;
  }

//trigger exception
checkNum(2);

Try, throw and catch



Proper exception code should include:

    Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown"
    Throw - This is how you trigger an exception. Each "throw" must have at least one "catch"
    Catch - A "catch" block retrieves an exception and creates an object containing the exception information




------------------------------------------------------------------------------------------------------------


PHP MySQL Introduction

PHP MySQL Connect to a Database

Syntax - mysql_connect(servername,username,password); 


$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

closing connection 

mysql_close($con);


Create a Database

syntax - CREATE DATABASE database_name 

if (mysql_query("CREATE DATABASE my_db",$con))
 {
 echo "Database created";
 }
else
  {
  echo "Error creating database: " . mysql_error();
  }
Create a Table


// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";

// Execute query
mysql_query($sql,$con);



$sql = "CREATE TABLE Persons 
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";

insering data to table


mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");


Select Data From a Database Table


mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }

mysql_close($con);

Update Data In a Database

mysql_select_db("my_db", $con);

mysql_query("UPDATE Persons SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");

mysql_close($con);

Delete Data In a Database

mysql_select_db("my_db", $con);

mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");


SQL basics


SQL SELECT Statement

SELECT column_name(s) FROM table_name - eg:-  SELECT LastName,FirstName FROM Persons
SELECT * FROM table_name - eg:-  SELECT * FROM Persons

The SQL SELECT DISTINCT Statement


SELECT DISTINCT column_name(s) FROM table_name - eg:-  SELECT DISTINCT City FROM Persons



The WHERE Clause 

SELECT column_name(s) FROM table_name WHERE column_name operator value

eg:- SELECT * FROM Persons WHERE City='Sandnes'



SQL Joins


SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.

Different SQL JOINs

Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.

    JOIN: Return rows when there is at least one match in both tables
    LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
    RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
    FULL JOIN: Return rows when there is a match in one of the tables



OOPS in PHP
===============
 a class is just a template for these data members and methods. So, The idea is that you can create any number of "objects" based on a single "class." 

So if your class is called "User" you may create an object based on that class called $myUser or $myOtherUser 


No comments:

Post a Comment