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

Dynamic Link Creation

Dynamic Link

<!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=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?php $con = mysql_connect("localhost","root","");
mysql_select_db("123", $con);  $result = mysql_query("SELECT * FROM asd");
echo "<table border='1'> <tr> <th>Name</th> <th>Roll</th> </tr>";
while($row = mysql_fetch_array($result))
  {
  echo "<td>".$row['name']."</td>";
  echo "<td>" . $row['roll'] . "</td>";
  echo "<td><a href=\"view.php?id=".$row['id']."\">View</a>";
  echo "</tr>";   } echo "</table>";
  mysql_close($con); ?>
</body>
</html>

Dynamic Page Result:


<<!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=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<HTML>
<?php
$id=$_GET['id'];
$db = mysql_connect("localhost", "root", "");
mysql_select_db("123",$db);
$result = mysql_query("SELECT * FROM asd WHERE id=$id",$db);
$row = mysql_fetch_array($result);
echo "Name: ".$row["name"];
echo "<br>Roll: ".$row["roll"];
?>
</HTML>
</body>
</html>



PHP Email Verification

Overview

In this tutorial, create 4 PHP files and 2 databases
1. signup.php
2. signup_ac.php
3. confirmation.php
4. config.php

We have to create 2 databases
1. temp_members_db
2. registered_members

PHP Queries Order

You can order MySQL results using "ORDER BY"

1. ORDER BY column_name ASC
2. ORDER BY column_name DESC
3. ORDER BY RAND().

1. ORDER BY column_name ASC is order by ascending.
2. ORDER BY column_name DESC is order results by descending.
3. ORDE BY RAND() is order results by random.



Syntax

"SELECT column_name FROM table_name ORDER BY column_name ASC";
or
"SELECT column_name FROM table_name";
- This will select the records from mysql by ascending (ascending is the default value).

"SELECT column_name FROM table_name ORDER BY column_name DESC";
- This will select the records from mysql by descending

"SELECT column_name FROM table_name ORDER BY RAND()";
- This will select the records from mysql by random




Example Order by Ascending
order mysql result by ascending
The records were sorted by id by ascending
Example Order by Descending
order mysql result by descending
The records were sorted by id by descending
Example Order by Random
order mysql result by random
The records were sorted by random



PHP Retrieve Data (While loop)

<!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=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$database = "infra";

$conn = mysql_connect($hostname, $username, $password)
 or die("Connecting to MySQL failed");

mysql_select_db($database, $conn)
 or die("Selecting MySQL database failed");

$data = mysql_query("select * from search");
 while($info = mysql_fetch_array( $data ))
 {
 Print "<th>Name:</th> <td>".$info['name'] . "---";
 Print "<th>type:</th> <td>".$info['type'] . " <br>";
 }

?>
</body>
</html>

Dynamic Grid

Coding:

<?php
// Include database connectioninclude_once 'connect_to_mysql.php';// SQL query to interact with info from our database$sql mysql_query("SELECT id, member_name FROM member_table ORDER BY id DESC LIMIT 15"); $i 0;// Establish the output variable$dyn_table '<table border="1" cellpadding="10">';
while(
$row mysql_fetch_array($sql)){
   
    
$id $row["id"];
    
$member_name $row["member_name"];
   
    if (
$i == 0) { // if $i is divisible by our target number (in this case "3")
        
$dyn_table .= '<tr><td>' $member_name '</td>';
    } else {
        
$dyn_table .= '<td>' $member_name '</td>';
    }
    
$i++;
}
$dyn_table .= '</tr></table>';?><html>
<body>
<h3>Dynamic PHP Grid Layout</h3>
<?php echo $dyn_table?></body>
</html>



PHP Session

There is a relationship between Sessions and Cookies -- they serve somewhat the same purpose, and are, to a certain extent, usable interchangeably.  Sessions, which were integrated into PHP in version 4 of the language, are a means to store and track data for a user while they travel through a series of pages, or page iterations, on your site.


How Sessions Work
Sessions in PHP are started by using the session_start( ) function.  Like the setcookie( ) function, the session_start( ) function must come before any HTML, including blank lines, on the page.  It will look like this:
<?php
session_start( );
?>
<html>
<head> ....... etc


starting a php session

Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.

Below is a simple script that you should place at the beginning of your PHP code to start up a PHP session.

PHP Code:
<?php
session_start(); // start up your PHP session! 
?>


storing a session variable

When you want to store user data in a session use the $_SESSION associative array. This is where you both store and retrieve session data. In previous versions of PHP there were other ways to perform this store operation, but it has been updated and this is the correct way to do it.

PHP Code:
<?php
session_start(); 
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
?>
Display:
Pageviews = 1


cleaning and destroying your session

Although a session's data is temporary and does not require that you explicitly clean after yourself, you may wish to delete some data for your various tasks.

Imagine that you were running an online business and a user used your website to buy your goods. The user has just completed a transaction on your website and you now want to remove everything from their shopping cart.

PHP Code:
<?php
session_start();  
if(isset($_SESSION['cart']))
    unset($_SESSION['cart']); 
?>
You can also completely destroy the session entirely by calling the session_destroy function.

PHP Code:
<?php
session_start(); 
session_destroy();

?>


PHP Login Example:

Index.php:

<?php

$host="localhost"; // Host name
$username="root"; // username
$password="root"; // password
$db_name="TA"; // Database name
$tbl_name="user"; // Table name

mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");



$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
  // Register $myusername, $mypassword and redirect to file "login_success.php"
  session_start();
  $_SESSION['username'] = $myusername;
  $_SESSION['password'] = $mypassword; 
  header("location: login_success.php");

    else {
        echo "Wrong Username or Password";
}


?>

And codes for login_success.php :

<?php 
session_start(); 

if(!$_SESSION['username']){ 
    header("Location: index.html"); 
    exit; 

echo 'Welcome, '.$_SESSION['username']; 
header("Location: student-page.html");
?>

PHP Include Function

This function is used to insert the content of one PHP file into another PHP file before the server executes it.

Can be used multiple times:

<?php include("navigation.php"); ?>

Once only:

<?php include_once("navigation.php"); ?>

Including from the root:

<?php
   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/common/header.php";
   include_once($path);
?>

Inserting and displaying images in MySQL using PHP

Database:

create table test_image (
id int(10)  not null AUTO_INCREMENT PRIMARY KEY,
name   varchar(25) not null default '',
image  blob        not null
 );


file_constants.php

<?php
$host="your_hostname";
$user="your_databaseuser";
$pass="your_database_password";
$db="database_name_to_use";
?>

file_insert.php

<html>
<head><title>File Insert</title></head>
<body>
<h3>Please Choose a File and click Submit</h3>

<form enctype="multipart/form-data" action=
"<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input name="userfile" type="file" />
<input type="submit" value="Submit" />
</form>

<?php

// check if a file was submitted
if(!isset($_FILES['userfile']))
{
    echo '<p>Please select a file</p>';
}
else
{
    try {
    $msg= upload();  //this will upload your image
    echo $msg;  //Message showing success or failure.
    }
    catch(Exception $e) {
    echo $e->getMessage();
    echo 'Sorry, could not upload file';
    }
}

// the upload function

function upload() {
    include "file_constants.php";
    $maxsize = 10000000; //set to approx 10 MB

    //check associated error code
    if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {

        //check whether file is uploaded with HTTP POST
        if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {  

            //checks size of uploaded image on server side
            if( $_FILES['userfile']['size'] < $maxsize) {
 
               //checks whether uploaded file is of image type
              //if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
                 $finfo = finfo_open(FILEINFO_MIME_TYPE);
                if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {  

                    // prepare the image for insertion
                    $imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));

                    // put the image in the db...
                    // database connection
                    mysql_connect($host, $user, $pass) OR DIE (mysql_error());

                    // select the db
                    mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());

                    // our sql query
                    $sql = "INSERT INTO test_image
                    (image, name)
                    VALUES
                    ('{$imgData}', '{$_FILES['userfile']['name']}');";

                    // insert the image
                    mysql_query($sql) or die("Error in Query: " . mysql_error());
                    $msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
                }
                else
                    $msg="<p>Uploaded file is not an image.</p>";
            }
             else {
                // if the file is not less than the maximum allowed, print an error
                $msg='<div>File exceeds the Maximum File limit</div>
                <div>Maximum File limit is '.$maxsize.' bytes</div>
                <div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
                ' bytes</div><hr />';
                }
        }
        else
            $msg="File not uploaded successfully.";

    }
    else {
        $msg= file_upload_error_message($_FILES['userfile']['error']);
    }
    return $msg;
}

// Function to return error message based on error code

function file_upload_error_message($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}
?>
</body>
</html>

file_display.php

<?php
 include "file_constants.php";
 // just so we know it is broken
 error_reporting(E_ALL);
 // some basic sanity checks
 if(isset($_GET['id']) && is_numeric($_GET['id'])) {
     //connect to the db
     $link = mysql_connect("$host", "$user", "$pass")
     or die("Could not connect: " . mysql_error());

     // select our database
     mysql_select_db("$db") or die(mysql_error());

     // get the image from the db
     $sql = "SELECT image FROM test_image WHERE id=" .$_GET['id'] . ";";

     // the result of the query
     $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());

     // set the header for the image
     header("Content-type: image/jpeg");
     echo mysql_result($result, 0);

     // close the db link
     mysql_close($link);
 }
 else {
     echo 'Please use a real id number';
 }
?>
Now you can see the images stored in the database using the following query string-:

http://{path_to_your_web_directory}/file_display.php?id=1

PHP Global Variables

PHP $_SERVER:

$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

Example:

<!DOCTYPE html>
<html>
<body>

<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

</body>
</html>

PHP $GLOBAL:

$GLOBAL is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods).

Example:

<?php
$x = 75;
$y = 25;

function addition()
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>

PHP $_REQUEST:

PHP $_REQUEST is used to collect data after submitting an HTML form.

Example:

<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
$name = $_REQUEST['fname'];
echo $name;
?>
</body>
</html>

PHP $_POST:

PHP $_POST is widely used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.

Example:

<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
$name = $_POST['fname'];
echo $name;
?>

</body>
</html>

PHP $_GET:

PHP $_GET can also be used to collect form data after submitting an HTML form with method="get".

Example:

<!DOCTYPE html>
<html>
<body>

<a href="test_get.php?subject=SaribAli">Test $GET</a>

</body>
</html>

Connection String

PHP5 :

<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

OLD Method:

<?php
$username = "";
$password = "";
$hostname = "localhost";
$database = "";

$conn = mysql_connect($hostname, $username, $password)
or die("Connecting to MySQL failed");

mysql_select_db($database, $conn)
or die("Selecting MySQL database failed");

mysql_close($conn);
?>


PHP Calculator

<?php
ini_set('display_errors',0);
ifisset( $_REQUEST['calculate'] ))
{
$operator=$_REQUEST['operator'];
if($operator=="+")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res= $add1+$add2;
}
if($operator=="-")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res= $add1-$add2;
}
if($operator=="*")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res =$add1*$add2;
}
if($operator=="/")
{
$add1 = $_REQUEST['fvalue'];
$add2 = $_REQUEST['lvalue'];
$res= $add1/$add2;
}
if($_REQUEST['fvalue']==NULL && $_REQUEST['lvalue']==NULL)
{
echo "<script language=javascript> alert(\"Please Enter values.\");</script>";
}
else if($_REQUEST['fvalue']==NULL)
{
echo "<script language=javascript> alert(\"Please Enter First value.\");</script>";
}
else if($_REQUEST['lvalue']==NULL)
{
echo "<script language=javascript> alert(\"Please Enter second value.\");</script>";
}
}
?>
<form>
<table style="border:groove #00FF99">
            <tr>
                <td style="background-color:aquacolor:redfont-family:'Times New Roman'">Enter First Number</td>
                <td colspan="1">
               
                    <input name="fvalue" type="text" style="color:red"/></td>
            <tr>
                <td style="color:burlywoodfont-family:'Times New Roman'">Select Operator</td>
                <td>
                    <select name="operator" style="width63px">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select></td>
               </tr>
            <tr>
                <td style="background-color:aquacolor:redfont-family:'Times New Roman'">Enter First Number</td>
                <td class="auto-style5">
                    <input name="lvalue" type="text"  style="color:red"/></td>
               
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="calculate" value="Calculate" style="color:wheat;background-color:rosybrown" /></td>
               
            </tr>
            <tr>
                <td style="background-color:aqua;color:red">Output = </td>
                <td style="color:darkblue"><?php echo $res;?></td>
               
            </tr>
       </table>
 </form>