Learn PHP Lacture2

31
Accessing MySQL with PHP

description

 

Transcript of Learn PHP Lacture2

Page 1: Learn PHP Lacture2

Accessing MySQL with PHP

Page 2: Learn PHP Lacture2

Overview of My SQL Structure and Syntax

Databases are stores of information. MySQL is an open-source database that can be used for

web applications. The only requirement is that, you need to have a server

at your disposal where you can install MySQL. Types of Storage Engines

◦ MyISAM (Indexed Sequential Access Method)◦ MERGE◦ MEMORY◦ InnoDB◦ BDB (BerkeleyDB )

Page 3: Learn PHP Lacture2

My SQL Syntax and CommandsCommon commands

◦ CREATE : Creates new databases and tables◦ ALTER : Modifies existing tables◦ SELECT : Chooses the data you want◦ DELETE : Erases the data from your table◦ DESCRIBE : Lets you know the structure and

specifics of the table◦ INSERT INTO table name VALUES : Puts

values into the table◦ UPDATE : Lets you modify data already in a

table◦ DROP : Deletes an entire table or database

Page 4: Learn PHP Lacture2

Data Type in MySQL Text Types

◦ char(size) It is used to store no. of character and it is in fixed length.

◦ varchar(size) It is used to store alphanumeric data of variable length.

◦ blob It is binary large object which can hold variable amount of business

data

◦ Binary and Varbinary These 2 type are similar to char and varchar except that they hold

binary string rather than ascii string

Number Types◦ int(size)

It is used to store integer type of data. It divide in to 5 segment int, tiny int, small int, medium int,big int

◦ Float(size,precision) It is allow to store decimal numbers with specific precision.

◦ Double(size,precision) It is allow to store large floating decmial point value.

Page 5: Learn PHP Lacture2

Date◦ Hold the date value◦ Range between 1000-01-01 to 9999-12-31

Time◦ Hold the time value◦ Standard format hh:mm:ss

Datetime◦ It hold date and time value◦ Range between 1000-01-01 00:00:00 to 9999-12-31

23:59:59◦ Standard format yyyy-mm-dd hh:mm:ss

year◦ It is required 1 byte for holds year value

Page 6: Learn PHP Lacture2

How PHP Fits with My SQL You can use MySQL commands within PHP code. Some of the more commonly used functions are:

◦ mysql_connect($host, $username, $password) : Connects to the MySQL server and returns a resource which is used to reference the connection.

◦ Mysql_pconnect():-◦ mysql_select_db($database, $resource) : Equivalent to the

MySQL command USE and sets the active database.◦ mysql_query($query, $resource) : Used to send any MySQL

command to the database server. In the case of SELECT queries, a reference to the result set will be returned.

◦ mysql_fetch_array($result) : Return a row of data from the query ’ s result set as an associative array, numeric array or both.

◦ mysql_fetch_assoc($result) : Return a row of data from the query ’ s result set as an associative array.

◦ mysql_error([$resource]) : Shows the error message generated by the previous query.

◦ die(<String> $msg) die() prints message and exits the current script.

Page 7: Learn PHP Lacture2

Cont…To connect with database

◦ $con = mysql_connect ($host, $username, $password)$host = ‘localhost’;$user = ‘root’;$pass = ‘’;$con = mysql_connect($host, $user, $pass);

The following statement has the same effect:$con = mysql_connect(‘localhost’, ‘root’, ‘’);

To close the connection◦ mysql_close($con);

To select database$db = mysql_select_db(DBName,$con)

Page 8: Learn PHP Lacture2

Create TableSyntax:-

◦ CREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name3 data_type,....)

Example:-◦ CREATE TABLE Persons

(FirstName varchar(15),LastName varchar(15),Age int)

Important: A database must be selected before a table can be created. The database is selected with the mysql_select_db() function.

Page 9: Learn PHP Lacture2

Insert data into tables The INSERT INTO statement is used to add new records to a database table. It is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be

inserted, only their values:

INSERT INTO table_name VALUES (value1, value2, value3,...) The second form specifies both the column names and the values to be

inserted:

INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

Example:-

// insert data into table

$insert=mysql_query("INSERT INTO Persons VALUES (1, 'Glenn', 'Quagmire',33 )");

// Execute querymysql_query($insert,$con);

// insert data into table

$insert=mysql_query("INSERT INTO Persons (personID,FirstName, LastName, Age) VALUES (2,'Peter', 'Griffin',35)");

// Execute querymysql_query($insert,$con);

Page 10: Learn PHP Lacture2

Insert data into table using FORM<html>

<body><form action="insert.php"

method="post">Firstname: <input type="text"

name="firstname">Lastname: <input type="text"

name="lastname">Age: <input type="text"

name="age"><input type="submit">

</form></body></html>

When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php".

Page 11: Learn PHP Lacture2

Here is the "insert.php" page: <?php $con = mysql_connect('localhost', 'root', '') or die ('Unable to connect. Check your connection

parameters.'); echo "Connection successfully\n"; // select database mysql_select_db('student', $con) or die(mysql_error($con)); echo "Database active\n";//insert data

$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))  {  die('Error: ' . mysql_error());  }echo "1 record added";

mysql_close($con);?>

Page 12: Learn PHP Lacture2

Retrieve the Data From a Database Table $result = mysql_query("select * from Persons ") To retrive the data from the table we are using the

mysql_fetch_array() function. When we pass $result into

the mysql_fetch_array function -- mysql_fetch_array($result) -- an associative array (firstname, lastname, age) is returned.

mysql_fetch_array() function to return the first row from the recordset as an array.

In our MySQL table " Persons," there are only three fields that we care about: firstname, lastname and age.

These names are the keys to extracting the data from our associative array.

To get the firstname we use $row[‘firstname'] , to get the lastname we use $row[‘lastnamr'] and to get the age we use $row['age'].

Page 13: Learn PHP Lacture2

fetch array while loopEach call to mysql_fetch_array() returns the

next row in the recordset.

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

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

The while loop loops through all the records in the recordset.

To print the value of each row, we use the PHP $row variable ($row['FirstName'] ,$row['LastName'],$row[‘age’]).

Page 14: Learn PHP Lacture2

Retrieving data To retrieving the data from database 2 function are used.

◦ mysql_fetch_array()

◦ mysql_fetch_assoc()

The mysql_fetch_assoc() function returns a single row from the table as an associative array. The data can be retrieved by using the column names as indexes.

The mysql_fetch_array() function returns a single row from the table. The data can be retrieved by column names and column indexes.

@ is used to generate user defined exception other than System generated errors.

mysql_num_fields( $result ) is used to count total number of fields and coloumn from your database.

$num_cols = mysql_num_fields( $result ); mysql_num_rows( $result ) is used to count total number of

recods from your database.

$num_rows = mysql_num_rows( $result );

Page 15: Learn PHP Lacture2

Include() AND include_once()Include() AND require():-

◦ The include and require statements are used to insert useful codes written in other files, in the flow of execution.

◦ Include and require are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script include will only produce a warning (E_WARNING) and the script will

continue So, if you want the execution to go on and show users the output, even if

the include file is missing, use include(). Otherwise, require().

◦ Syntax:- Include(“file name with path”); or include “file name with path”; Require(“file name with path”); or require “file name with path”;

◦ Example:- <html>

<body>

<?php include 'header.php'; ?><h1>Welcome to my home page!</h1><p>Some text.</p>

</body></html>

Page 16: Learn PHP Lacture2

Include_once() AND require_once() Include_once() & require_once() both are functioning

same as include() and require. But the main difference between those function is

include_once() and require_once() include file only once while include() and require() include files as many time as you want.◦ Syntax:-

Include_once(“file name with path”); or include_once “file name with path”;

Require_once(“file name with path”); or require_once “file name with path”;

◦ Example:- <html>

<body>

<?php include_once 'header.php'; ?><h1>Welcome to my home page!</h1><p>Some text.</p>

</body></html>

Page 17: Learn PHP Lacture2

Maintaining State in PHP using Cookies & SessionsWhy to maintain state in php?

◦HTTP is stateless Protocol.◦Any data you have stored is forgotten

about when the page has been sent to the client and the connection is closed.

◦Cookie is tiny bits of information that a web site could store on the client's machine that were sent back to the web site each time a new page was requested. Each cookie could only be read by the web site that had written it.

Page 18: Learn PHP Lacture2

What is a Cookie?A cookie is a small text file that is

stored on a user’s computer.Each cookie on the user’s

computer is connected to a particular domain.

Each cookie be used to store up to 4kB of data.

A maximum of 20 cookies can be stored on a user’s PC per domain.

Page 19: Learn PHP Lacture2

1. User sends a request for page at www.example.com for the first time.

Example

page request

Page 20: Learn PHP Lacture2

2. Server sends back the page xhtml to the browser AND stores some data in a cookie on the user’s PC.

Example

cookie data

xhtml

Page 21: Learn PHP Lacture2

3. At the next page request for domain www.example.com, all cookie data associated with this domain is sent too.

Example

page request

cookie data

Page 22: Learn PHP Lacture2

setcookie(name [,value [,expire [,path [,domain [,secure]]]]])

name = cookie namevalue = data to store (string)expire = UNIX timestamp when the cookie expires.

Default is that cookie expires when browser is closed.path = Path on the server within and below which the

cookie is available on.domain = Domain at which the cookie is available for.secure = If cookie should be sent over HTTPS

connection only. Default false.

Set a cookie

Page 23: Learn PHP Lacture2

setcookie(‘name’,’Robert’)This command will set the cookie called

name on the user’s PC containing the data Robert. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted when the browser is closed (default expire).

setcookie(‘age’,’20’,time()+60*60*24*30)This command will set the cookie called age

on the user’s PC containing the data 20. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted after 30 days.

Set a cookie - examples

Page 24: Learn PHP Lacture2

As the setcookie command involves sending a HTTP header request, it must be executed before any xhtml is echoed to the browser, including whitespace.

Where to write code for Cookie…

correct!incorrect.

echoed whitespace beforesetcookie

Page 25: Learn PHP Lacture2

All cookie data is available through the superglobal $_COOKIE:$variable = $_COOKIE[‘cookie_name’]

or$variable = $HTTP_COOKIE_VARS[‘cookie_name’];

e.g.$age = $_COOKIE[‘age’]

Read cookie data

Page 26: Learn PHP Lacture2

To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past…

setcookie(‘cookie_name’,’’,time()-6000)

Delete a cookie

Page 27: Learn PHP Lacture2

You can store user information (e.g. username, items selected, etc.) in the server side for later use using PHP session.Sessions work by creating a unique id (UID) for each visitor and storing variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

PHP Sessions

<?php session_start(); ?><html><body></body></html>

session_start() function must appear BEFORE the <html> tag.

Before you can store user information in your PHP session, you must first start up the session.

Page 28: Learn PHP Lacture2

PHP Sessions Starting a PHP session:

<?php session_start(); ?>

• This tells PHP that a session is requested. • A session ID is then allocated at the server end.• session ID looks like:

sess_f1234781237468123768asjkhfa7891234g

Page 29: Learn PHP Lacture2

$_SESSION e.g., $_SESSION[“intVar”] = 10;

Testing if a session variable has been set:

session_start();

if(!$_SESSION['intVar']) {...} //intVar is set or not

Session variables

Page 30: Learn PHP Lacture2

Session Example 1 <?php

session_start(); if (!isset($_SESSION["intVar"]) ){ $_SESSION["intVar"] = 1; } else { $_SESSION["intVar"]++; } echo "<p>In this session you have accessed

this page " . $_SESSION["intVar"] . "times.</p>";

?>

Page 31: Learn PHP Lacture2

Ending sessionsunset($_SESSION[‘name’])

– Remove a session variable

session_destroy()– Destroys all data registered to a session– does not unset session global variables and

cookies associated with the session– Not normally done - leave to timeout