What Is a Sitemap?

using XML Sitemaps can help showcase
your most important links it would
be foolish not to utilize Webmaster Tools, as it is an indispensable resource for conducting
SEO.

Major Search Engine?

The name of bots/spider of Google search engineis GoogleBot, Yahoo Slurp for Yahoo search andBingBot for Bingsearch engine.

Why the Title Tag in Website is implemented for optimization?

Your page titles will show up in the SERPs, so make them concise and relevant.

Internal optimization refers to on-page and on-site activities. On-page activities include
keyword optimizations of <title> tags, description meta tags, page copy, and link
anchor text.

Concentrate on making easy, clear-cut, and logical interfaces with a focus on getting
to the right information quickly. Link anchor text should be of reasonable size and
should be similar to, or the same as, the destination page’s HTML title tag text (if it
exists).

TITLE element to identify the contents of a document. Since
users often consult documents out of context, authors should provide context-rich titles.
Thus, instead of a title such as “Introduction”, which doesn’t provide much contextual
background, authors should supply a title such as “Introduction to Medieval Bee-
Keeping” instead.
One of the most critical on-page factors, the <title> tag is not to be dismissed. Search
engines tend to use the <title> tag text as search results titles. All pages should have
unique page titles. All page titles should be crafted wisely, using the most important
keywords found in the page copy.

The svg element HTML5

The <svg> element allows the author to build a vector-based image directly in
the page using the SVG markup language.

<svg xmlns:xlink=”http://www.w3.org/1999/xlink”
xmlns=”http://www.w3.org/2000/svg”
viewBox=”0 0 200 100”
width=”200px” height=”100px”>
<circle cx=”50” cy=”50” r=”30”
style=”stroke:#0000ff; stroke-width: 5px;
fill:#ff0000;”/>
<rect x = ”100”
y = ”0”
height = ”50”
width = ”50”
stroke-width = ”2px”
stroke = ”#ffff00”
fill = ”#00ff00” />
</svg>

The context object drawing functionality HTML5

arc(): The arc command draws an arc (portion of a circle) as part of a
path. The arc is defined like a circle, with a center and radius, but also with
beginning and ending angles. If the angles describe a full circle (0 to 2 × pi
radians), the arc command will draw a full circle. See the preceding example
for a custom circle function created from the arc command.

beginPath(): This command begins the definition of a path. Normally a
path is defined by a single moveTo command, followed by a series of
lineTo commands, and finished by a stroke, closePath, or fill.

closePath(): This command connects the last point of a path (drawn
with moveTo and lineTo commands) to the first, creating a closed shape
that can be filled.

drawImage(): The drawImage command allows you to draw an image (from
an external image file) on the canvas. Many implementations allow pixel-level
manipulation, allowing you to apply custom filters and transformations to
your images, which allows far more control than the typical <img> tag.

 fill(): The fill command (and its variants — like fillRect) allows you to
apply the current fill style to elements drawn on the screen.

 fillRect(): This command builds a rectangle of a specified size and
position, filled in with the current fill style.

fillStyle(): Allows you to specify the fill style. This can be a standard
color value, or a predefined gradient.

 lineTo(): This command (along with the moveTo command) allows you
to build a path on the screen. The lineTo command takes a point as input
and draws from a previously defined point to the current point. Note that
the path is not displayed until the application of the stroke function.

lineWidth(): This defines the width of the line being drawn by a stroke
command.

 moveTo: Used in path definition, the moveTo command is used to indicate
the starting point of a path.

stroke(): This command draws the currently defined path. Note that
paths are not immediately drawn; the stroke command actually draws the
path on the screen.

The canvas tag HTML5

The <canvas> tag sets up a portion of the screen for program-controlled graphics.
The HTML simply sets aside a portion of the screen to be used as a canvas.
All the drawing and manipulation of the image is done through JavaScript code.
The following HTML code sets up a canvas element and provides a button.

<canvas id = “myCanvas”
width = “300”
height = “200”>
This example requires HTML5 canvas support
</canvas>
<button type = “button”
onclick = “draw()”>
click me to see a drawing
</button>



The canvas element does little on its own. To do anything interesting with the
canvas tag, use JavaScript to extract a drawing context (a special element that
can be drawn on) and use the methods of that context object to create dynamic
graphics. For example, here is the draw() function that will be enabled when
the user clicks the button

function draw(){
var myCanvas = document.getElementById(“myCanvas”);
var context = myCanvas.getContext(“2d”);
context.fillStyle = “blue”;
context.strokeStyle = “red”;
circle(context, 1, 1, 1);
for (i = 1; i <= 200; i+= 2){
circle(context, i, i, i, “blue”);
circle(context, 300-i, 200-i, i, “red”);
circle(context, 300-i, i, i, “blue”);
circle(context, i, 200-i, i, “red”);
} // end for
} // end draw
function circle(context, x, y, radius, color){
context.strokeStyle = color;
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2, true);
context.stroke();
} // end circle

video element of HTML5.

The video element is one of the more anticipated features of HTML5. With this
tag, developers will be able to embed videos into a Web page without requiring
a plugin like Flash.

<video src = “bigBuck.ogv” controls>
Your browser does not support embedded video
through HTML5.
</video>


The <video> tag itself is pretty simple to understand, but the actual implementation
is somewhat complex. HTML5 indicates a video tag, but it doesn’t specify
what format the browser will support. It will not surprise you that all the
browser manufacturers have a different opinion about which format will be supported.
At the moment, there are three main video formats in contention.


If you want to incorporate HTML5 video, use the <source> tag to include all the
major formats. (You can use the free FFmpeg tool available for all major software
platforms to convert your videos.) As a final fallback, use the <embed> tag inside
your <video> tag to load the video with a Flash player.
You can use JavaScript to control the video element in the same way you control
audio. See the “audio” section earlier in this part for more information
about controlling your media elements through JavaScript code.

The details Element HTML5

This new element helps mark up a section of the document that’s hidden, but can
be expanded to reveal additional information. The aim of the element is to provide
native support for a feature common on the Web—a collapsible box that has a title,
and more info or functionality hidden away.
Normally this kind of widget is created using a combination of markup and scripting.
The inclusion of it in HTML5 intends to remove the scripting requirements and
simplify its implementation for web authors.

<details>
<summary>Some Magazines of Note</summary>
<ul>
<li><cite>Bird Watchers Digest</cite></li>
<li><cite>Rowers Weekly</cite></li>
<li><cite>Fishing Monthly</cite></li>
</ul>
</details>


If details lacks a defined summary, the user agent will define a default summary
(for example, “Details”). If you want the hidden content to be visible by default,
you can use the Boolean open attribute.

The head Element HTML5

The next part of our page is the <head> section. The first line inside the head is the
one that defines the character encoding for the document. This is another element
that’s been simplified. Here’s how you used to do this:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
HTML5 improves on this by reducing the character encoding <meta> tag to the bare
minimum:
<meta charset="utf-8">

In nearly all cases, utf-8 is the value you’ll be using in your documents.

The html Element HTML5

Next up in any HTML document is the html element, which has not changed significantly
with HTML5. In our example, we’ve included the lang attribute with a
value of en, which specifies that the document is in English. In XHTML-based
syntax, you’d be required to include an xmlns attribute. In HTML5, this is no longer
needed, and even the lang attribute is unnecessary for the document to validate or
function correctly.



<!doctype html>
<html lang="en">
</html>

The Doctype HTML5

First, we have the Document Type Declaration, or doctype. This is simply a way to
tell the browser—or any other parsers—what type of document they’re looking at.
In the case of HTML files, it means the specific version and flavor of HTML. The
doctype should always be the first item at the top of all your HTML files. In the
past, the doctype declaration was an ugly and hard-to-remember mess.

HTML5
has done away with that indecipherable eyesore. Now all you need is this:

<!doctype html>

A Basic HTML5 Template

As you learn HTML5 and add new techniques to your toolbox, you’re likely going
to want to build yourself a blueprint, or boilerplate, from which you can begin all
your HTML5-based projects. In fact, you’ve probably already done something similar
for your existing XHTML or HTML 4.0 projects. We encourage this, and you
may also consider using one of the many online sources that provide a basic HTML5
starting point for you.
In this project, however, we want to build our code from scratch and explain each
piece as we go along. Of course, it would be impossible for even the most fantastical
and unwieldy sample site we could dream up to include every new element or
technique, so we’ll also explain some new features that don’t fit into the project.
This way, you’ll be familiar with a wide set of options when deciding how to build
your HTML5 and CSS3 websites and web apps, so you’ll be able to use this book
as a quick reference for a number of techniques.


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]-->
</head>
<body>
1

What is a cookie , explaing ?

Cookie is use to store the temporary data in browser memory, We can store data in cookies using setcookie('name','value','time');
we can use that rule for simple cookie, this value will store in the browser memory. If the browser is closed the cookie value will be deleted. Another way to store data in cookie file for long time:
persistent cookie using that way we can store data for long time in the user system.

How can we find the number of rows in a MySQL table?

By Mysql

SELECT COUNT(*) FROM table_name;

How to prevent hijacking in PHP?

 Make Error_reporting to E_ALL so that all variables will be intialized before using them.
 Make practice of using htmlentities(), strip_tags(), utf8_decode() and addslashes() for filtering malicious data in php
 Make practice of using mysql_escape_string() in mysql.

What is difference between mysql_fetch_array(),mysql_fetch_row() and mysql_fetch_object() ?

mysql_fetch_array():: fetches a result row as a associated array, numeric array

mysql_fetch_object: Fetaches a result row as object.

mysql_fetch_row::fetches a result row as array

SELECTING DATA IN PHP

You frequently select data in a MySQL table using PHP. Selecting data through a PHP program
using a MySQL command takes four steps:
1. Make a connection to the database.
2. Create a safe query with the command.
3. Run the query.
4. Read the results.
The following code makes the connection and creates a safe query. Rather than just running the
query, use it as the right side of an assignment. This creates a mysqli_result object that you use to
read the results via methods in the result object. This example takes each row, one at a time,
and puts it into an associative array.


<?php
define(“MYSQLUSER”, “php24sql”);
define(“MYSQLPASS”, “hJQV8RTe5t”);
define(“HOSTNAME”, “localhost”);
define(“MYSQLDB”, “test”);
// Make connection to database
$connection = @new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS, MYSQLDB);
if ($connection->connect_error) {
die(‘Connect Error: ‘ . $connection->connect_error);
} else {
echo ‘Successful connection to MySQL <br />’;
// Set up the query
$query = “SELECT * FROM ‘table1‘ “
. “ WHERE ‘code‘ = 15”
. “ ORDER BY ‘description‘ ASC “
;
// Run the query
$result_obj = ‘’;
$result_obj = $connection->query($query);
// Read the results
// loop through the result object, row by row
// reading each row into an associative array
while($result = $result_obj->fetch_array(MYSQLI_ASSOC)) {
// display the array
print_r($result);
echo ‘<br />’;
}
}

// Read the results
// loop through the results, row by row
// reading each row into an associative array
while($result = $result_obj->fetch_array(MYSQLI_ASSOC)) {
// collect the array
$item[] = $result;
}
// print array when done
echo ‘<pre>’;
print_r($item);
echo ‘</pre>’;


The example prints out the array









fetch_array(MYSQLI_ASSOC): This returns an associative array. Loop through to get all the
rows. Same as fetch_assoc().
‰ fetch_array(MYSQLI_NUM): This returns a numeric array. Loop through to get all the rows.
Same as fetch_row().
‰ fetch_array(MYSQLI_BOTH): This returns both an associative array and a numeric array
with the same data. Loop through to get all the rows. This is the default if no type is
specifi ed.
‰ fetch_all(MYSQLI_ASSOC): This returns all the rows as an associative array.
‰ fetch_all(MYSQLI_NUM): This returns all the rows as a numeric array.
‰ fetch_all(MYSQLI_BOTH): This returns all the rows both as an associative array and a
numeric array with the same data.
‰ fetch_object($class_name): This returns an object of the row. Loop through to get all
the rows. If you give it a class name, it uses that class to create the object. If there is no class
name it will create a stdClass object, which is a predefi ned class.

Optimizing for Both Facebook and Search Engines

You’re probably familiar with search engine optimization (SEO) tactics for improving your website’s
search rankings in Google and other major search engines. But have you thought about how to incorporate
social media into your search strategy?
Facebook can be a valuable asset for search results. The volume of content and variety of places to add
keyword-rich content can help you attract new Page members on Facebook, while providing more natural
search results
Facebook is indexed by search engines and also has deals with Google
and Bing to display social search results that include posts from your friends.
Facebook’s search is not always the greatest at displaying results, but the site’s working on it.
Counteract its shortcomings with some rockstar SEO to ensure that people looking for your name or
service can find you. Misspellings are especially important to account for on Facebook.
In the more general natural-search realm, a well-optimized Facebook Page can help you overtake
a competitor by providing a second set of Pages (in addition to your own website) to display on the
search results page. This can also be helpful when you’re looking to do some reputation management.
A Facebook Page can also give you the opportunity to add a few more keywords that didn’t work as
well on your website..

Developing a Facebook Content Strategy

Given the restrictions Facebook places on Page design, content is the easiest—and often most
effective—
way to differentiate yourself from competitors. Facebook’s power lies in its huge number
of users, but this also creates a high volume of posts. To reach these potential customers or brand
enthusiasts, your content must stand apart from the rest. Because content is a core piece of a successful
Facebook marketing campaign, this chapter explores ways you can create and optimize it for
Page members, while at the same time improving your placement in both Facebook and natural web
searches.

Competing with Other Content on Facebook
The average Facebook user has 130 friends and is connected to 80 community Pages, Groups, and
Events. Yet this is only a fraction of the 900 million people, places, and things that he could interact with
on Facebook

Considering the more than 30 billion pieces of content being shared across
the site each month, you can understand clearly why content is a key factor in your Facebook marketing
strategy. Obviously, there’s a lot that the average user is seeing on a daily basis. But this average user
also creates about 90 pieces of content every month—posting links to news stories or blog posts, writing
notes, uploading to photo albums, creating Events, writing on friends’ Walls, and more.

Since Facebook imposes so many design restrictions, content is the best way to market yourself to
potential Page members (and future customers), as well as to keep current Page members and customers
engaged and entertained. On the other hand, you must also combat the fatigue many users feel at
seeing a never-ending stream of their friends’ lunch orders, random thoughts, and recent likes.

What Is a Session?

It is stored at server side because PHP is server side scripting language

Session is stored on server side because how much time page will execute it doesn't depend on client it depends on server. Server decide the session of each page ..thats why session is stored on server side

Session is to store as the server side value
method $_session start('id');
and cookie is store the validation of client side

How do you define a constant in php?

by define() directive,
like define (“MYCONSTANT”, 500);

THE DIFFERENT TYPES OF ERRORS IN PHP?

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined
2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.
Internally, these variations are represented by twelve different error types

What’s the special meaning of __sleep and __wakeup?

__sleep returns the array of all the variables than need to be saved,
while __wakeup retrieves them.

What is the difference between $age and $$age

They are both variables. But $age is a variable with a fixed name. $$age is a variable who’s name is stored in $age. For example, if $age contains “var”, $$age is the same as $var.

$test = ‘abcd';
is equivalent to
$holder = ‘test';
 $$holder = ‘abcd';

How many values can the SET function of MySQL take?

MySQL set can take zero or more values but at the maximum it can
take 64 values

What is the maximum size of a file that can be uploaded using PHP and how can we change this?

By default the maximum size is 2MB.
 can change the size
 setup at php.ini
upload_max_filesize = 12M

How can we get the browser properties using PHP?

$_SERVER['HTTP_USER_AGENT'];

How can we encrypt the username and password using PHP?

The functions in this section perform encryption and decryption

encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()

count the elements of an array?

sizeof($array) – This function is an alias of count()

 count($urarray) – This function returns the number of elements in an array.

sorting an array?

arsort()
sort()
natsort()

What are “GET” and “POST”?

GET: we are submitting a form to login.php, when we do submit or similar action, values are sent through visible query string (notice ./login.php?username=…&password=… as URL when executing the script login.php) and is retrieved by login.php by $_GET['username'] and $_GET['password'].

POST: we are submitting a form to login.php, when we do submit or similar action, values are sent through invisible standard input (notice ./login.php) and is retrieved by login.php by $_POST['username'] and $_POST['password'].

POST method data is sent by standard input (nothing shown in URL when posting while in GET method data is sent through query string.



  • PHP - Echo?php $myiString = "Hi!"; echo $myiString; echo "I love PHP!"; ?   Display: Hi! I love  PHP!  A simple form example     1 2 3 Building a Form 4 5 6 " 7 method="get" 8 9 Search: 10 1… Read More
  • PHP Array Functionsarray_change_key_case — Changes all keys in an array array_chunk — Split an array into chunks array_combine — Creates an array by using one array for keys and another for its values array_count_values — Counts all the value… Read More
  • Php Directory Functionschdir — Change directory chroot — Change the root directory closedir — Close directory handle dir — Return an instance of the Directory class getcwd — Gets the current working directory opendir — Open directory handle read… Read More
  • Php Mysql Image upload?php // 1. Gem modtagne formulardata i variabler: $navn = $_POST['navn']; $alder = $_POST['alder']; $postnr = $_POST['postnr']; $mail = $_POST['mail']; $billede = $_FILES['profilbillede']; $password = $_POST['… Read More
  • PHP MySQL Functionsmysql_field_len — Returns the length of the specified field mysql_field_name — Get the name of the specified field in a result mysql_field_seek — Set result pointer to a specified field offset mysql_field_table — Get … Read More
  • Length of a StringThe length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string: integer strlen(string subject) We used strlen( ) earlier in the chapter t… Read More
  • Defining FunctionsThere are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the function statement: function some_function([argumen… Read More
  • PHP HTTP Functionsob_deflatehandler — Deflate output handler ob_etaghandler — ETag output handler ob_inflatehandler — Inflate output handler http_parse_cookie — Parse HTTP cookie http_parse_headers — Parse HTTP headers http_parse_message — P… Read More
  • PHP Date / Time Functionscheckdate — Validate a Gregorian date date_add — Alias of DateTime::add date_create_from_format — Alias of DateTime::createFromFormat date_create — Alias of DateTime::__construct date_date_set — Alias of DateTime::setDate …Read More
  • PHP Zip File Functionszip_close — Close a ZIP file archive zip_entry_close — Close a directory entry zip_entry_compressedsize — Retrieve the compressed size of a directory entry zip_entry_compressionmethod — Retrieve the compression meth… Read More
  • Including and Requiring PHP FilesTo make your code more readable, you can place your functions in a separate file. Many PHP add-ons that you download off the Internet contain functions already placed into files that you simply include in your PHP program… Read More
  • Creating ArraysPHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use: $numbers = array(5, 4, 3, 2, 1);… Read More
  • File Manipulation11.3. File Manipulation There may be times when you don't want to store information in a database and may want to work directly with a file instead. An example is a logfile that tracks when your application can't co… Read More
  • PHP Configuration DirectivesAlthough the focus of this book is application security, there are a few configuration directives with which any security-conscious developer should be familiar. The configuration of PHP can affect the behavior of the cod… Read More
  • Showing the Browser and IP AddressHere is a simple page that prints out the browser string and the IP address of the HTTP request. Create a file with the following content in your web directory, name it something like example.php3, and load it in your bro… Read More
PHP Functions
Php tutorial - imagemagick
php.ini Basics
PHP Sessions
Cookies Versus Sessions
PHP Web-Related Variables
PHP ERRORS
maximum size of a file uploaded
Php Image upload
php file_get_contents
MySQL Data on the Web
What are GET and POST
php and pdf
$_ENV and $_SERVER
PEAR with php
SELECTING DATA PHP
prevent hijacking with PHP
LAMP
PHP MySQL Functions
PHP Zip File Functions
Substrings PHP
PHP Variable names
PHP magic methods
How to get current session id
Add variables into a session
$_GET , $_POST,$_COOKIE
different tables present in mysql
PHP CURL
php Sessions page
PHP-sorting an array
PHP-count the elements of array
Operators for If/Else Statements
PHP file uploading code
PHP global variables
Testing working using phpinfo
PHP Code for a Valid Number
PHP-Associative Arrays
PHP mvc tutorial
PHP get_meta_tags-Extracts
difference between print and echo
PHP best tutorial-PHP variables
Reading DOC file in PHP
PHP interview questions
convert time PHP
PHP implode array elements
header function-PHP
PHP-Renaming Files Directories
PHP Classes
in_array function in PHP
keep your session secure PHP
Web Application with PHP
What is SQL Injection
PHP-extract part of a string
PHP urlencode
PHP- know browser properties
PHP- Extracting Substrings
Checking Variable Values /Types
PHP-best 20 Open Source cms
IP AddressPHP
PHP-Scope Resolution Operator
how create new instance of object
how eliminate an object
PHP- ob_start
XML file using the DOM API
PHP- MVC
PHP- CAPTCHA
PHP- Position of a Value in an Array
PHP-Mail Functions
PHP-difference include vs require
calculate the sum of values in an array
PHP-total number of rows
Show unique records mysql
MySQL Triggers
MySQL data directory
MySQL Subqueries
PHP- Networking Functions
PHP- Operators
Restore database
Conditional Functions mysql
PHP-function overloading
Friend function
mysql_connect /mysql_pconnect
PHP-Error Control Operators
what is IMAP
Apache-Specific Functions
Send Email from a PHP Script
SQL inherently
WAMP, MAMP, LAMP
Php tutorial-SYMBOLS
Table Types-MySQL
PHP-Encryption data management
PHP Array
Running MySQL on Windows
Maximum Performance MySQL
XML-RPC
PHP-static variables
Advanced Database Techniques
FTP
Codeigniter
Apache Pool Size
Why NoSQL
MySQL Server Performance
Database software
SQL Interview Answers
PHP Redirect
PHP Interview Questions with Answers
Advanced PHP

What is the default session time in php and how can I change it?

The default session time in php is until closing of browser

What are the MySQL database files stored in system ?

Data is stored in name.myd
Table structure is stored in name.frm
Index is stored in name.myi

What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array.
mysql_fetch_object() -> Fetch a result row as an object.
mysql_fetch_row() -> Fetch a result set as a regular array().

What Is a Persistent Cookie?

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
*Temporary cookies can not be used for tracking long-term information.
*Persistent cookies can be used for tracking long-term information.
*Temporary cookies are safer because no programs other than the browser can access them.
*Persistent cookies are less secure because users can open cookie files see the cookie values.

What function can be used to encode passwords for storage in the database

The md5() function creates a one-way encoding of the password.

Where is the data for a cookie stored?

Cookies are stored on the web user's hard drive.

How can we get second of the current time using date function?

$second = date("s");

php and pdf

 Documents and Pages

A PDF document is made up of a number of pages. Each page contains text and/or images.Put text onto
 the pages, and send the pages back to the browser when you're done.

 
 
<?php

require("../fpdf/fpdf.php"); // path to fpdf.php

$pdf = new FPDF(  );
$pdf->AddPage(  );
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello Out There!');
$pdf->Output(  );

?>
 follows the basic steps involved in creating a PDF document.

The cell concept in the FPDF Library is that of a rectangular area on the page that you can create and control.
 This cell can have a height, width, a border, and of course can contain text.
The basic syntax for the cell method is as follows:
Cell(float w [, float h [, string txt [, mixed border [, int ln [, 
string align [, int fill [, mixed link]]]]]]])

The first option is the width, then the height, then the text to be outputted, then border, then new line control, then its alignment, any fill colour for the text, and finally if you want the text to be an HTML link. So, for example, if we want to change our original example to have a border and be center
 aligned we would change the cell code to the following:
$pdf->Cell(90,10,'Hello Out There!',1,0,'C');

The cell method is used extensively while generating PDF documents with fpdf,

Demonstrating coordinates and line management

<?php
require("../fpdf/fpdf.php");

$pdf = new FPDF('P', 'in', 'Letter');
$pdf->AddPage(  );
$pdf->SetFont('Arial','B',24);
// Cell(W, H, 'text', Border, Return, 'Allign') - basic syntax
$pdf->Cell(0,0,'Top Left!',0,1,'L');
$pdf->Cell(6,0.5,'Top Right!',1,0,'R');
$pdf->ln(4.5);
$pdf->Cell(0,0,'This is the middle!',0,0,'C');
$pdf->ln(5.3);
$pdf->Cell(0,0,'Bottom Left!',0,0,'L');
$pdf->Cell(0,0,'Bottom Right!',0,0,'R');
$pdf->Output(  );
?>

Declaring a Class

To design your program or code library in an object-oriented fashion, you'll need to define your own classes, using the class keyword.
A class definition includes the class name and the properties and methods of the class. Class names are case-insensitive and must conform to the rules for PHP identifiers. The class name stdClass is reserved. Here's the syntax for a class definition:
 
 
class classname [ extends baseclass ]
    {
        [ var $property [ = value ]; ... ]

        [ function functionname (args) {
              // code
          }
          ...
        ]
    }
 
 

Declaring Methods

A method is a function defined inside a class. Although PHP imposes no special restrictions, most methods act only on data within the object in which the method resides. Method names beginning with two underscores (_ _) may be used in the future by PHP (and are currently used for the object serialization methods _ _sleep( ) and _ _wakeup( ), described later in this chapter, among others), so it's recommended that you do not begin your method names with this sequence.
Within a method, the $this variable contains a reference to the object on which the method was called. For instance, if you call $rasmus->birthday( ) inside the birthday( ) method, $this holds the same value as $rasmus. Methods use the $this variable to access the properties of the current object and to call other methods on that object.

Here's a simple class definition of the Person class that shows the $this variable in action:
class Person { var $name; function get_name ( ) { return $this->name; } function set_name ($new_name) { $this->name = $new_name; } }
 
 
As you can see, the get_name( ) and set_name( ) methods use $this to access and set the $name property of the current object.
To declare a method as a static method, use the static keyword. Inside of static methods the variable $this is not defined. For example:

class HTML_Stuff {
static function start_table( ) {
echo "<table border='1'>\n";
 } static function end_table ( ) {
echo "</table>\n";
}
}
HTML_Stuff::start_table( ); // print HTML table rows and columns HTML_Stuff::end_table( );


Declaring Properties

In the previous definition of the Person class, we explicitly declared the $name property. Property declarations are optional and are simply a courtesy to whoever maintains your program. It's good PHP style to declare your properties, but you can add new properties at any time.
Here's a version of the Person class that has an undeclared $name property:
    class Person {
        function get_name (  )
        {
            return $this->name;    }

        function set_name ($new_name) {
            $this->name = $new_name;
        }
    }

You can assign default values to properties, but those default values must be simple constants:
    var $name = 'J Doe';       // works
    var $age  = 0;             // works
    var $day  = 60*60*24;      // doesn't work

Using access modifiers, you can change the visibility of properties. Properties that are accessible outside the object's scope should be declared public; properties on an instance that can only be accessed by methods within the same class should be declared private.
 

Sorting One Array at a Time

PHP functions for sorting an array
Effect
Ascending
Descending
User-defined order
Sort array by values, then reassign indices starting with 0
sort( )
rsort( )
usort( )
Sort array by values
asort( )
arsort( )
uasort( )
Sort array by keys
ksort( )
krsort( )
uksort( )

The sort( ), rsort( ), and usort( ) functions are designed to work on indexed arrays because they assign new numeric keys to represent the ordering. They're useful when you need to answer questions such as, "What are the top 10 scores?" and "Who's the third person in alphabetical order?" The other sort functions can be used on indexed arrays, but you'll only be able to access the sorted ordering by using traversal functions such as foreach and next 

To sort names into ascending alphabetical order, you'd use this:
    $names = array('cath', 'angela', 'brad', 'dave');
    sort($names);                // $names is now 'angela', 'brad', 'cath', 'dave'

To get them in reverse alphabetic order, simply call rsort( ) instead of sort( ).
If you have an associative array mapping usernames to minutes of login time, you can use arsort( ) to display a table of the top three, as shown here:
    $logins = array('njt' => 415,
                    'kt'  => 492,
                    'rl'  => 652,
                    'jht' => 441,
                    'jj'  => 441,
                    'wt'  => 402);
    arsort($logins);
    $num_printed = 0;
    echo("<table>\n");
    foreach ($logins as $user => $time ) {
      echo("<tr><td>$user</td><td>$time</td></tr>\n");
      if (++$num_printed == 3) {
        break;                   // stop after three
      }
    }
    echo("</table>\n");
    <table>
    <tr><td>rl</td><td>652</td></tr>
    <tr><td>kt</td><td>492</td></tr>
    <tr><td>jht</td><td>441</td></tr>
    </table>

If you want that table displayed in ascending order by username, use ksort( ):
    ksort($logins);
    echo("<table>\n");
    foreach ($logins as $user => $time) {
      echo("<tr><td>$user</td><td>$time</td></tr>\n");
    }
    echo("</table>\n");
    <table>
    <tr><td>jht</td><td>441</td></tr>
    <tr><td>jj</td><td>441</td></tr>
    <tr><td>kt</td><td>492</td></tr>
    <tr><td>njt</td><td>415</td></tr>
    <tr><td>rl</td><td>652</td></tr>
    <tr><td>wt</td><td>402</td></tr>
    </table>

User-defined ordering requires that you provide a function that takes two values and returns a value that specifies the order of the two values in the sorted array. The function should return 1 if the first value is greater than the second, -1 if the first value is less than the second, and 0 if the values are the same for the purposes of your custom sort order.
 a program that lets you try the various sorting functions on the same data.

 

How to Read an RSS Feed With PHP

<?php
include("../includes/config.php");
include("../includes/dbcon.php");

$tt_res=mysql_query("SELECT *
FROM `rss_data`");

$num = mysql_num_rows($tt_res);
if($num!=0)
{
$tt="TRUNCATE TABLE `rss_data`";
mysql_query($tt);
}



//get the q parameter from URL
$q="yy";

//find out which feed was selected
if($q=="Google")
  {
  $xml=("http://news.google.co.in/news?pz=1&cf=all&ned=in&hl=en&topic=s&output=rss");
  }
elseif($q=="yy")
  {
  $xml=("http://in.news.yahoo.com/rss/cricket");
  }

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;



//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=5; $i++)
  {
  $item_title=$x->item($i)->getElementsByTagName('title')
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_link=$x->item($i)->getElementsByTagName('link')
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_desc=$x->item($i)->getElementsByTagName('description')
  ->item(0)->childNodes->item(0)->nodeValue;
 
  $item_title1=addslashes($item_title);
   $item_desc1=addslashes($item_desc);
 
echo $kk="INSERT INTO `rss_data` (
`item_title` ,
`item_desc`
)
VALUES (
 '".$item_title1."', '".$item_desc1."'
)";

mysql_query($kk);


  }
?>

mysqli Fetch Methods

If you prefer different MySQL fetch methods, they're also in mysqli. Given the same query of SELECT username FROM users, these example functions all print the same results:
// Fetch numeric arrays:

while ($row = mysqli_fetch_row($result)) {

    print $row[0] . "\n";

}



// Alternative syntax:

while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {

    print $row[0] . "\n";

}



// Alternative associative array syntax:

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

    print $row['username'] . "\n";

}



// Both numeric and associative:

while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {

    print $row[0] . "\n";

    print $row['username'] . "\n";

}



// Fetch as "object"

while ($row = mysqli_fetch_object($result)) {

    print $row->username . "\n";

}

XML Extensions in PHP 5

SimpleXML
A new PHP 5-only extension that excels at parsing RSS files, REST results, and configuration data. If you know the document's format ahead of time, SimpleXML is the way to go. However, SimpleXML supports only a subset of the XML specification.

XPath
This extension allows you to query XML documents like you're searching a database, to find the subset of information that you need and eliminate the unnecessary portions.


 XSLT
A way to take XML documents and transform them into HTML or another output format. It uses XML-based stylesheets to define the templates. XSLT is easily shared among different applications, but has a quirky syntax.

 

  • Reading XML into a tree
  • Reading XML from a stream
  • Creating new XML documents
  • Searching XML with XPath
  • Changing XML into HTML or other output formats with XSLT
  • Validating XML to ensure it conforms to a specification



    Example XML address book
    <?xml version="1.0"?>
    
    <address-book>
    
        <person id="1">
    
            <!--Rasmus Lerdorf-->
    
            <firstname>Rasmus</firstname>
    
            <lastname>Lerdorf</lastname>
    
            <city>Sunnyvale</city>
    
            <state>CA</state>
    
            <email>rasmus@php.net</email>
    
        </person>
    
    
    
        <person id="2">
    
            <!--Zeev Suraski-->
    
            <firstname>Zeev</firstname>
    
            <lastname>Suraski</lastname>
    
            <city>Tel Aviv</city>
    
            <state></state>
    
            <email>zeev@php.net</email>
    
        </person>
    
    </address-book>
     
     
     



    $dom = new DOMDocument;
    
    $dom->preserveWhiteSpace = false;
    
    $dom->load('address-book.xml');
    
    
    
    $root = $dom->documentElement;
    
    
    
    foreach ($root->childNodes as $person) {
    
        process($person);
    
    }

     

    The childNodes attribute is not an array, but a DOMNodeList object. The item( ) method allows you to access individual items, and the length property tells you the number of items in the list.
    This code is equivalent to the foreach loop:
    $people = $root->childNodes;
    
    
    
    for ($i = 0; $i < $people->length; $i++) {
    
        process($people->item($i));
    
    }


Tips for Optimizing CSS

1. Replace inline style with type selectors to target multiple instances of identical
elements.
2. Use descendant selectors to avoid inline classes.
3. Group selectors with common declarations.
4. Group declarations with common selectors.
5. Combine common styles into shared classes.
6. Use inheritance to eliminate duplicate declarations.
7. Use CSS shorthand to abbreviate rules and colors.
8. Abbreviate long class and ID names.
9. Use CSS2 and CSS3.x techniques.
10. Replace JavaScript behavior with CSS techniques.
In addition, you can eliminate extraneous whitespace by removing tabs, comments,
and returns.


Web pages that use inline style pepper HTML code with unnecessary font and style
tags. This effectively hardcodes the presentation directly within the HTML. Unless
the style is used only once, it is more efficient to create a CSS rule and target all elements
of a certain kind with type selectors (i.e., p, ul, h2, etc.). For example, this:




<h2 style="font-size:1.2em;color:red;">Little red Corvette</h2>
<h2 style="font-size:1.2em;color:red;">Baby you're much too fast to embed</h2>
<h2 style="font-size:1.2em;color:red;">Little red Corvette</h2>
<h2 style="font-size:1.2em;color:red;">You need a love that's gonna last</h2>
becomes this, by abstracting the inline style to a block style:
<style type="text/css"><!--
#main h2{font-size:1.2em;color:red;}
--></style>
The corresponding HTML cleans up to this:
<div id="main">
<h2>Little red Corvette</h2>
<h2>Baby you're much too fast</h2>
<h2>Little red Corvette</h2>
<h2>You need a love that's gonna last</h2>
</div>
 

Note how clean the code becomes after you remove the inline styles. This CSS technique
also helps search engine optimization (SEO) by boosting keyword density and
prominence.

Advanced SQL

15.1 Exploring with SHOW

The SHOW command is useful for exploring the details of databases, tables, indexes, and MySQL. It's a handy tool when you're writing new queries, modifying database structure, creating reports, or understanding how your MySQL server is performing. The SHOW command isn't part of the SQL standard and is MySQL-specific. It can be used in several ways:

SHOW DATABASES
Lists the databases that are accessible by the MySQL server. You will only see those databases that you have access to, unless you have the SHOW DATABASES privilege; privileges and user rights are discussed later in this chapter.

SHOW TABLES
Shows the tables in the database, after a database has been selected with the use command.

SHOW TABLE STATUS
Provides information about all tables in the current database, including the table type, number of rows, how the rows are stored, average row length, size of the datafile, next auto_increment value (if applicable), creation time, last modification time, and any extra options used with CREATE TABLE.

SHOW CREATE TABLE tablename
Shows the CREATE TABLE statement that was used to create the table tablename. The output always includes any additional information automatically added or changed by MySQL during the creation process, such as the table type and character set used.

SHOW OPEN TABLES
Shows which tables the server currently has open and which tables are locked.

SHOW COLUMNS FROM tablename
Shows the attributes, types of attributes, key information, whether NULL is permitted, defaults, and other information for a table tablename. The alias DESCRIBE table produces the same output.

SHOW INDEX FROM tablename
Presents the details of all indexes on the table tablename, including the PRIMARY KEY. It shows (amongst other information) what the attributes are that form each index, whether values in the index uniquely identify rows, how many different values there are in the index (the cardinality), and the index data structure used (usually a B-tree).

Using mysql_fetch_array fanc

we accessed attributes in order using the foreach loop statement. In many cases, you'll also want to access the attributes in another way, and this is usually best achieved by using the attribute names themselves. It's much easier to remember that you want to show the user the vintage year, the wine's name, the varieties, and the price, than to remember you want to show attributes four, two, six, and one from the SELECT statement. It's also a much better programming methodology because your code will be independent of the structure of the SQL statement and it'll be more readable. What's more, it's faster to access only the values you need.

$result = mysql_query("SELECT winery_name, phone, fax FROM winery");



while($row = mysql_fetch_array($result))

{

   print "The {$row["winery_name"]} winery's fax is {$row["fax"]}". 

   print "Their phone is {$row["phone"]}.\n";

}

MySQL Database Using PHP

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 <title>Wines</title>
 </head>
<body> <pre>
<?php
 // (1) Open the database connection
$connection = mysql_connect("localhost","fred","shhh");
// (2) Select the winestore database
mysql_select_db("winestore", $connection);
 // (3) Run the query on the winestore through the connection
$result = mysql_query ("SELECT * FROM wine", $connection);
// (4) While there are still rows in the result set, fetch the current
// row into the array $row
 while ($row = mysql_fetch_array($result, MYSQL_NUM))
{ // (5) Print out each element in $row, that is, print the values of
// the attributes
foreach ($row as $attribute)
print "{$attribute} ";
 // Print a carriage return to neaten the output print "\n"; }
?>
</pre>
</body>
</html>

Connect to the server with the MySQL function mysql_connect( ) .We use three parameters here: the hostname of the database server, a username, and a password. Let's assume here that MySQL is installed on the same server as the scripting engine and, therefore, localhost is the hostname. If the servers are on different machines, you can replace localhost with the domain name of the machine that hosts the database server.

The function mysql_connect( ) returns a connection resource that is used later to work with the server. Many server functions return resources that you pass to further calls. In most cases, the variable type and value of the resource isn't important: the resource is simply stored after it's created and used as required. 

Configuring the Connection Mysql

<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'mypassword');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server.';
include 'output.html.php';
exit();
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

If PHP is unable to connect to your MySQL server, or if the username and password
you provided are incorrect, you’ll instead see a similar screen to that in Figure 4.7.
To make sure your error-handling code is working properly, you might want to
misspell your password intentionally to test it out.

When an exception is caught, the value stored
in that variable is actually another PHP object; in fact, all exceptions are represented
by PHP objects! Like the PDO object we have stored in $pdo, the PDOException object
has properties we can access and methods we can call.

MySQL Data on the Web

Before we leap forward, it’s worth taking a step back for a clear picture of our ultimate
goal. We have two powerful tools at our disposal: the PHP scripting language
and the MySQL database engine. It’s important to understand how these will fit
together.

The whole idea of a database driven website is to allow the content of the site to
reside in a database, so that content may be pulled dynamically from the database
to create web pages for viewing on a regular browser. So, at one end of the system
you have a visitor to your site using a web browser to request a page. That browser
expects to receive a standard HTML document in return.

Just so it’s clear and fresh in your mind, this is what happens when there’s a visitor
to a page on your database driven website:
1. The visitor’s web browser requests the web page from your web server.
2. The web server software (typically Apache) recognizes that the requested file
is a PHP script, so the server fires up the PHP interpreter to execute the code
contained in the file.
3. Certain PHP commands (which will be the focus of this chapter) connect to the
MySQL database and request the content that belongs in the web page.
4. The MySQL database responds by sending the requested content to the PHP
script.
5. The PHP script stores the content into one or more PHP variables, then uses
echo statements to output the content as part of the web page.
6. The PHP interpreter finishes up by handing a copy of the HTML it has created
to the web server.
7. The web server sends the HTML to the web browser as it would a plain HTML
file, except that instead of coming directly from an HTML file, the page is the
output provided by the PHP interpreter. The browser has no way of knowing
this, however. From its perspective, it’s requesting and receiving a web page
like any other.

Here’s how you use PDO to establish a connection to a MySQL server:
new PDO('mysql:host=hostname;dbname=database', 'username',
'password')