Monday, November 10, 2014

PHP 1st, 2nd, 3rd, 4th, 5th, 6th and so on PHP Add Ordinal Number Suffix

<?php

function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1:  return $num.'st';
case 2:  return $num.'nd';
case 3:  return $num.'rd';
}
}
return $num.'th';
}

for ($i = 1; $i <= 100; $i++){
echo addOrdinalNumberSuffix($i) . "\t";
if ($i % 10 == 0) {
echo "<br/>";
}
}

?>


Output :)


Friday, October 10, 2014

MySql query to select count of only max value from table in PHP

CREATE TABLE tableName  // Give any name as u like
(
     id int auto_increment primary key,
     party varchar(20),
     constituency varchar(30),
     votes int(11)
);

Then insert some details.
I inserted these details :)

INSERT INTO tableName
          (party, constituency,votes)
VALUES
          ('BJP', 'Surat',1200),
          ('Congress', 'Surat',1100),
          ('BJP', 'Baroda',800),
          ('Congress', 'Baroda',900);

Query :)

mysql_query("select max(votes) from tableName group by constituency");

Output :)


Wednesday, October 8, 2014

PDO search database using LIKE.

First create database and name it as u like. I create database named with `fdb`. And then create table with 4 columns.

DEMO :)

Then insert some details


Example :)

/* here project is the database table name */

<?php
try{
$bdd=new PDO("mysql:host=localhost;dbname=fdb","root","");
}
catch(exception $e){
die("ERROR : ".$e->getMessage());
}

$keyword='ma';  /* You can use any characters as keywords */

$sql="SELECT * FROM project WHERE fullname LIKE :keyword;";
$q=$bdd->prepare($sql);
$q->bindValue(':keyword','%'.$keyword.'%');
$q->execute();

while ($r=$q->fetch(PDO::FETCH_ASSOC)) {
   echo"<pre>".print_r($r,true)."</pre>";
}
?>

Output :)


Friday, September 19, 2014

Display data in the table from database.

First create the database and name it fdb.
Then create table with 2 columns in the database and name it simp.
Insert data in the table.

Demo :)

Now php file :)

<?php
$dbserver="localhost";
$dbusername="root";
$dbpassword="";
$dbname="fdb";

$link=mysql_connect($dbserver,$dbusername,$dbpassword);
mysql_select_db($dbname,$link);

function displaytable($tablename,$link)
{
$query = "SELECT city FROM $tablename";
$res = mysql_query($query,$link);
$ccount = mysql_num_fields($res);

echo "<table border=1>";
echo ("<tr align=center>");
echo "<td><b>City List</b></td>";
echo "</tr>";

while($row=mysql_fetch_array($res))
{
echo ("<tr>");
for($col=0;$col<$ccount;$col++)
{
echo"<td> $row[$col]</td>\n";
echo"</tr>\n";
}
}
echo "</table>\n";
}
?>
<html>
<head>
<title>Display Table Data</title>
</head>
<body>
<h4>Table Data</h4>
<hr/>
<table>
<tr>
<td>
<?php
displaytable("simp",$link);
?>
</td>
</tr>
</table>
</body>
</html>

Output :)

Wednesday, September 17, 2014

How to know total no of rows in Database table in PHP?

First create a database and a table in it.
Here database name = first_db and table name = students
Add some data in the table

<html>
<head>
<title>No of Rows</title>
</head>
<body>

<?php
$dbserver="localhost";

$dbusername="root";

$dbpassword="";

$dbname="first_db";

$link=mysql_connect($dbserver,$dbusername,$dbpassword);
mysql_select_db($dbname,$link);

if($_REQUEST['btn'])
{
$sql="select * from students"; // Here students is a database table name that we created in the database
$result=mysql_query($sql,$link);
$row=mysql_num_rows($result);

echo "Total no of rows : " . $row ;

mysql_close($link);
}
?>

<form action="totalnorows.php" method="POST">
<table>
<tr>
<td>
<input type="submit" name="btn" value="Get No" />
</td>
</tr>
</table>
</form>

</body>
</html>

Output :)

Screen 1 :)



Screen 2 :)

Screen 3 :)

Table of 25

<?php
$n=1;
factorial($n);
function factorial($n){
if($n<=10)
{
$ans= $n * 25;
echo "25 * $n"." = "."$ans"."<br/>";
factorial($n+1);
}
}
?>


Output :)

Sunday, April 20, 2014

How to create Registration form in PHP.

First create a database table in MySql :-



Than create a Sign Up form using html.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>

<form method="post" action="database.php">
<fieldset style="width:30%">
<legend>Registration Form</legend>
<table align="center">
<tr>
<td>First Name :</td>
<td><input type="text" name="fname"/></td>
</tr>
<tr>
<td>Last Name :</td>
<td><input type="text" name="lname"/></td>
</tr>
<tr>
<td>Select UserName :</td>
<td><input type="text" name="uname"/></td>
</tr>
<tr>
<td>Email ID :</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="pw"/></td>
</tr>
<tr>
<td></td>
<td><input id="button" name="submit" type="submit" value="Sign Up"/></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>

write the following code in the Database.php :-


<?php
$cn=mysql_connect('localhost','root','');
$cd=mysql_select_db('Mahi',$cn); //Mahi is a Database Name

if(isset($_POST['submit']))
{
SignUp();
}

function SignUp()
{
if(!empty($_POST['uname'])) //checking the 'uname' is empty or have some text
{
$query = mysql_query("SELECT * FROM cf1 WHERE UserName = '$_POST[uname]'
OR UserName='$_POST[uname]' and Email='$_POST[email]' OR
Email='$_POST[email]'"); //cf1 is a Table name of a Database

if(!$row = mysql_fetch_array($query))
{
newuser();
}

else
{
echo "SORRY...This is Aready Registered User.";
}
}
}

function NewUser()
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$uname = $_POST['uname'];
$email = $_POST['email'];
$pw = $_POST['pw'];

$query = "INSERT INTO CF1(First_Name,Last_Name,UserName,Email,Password) VALUES ('$fname','$lname','$uname','$email','$pw')";

$data = mysql_query ($query);

if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
?>

Output :-




Friday, April 18, 2014

Display data of database table on table(html) in PHP.

First create a table in mysql database that contain 2 columns Username and Password than save it.
Now create a php file and write following code in it :-


<table width="50%" border="1">
<tr>
<td><strong><font color="#000000">UserName</font></strong></td>
<td><strong><font color="#000000">Password</font></strong></td>
</tr>

<?PHP
mysql_connect('localhost','root','12345');
mysql_select_db('Mahi');
   
$sql = "SELECT * FROM signup1";
//echo $sql;exit;
   
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>

<tr>
<td><?php echo $row['Username']; ?></td>
        <td><?php echo $row['Password']; ?></td>
       
</tr>

<?php
}
?>

Output :-


Wednesday, March 26, 2014

Simple sign up form in php using MySql.

Note :- I am using XAMPP server for mysql.


form.php

<!DOCTYPE HTML>
<html>
<head>
<title>Sign-Up</title>
</head>
<body>
<center>
<fieldset style="width:30%">
<legend>Registration Form</legend>
<form method="POST" action="connect.php">
<table border="0">
<tr>

<td>Name</td><td> <input type="text" name="name"></td>
</tr>

<tr>
<td>Email</td><td> <input type="text" name="email"></td>
</tr>

<tr>
<td>UserName</td><td> <input type="text" name="user"></td>
</tr>

<tr>
<td>Password</td><td> <input type="password" name="pass"></td>
</tr>

<tr>
<td>Confirm Password </td><td><input type="password" name="cpass"></td>
</tr>

<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</table>
</form>
</fieldset>
</center>
</body>
</html>

connect.php


<?php
$con=mysql_connect('localhost','root','') or die("Failed to connect to MySQL: " . mysql_error());

$db=mysql_select_db('signup2',$con) or die("Failed to connect to MySQL: " . mysql_error());

function NewUser()
{
$fullname = $_POST['name'];
$userName = $_POST['user'];
$email = $_POST['email'];
$password =  $_POST['pass'];

$query = "INSERT INTO userinfo (Name,Email,UserName,Password) VALUES ('$fullname','$email','$userName','$password')";

$data = mysql_query ($query)or die(mysql_error());

if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
}

function SignUp()
{
if(!empty($_POST['user']))   //checking the 'user' name which is from Sign-Up.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM userinfo WHERE UserName = '$_POST[user]' AND Password = '$_POST[pass]'") or die(mysql_error());

if(!$row = mysql_fetch_array($query) or die(mysql_error()))
{
newuser();
}
else
{
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
?>

Output:-



Monday, March 24, 2014

OOPs in PHP :- Simple example of class

<?php
class bank
{
var $amt=1000;

function deposite($dep)
{
echo "Balance in the account ".$this->amt."<br/>";
$this->amt=$this->amt+$dep;
echo "Balance after deposite money ".$this->amt;
echo "<br/>";
}
function withdraw($wd)
{
$this->amt=$this->amt-$wd;
echo "Balance after withdraw money ".$this->amt;
}
}
$b=new bank();
$b->deposite(500);
$b->withdraw(200);
?>

Output:-



Use of unset in PHP

If we declare any variable as unset then it will be undefined for the next part of the coding. See example :-


<?php
echo "<center>";

$a="Mahi";
$b="Piyu";
$c="Bhavna";

echo $a." ".$b." ".$c."<br/>";

unset($a,$b,$c);

echo $a;
echo $b;
echo $c;

echo "</center>";
?>

Output:-



PHP Cookie

<?php
$un=$_POST['username'];
setcookie('Login','$un');
?>
<html>
<center>
<h2>Please Login</h2>
<form method="POST">
<table>
<tr>
<td>
UserName:
</td>
<td>
<input type="text" name="username"?>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/>
</tr>
<tr>
<td><input type="submit" value="Submit" name="submit"/></td>
</tr>
</table>
</form>
</center>
</html>

Save and run file. Enter info and submit it. Now open setting page of your browser and open cookies check there for our cookie.

Simple example of SESSION in PHP

SessionMethod1.php


<html>
<form method="POST">
<table align="center">
<tr>
<td>
UserName:
</td>
<td>
<input type="text" name="username"?>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/>
</tr>
<tr>
<td><input type="submit" value="Submit" name="submit"/></td>
</tr>
</table>
</form>
</html>
<?php
session_start();
$_SESSION["un"]=$_POST['username'];
$_SESSION["pw"]=$_POST['password'];
?>

SessionMethod2.php


<?php
session_start();

echo $_SESSION["un"]."<br/>";
echo $_SESSION["pw"];
?>

Output:-





Sunday, March 23, 2014

FILES method in PHP

<?php
echo "<center>";
//you get the following information for each file:
$a=$_FILES['photo']['name'];
$b=$_FILES['photo']['size'];
$c=$_FILES['photo']['type'];
$d=$_FILES['photo']['tmp_name'];

if(empty($a))
{
echo "Please choose your file!<br/>";
}
else
echo "Wait file is processing";

/*echo $a."<br/>";
echo $b."<br/>";
echo $c."<br/>";
echo $d;
echo "</center>";*/
?>

<form method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="photo" size="25" />
<input type="submit" name="submit" value="Submit" />
</form>
<table width="40%" align="center">
<tr>
<th>
Image Name
</th>
<th>
Image Size
</th>
<th>
Image Type
</th>
</tr>
<tr>
<td>
<?php echo $a; ?>
</td>
<td>
<?php echo $b; ?>
</td>
<td>
<?php echo $c; ?>
</td>
</tr>
</table>

Output:-


REQUEST Method in PHP

First create a webpage that contain a form.


<html>
<head>
<title>Form</title>
</head>
<body>
<center>
<h2>Registration Form</h2>
<form method="POST" action="FormRequestMethod2.php"> <!-- Here we can use POST or GET method whatever we want to use -->
<table>
<tr>
<td>
Enter Your Name:
</td>
<td>
<input type="text" name="username"/><br/>
</td>
</tr>
<tr>
<td>
Enter Email Id :
</td>
<td>
<input type="text" name="email"/><br/>
</td>
</tr>
<tr>
<td>
Enter Your Password :
</td>
<td>
<input type="password" name="password"/><br/>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

Now create another page and name it FormRequestMethod2.PHP


<html>
<head>
<title>Result of previous page</title>
</head>
<body>
<center>
<h2>Your information is as below</h2>
<table>
<tr>
<td>
User Name : 
</td>
<td>
<?php echo $_REQUEST['username']; ?>
</td>
</tr>
<tr>
<td>
Email Id :
</td>
<td>
<?php echo $_REQUEST['email']; ?>
</td>
</tr>
<tr>
<td>
Password :
</td>
<td>
<?php echo $_REQUEST['password']; ?>
</td>
</tr>
</table>
</body>
</html>

First run the 1st file fill up the info and press button. You will redirect to another page that contains your info.


Output :-


1st Screen 


2nd Screen 

POST Method in PHP

First create a webpage that contain a form.


<html>
<head>
<title>Form</title>
</head>
<body>
<center>
<h2>Registration Form</h2>
<form method="POST" action="FormPostMethod2.php">
<table>
<tr>
<td>
Enter Your Name:
</td>
<td>
<input type="text" name="username"/><br/>
</td>
</tr>
<tr>
<td>
Enter Email Id :
</td>
<td>
<input type="text" name="email"/><br/>
</td>
</tr>
<tr>
<td>
Enter Your Password :
</td>
<td>
<input type="password" name="password"/><br/>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

Now create another page and name it FormPostMethod2.PHP


<html>
<head>
<title>Result of previous page</title>
</head>
<body>
<center>
<h2>Your information is as below</h2>
<table>
<tr>
<td>
User Name :
</td>
<td>
<?php echo $_POST['username']; ?>
</td>
</tr>
<tr>
<td>
Email Id :
</td>
<td>
<?php echo $_POST['email']; ?>
</td>
</tr>
<tr>
<td>
Password :
</td>
<td>
<?php echo $_POST['password']; ?>
</td>
</tr>
</table>
</body>
</html>

First run the 1st file fill up the info and press button. You will redirect to another page that contains your info.


Output :-


1st Screen 


2nd Screen 

GET Method in PHP

First we have to create a web page that contain a form


<html>
<head>
<title>Form</title>
</head>
<body>
<h2>Registration Form</h2>
<form method="GET" action="infodisplay.php">
Enter Your Name:
<input type="text" name="username"/><br/>
Enter Email Id :
<input type="text" name="email"/><br/>
Enter Your Password :
<input type="password" name="password"/><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Then create another file named infodisplay.php and write the below code there :-


<?php
echo "Welcome You are a Member of this Page!<br/>";
$un=$_GET['username'];
$Email=$_GET['email'];
$pw=$_GET['password'];

echo $un."<br/>";
echo $Email."<br/>";
echo $pw;
?>

First, we have to run first file. fill up the form and click submit button. Then we automatically redirect to the second page :-


Output:-



Global Variable in PHP

/* In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name. */

<?php
$a=5;
$b=3;

function mahi()
{
$c=$GLOBALS['a']+$GLOBALS['b'];
echo $c;
}
mahi();
?>

Output :-



Saturday, March 22, 2014

User Defined Functions in PHP

<?php

//Function Without Argument
Add();
function Add()
{
$a=5;
$b=6;
$c=$a+$b;
echo $c;
}

echo "<br/>";

//Function With Argument
Add1(5,6);
function Add1($a,$b)
{
$c=$a+$b;
echo $c;
}

echo "<br/>";

//Returning Value From Function
echo Add2();
function Add2()
{
$a=5;
$b=6;
$c=$a+$b;
return ($c);
}
?>

Output :-


Foreach loop example in PHP.

<?php
$m=array("Mahi","Mahi1","Mahi2");
foreach($m as $p)
{
echo $p."<br/>";
}
?>

Output :-



Example of Associate Array in PHP

<?php
$city=array("S"=>"Surat" , "A"=>"Ahmedabad" , "R"=>"Rajkot");
echo $city["S"];

echo "<br/>";

$city=array("S"=>5 , "A"=>10 , "R"=>15);

$First_Value=$city["S"];
$Second_Value=$city["A"];
$Third_Value=$city["R"];

$Addition=$First_Value + $Second_Value + $Third_Value;

echo "The Result is : ".$Addition;
?>

Output :-



Sunday, March 9, 2014

Indexed Array in PHP.

Indexed arrays is arrays where each element is referenced by a numeric index, usually starting from zero. For example, the first element has an index of 0, the second has an index of 1, and so on.

Example:


<?PHP
$a = array(" Java <br/> "," Android <br/>"," Php <br/>"," Sql");
$size = count($a);
print_r($a);
?>

Output:


PHP include..

With include statement we can import reusable code and reuse it.

Example :

1.php

<?php
print "Starting 2 -->";
include '2.php';
print " <--Finishing 2";
?>

2.php

<?php
echo " <h1>Hello World</h1> ";
?>

Output:


PHP if else statement.

if else statement has the following syntax:-


if(condition_0){
...
}else{
...
}

or

if(condition_0){
...
}elseif (condition_1){

}elseif (condition_2){

}else{
...
}

Example:


<html>
<head>
<title>Simple if/elseif example</title>
</head>
<body>
<?php
$Age = 22;
if ($Age < 10)
{
echo "You're under 10";
}
else if ($Age < 20)
{
echo "You're under 20";
}
else if ($Age < 30)
{
echo "You're under 30";
}
else if ($Age < 40)
{
echo "You're under 40";
}
else
{
echo "You're over 40";
}
?>
</body>
</html>

Saturday, March 8, 2014

PHP Operators






Difference between single quotes and double quotes in string.(PHP)

Single and double quotation marks work in different ways.

If you enclose a string in single quotation marks, PHP uses the string exactly as typed.

However, double quotation marks has extra features:

variable names within the string are parsed and replaced with the variable's value special characters need escaping in the string.

Example:


<?PHP
$str = 'world';

echo "Hello, $str! \n"; // Displays "Hello, world!"
echo 'Hello, $str! \n'; // Displays "Hello, $str!"
echo " Hi\tFriend! "; // Displays "Hi      Friend!"
echo ' Hi\tFriend! '; // Displays "Hi\tFriend!"  
?>

PHP Type Casting.

Type casting can cause a variable's value to be treated as a specific type.

Syntax:


variableName1 = (newType) variableName2;

Example:-

<?php
       $a = 5.5;
       echo $a;             // Displays "5.5"
       echo (string)$a;     // Displays "5.5"
       echo (int) $a;       // Displays "5"
       echo (float) $a;     // Displays "5.5"
       echo (boolean) $a;   // Displays "1"  
?>

PHP Data Types

PHP has seven data types :-

1) string
2) integer
3) float
4) boolean
5) array
6) object
7) resource

*) string


Strings hold characters such as "a" "hello" "Mahi Babariya" etc.
PHP strings are case-sensitive.

*) integer


Integers hold whole numbers, either positive or negative, such as 1, -20, 12345,etc.
The limit of integer is between -2147483647 and 2147483647.
The integer numbers outside the range are automatically converted to floats.

*) float


Floats hold fractional numbers as well as very large integer numbers, such as 2.5, 1.00000001, and 12345.67890

*) Boolean


Booleans hold either true or false. Behind the scenes, booleans are integers.

*) Array


Arrays are a special variable type in that they hold multiple values like a container.

*) object


Objects are complex variables that have multiple values, and they can have their own functions.

*) resource


Resources might be picture data, or the result of an SQL query. We should free up resources after using them.

PHP Introduction

PHP scripts are generally saved with the file extension .php.

Usually one line of code contains just one statement, but we can have as many statements on one line as you want.

PHP Opening and Closing Code is <?php and ?>

Hello World! Example:


<?php

echo "Hello World<br><h1>Hello From MaHi</h1>";

?>

The code above generates the following result.


Hello World
Hello From MaHi