Você está na página 1de 51

Basic PHP functions for using MySQL

Function Result

Opens a connection to the MySQL server.


mysql_connect() Requires a hostname, username, and
password

mysql_select_db() Selects a db on the MySQL server.

mysql_query() Issues the SQL statement.

Puts an SQL statement result row into an


mysql_fetch_array()
array
Gets single element result data from a
mysql_result()
successful query.
Returns ameaningful error message from
mysql_error()
MySQL.
Closes a previously opened connection to a
mysql_close()
MySQL server.
Connecting to a MySQL server

• Must know the name of the server and a valid username


and password.
Syntax:

$conn = mysql_connect(“hostName or IP”,


“userName”, “password”) or
die(mysql_error() );
• die:
– A built-in PHP function that prints an error message and
exits the script.
– The use here, with the mysql_error() function, will cause
an error message to be printed.
– Useful for debugging code.
Connecting to a MySQL server

• $conn:

– The mysql_connect function returns a pointer to a DB


connection.
– You will use this variable like a file pointer
– Whenever you want to refer to this DB, use the $conn
variable
Selecting a Database

• Must have already connected to mySQL


• Now must choose the DB to use
• Syntax:
$db = mysql_select_db(“DBname”, $conn) or
die(mysql_error) );
– Die: same use as before
– Must know the name of the database
– $conn is the pointer returned from the mysql_connect
function
Issuing a SQL command

• Must have already connected to mySQL and selected a


Database.
• Now can issue any SQL command that you have
permission to use.
• Two steps:
– Form the command into a string
– Use the mysql_fetch_assoc() function to fetch
data from DB.
Making a query

– First line creates an SQL query from the students


table.
– Second line sends the query to the mysql server
represented by the variable $conn
– The result is placed in the $sql_result variable
– The while statement processes the results
-mysql_fetch_array function returns the
next row of the result (stored in variable
$sql_result) as an associative array
An example for Table creation
<?php
$con = mysql_connect("localhost",”root",“redhat");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
if (mysql_query("CREATE DATABASE parthi",$con))
  {
  echo "Database created";
  }
else
  {
  echo "Error creating database: " . mysql_error();
  }
mysql_select_db(“parthi", $con);
$sql = "CREATE TABLE student
(
fname varchar(15),
lname varchar(15),
age int
)";
mysql_query($sql,$con);
mysql_close($con);
?>
An example for Data Insertion
<?php
$con = mysql_connect("localhost",“root",“redhat");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db(“parthi", $con);
mysql_query("INSERT INTO student VALUES (‘raja', ‘kumar', ‘18')");
mysql_query("INSERT INTO student (fname, lname, age)
VALUES (‘naveen', ‘sankar', ‘16')");
mysql_close($con);
?>
An example for Data Insertion using HTML

Index.html

<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname" />
Lastname: <input type="text" name="lname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
An example for Data Insertion
Insert.php

<?php

$con=mysql_connect(“localhost","root","redhat");

mysql_select_db("parthi",$con);

$sql="INSERT INTO student VALUES('$_REQUEST[fname]',

‘$_REQUEST[lname]', '$_REQUEST[age]') ";

if(!mysql_query($sql,$con))

die('error inserting table'.mysql_error());

echo "<h3>User Added Successfully"."<br>";

mysql_close($con);

?>
An example for Data selection
<?php
$con=mysql_connect(“localhost","root","redhat");

if(!$con) {

die('could not connect:'.mysql_error());

echo 'mysql connected'."<br />";

mysql_select_db("parthi",$con);

$sql=mysql_query("SELECT * FROM student ");

echo "<table border='1'>


<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($sql))
  {
  echo "<tr>";

echo "<td>" . $row[‘fname'] . "</td>";


  echo "<td>" . $row[‘lname'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>
An example for Using WHERE clause
<?php
$con = mysql_connect("localhost",“root",“redhat");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db(“parthi", $con);

$sql = mysql_query("SELECT * FROM student WHERE fname=‘raja'");


while($row = mysql_fetch_array($sql))
  {
  echo $row[‘fname'] . " " . $row[‘lname'];
  echo "<br />";
  }
?>
An example for Using ORDER BY

<?php
$con = mysql_connect("localhost",“root",“redhat");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db(“parthi", $con);
$sql = mysql_query("SELECT * FROM student ORDER BY fname");

while($row = mysql_fetch_array($sql))
  {
  echo $row[‘fname'];
  echo " " . $row[‘lname'];
  echo " " . $row[‘age'];
  echo "<br />";
  }
mysql_close($con);
?>
An example for Updating data
<?php
$con = mysql_connect("localhost",“root",“redhat");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db(“parthi", $con);
mysql_query("UPDATE student SET age = '36'
WHERE FirstName = ‘raja' AND LastName = ‘kumar'");
mysql_close($con);
?>
An example for Data deletion
<?php
$con = mysql_connect("localhost",“root",“redhat");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db(“parthi", $con);
mysql_query("DELETE FROM Persons WHERE LastName=‘kumar'");
mysql_close($con);
?>
Creating a table using mysql

mysql>use test ;

mysql>create table login(username


varchar(50),password varchar(50),fname
varchar(50),lname varchar(50),phno varchar(20));
Closing a Database connection

Closing a Database connection


– A Database connection is automatically closed when
a script ends.

– If your script is long, however, it is good to close the


connection explicitly.

– Reason: there are a limited number of connections


that a MySQL server can make (depends on admin
settings)
Closing a Database connection

Syntax:

mysql_close();
Or
mysql_close($conn);

Example:

$conn = mysql_connect(“147.129.16.1”, “testUser”,


“conn!now”) or die(mysql_error() );
mysql_close($conn);
.
Object oriented programming

• Object-oriented programming (OOP) refers to the creation of reusable


software objects that can be easily incorporated into multiple programs

• An object refers to programming code and data that can be treated as an


individual unit or component

• Objects are often also called components

• Data refers to information contained within variables or other types of


storage structures

• The functions associated with an object are called methods

• The variables that are associated with an object are called properties or
attributes

• Popular object-oriented programming languages include C++, Java, and


Visual Basic
Reasons for making the extension OO

 It is easier to follow for developers that


prefer object-oriented programming
 It is easier to design from an architectural
standpoint.
 It is easier to maintain and reuse from the
userspace.
Encapsulation
• Objects are encapsulated – all code and required data are contained
within the object itself

• Encapsulated objects hide all internal code


and data

• An interface refers to the methods and properties that are required


for a source program to communicate with an objectEncapsulated
objects allow users to see only the methods and properties of the
object that you allow them to see

• Encapsulation reduces the complexity of the code

• Encapsulation prevents other programmers from accidentally


introducing a bug into a program, or stealing code
Object oriented programming and classes
• The code, methods, attributes, and other
information that make up an object are organized
into classes
• An instance is an object that has been created from
an existing class
• Creating an object from an existing class is called
instantiating the object
• An object inherits its methods and properties from
a class — it takes on the characteristics of the class
on which it is based
Object oriented programming in PHP

• PHP, like most modern programming languages (C++, Java, Perl,


JavaScript, etc.), supports the creation of objects.
• Creating an object requires you to first define an object class
(containing variables and/or function definitions) and then using
the “new” keyword to create an instance of the object class. (Note
that the object must be defined before you instantiate it.)
• Limited support in PHP <5

• Much better support in PHP >=5

• Simpler than Java OOP


Using Objects in PHP Scripts
• Declare an object in PHP by using the new operator with a class constructor

• A class constructor is a special function with the same name as its class that
is called automatically when an object from the class is instantiated

• The syntax for instantiating an object is:

$ObjectName = new ClassName();

• The identifiers for an object name:


– Must begin with a dollar sign

– Can include numbers or an underscore

– Cannot include spaces

– Are case sensitive


Using Objects in PHP Scripts
$Checking = new BankAccount();

– Can pass arguments to many constructor


functions
$Checking = new BankAccount(01234587, 1021, 97.58);

• After an object is instantiated, use a hyphen and a greater-than symbol


(->) to access the methods and properties contained in the object
• Together, these two characters are referred to as member selection
notation
• With member selection notation append one or more characters to an
object, followed by the name of a method or property
Using Objects in PHP Scripts

• With methods, include a set of parentheses at the


end of the method name, just as with functions

• Like functions, methods can also accept arguments

$Checking->getBalance();

$CheckNumber = 1022;

$Checking->getCheckAmount($CheckNumber);
Defining (declaring) a class
Use the “class” keyword which includes the class name (case-insensitive, but
otherwise following the rules for PHP identifiers). Note: The name “stdClass”
is reserved for use by the PHP interpreter.

• The functions and variables defined in a class are called class members

• Class variables are referred to as data members or member variables

• Class functions are referred to as member functions or function members

• Classes:
– Help make complex programs easier to manage

– Hide information that users of a class do not need to access or know about

– Make it easier to reuse code or distribute your code to others for use in
their programs

• Inherited characteristics allow you to build new classes based on existing


classes without having to rewrite the code contained in the existing one
Defining (declaring) a class
<?php

class Person

var $name;

function set_name($new_name)

$name = $this -> new_name;


}

function get_name() {

return $this -> name;

}
Declaring a class (cont.)
 Use the “$this” variable when accessing properties and functions
of the current object. Inside a method this variable contains a
reference to the object on which the method was called.
 Properties and functions can be declared as “public” (accessible
outside the object’s scope), “private” (accessible only by methods
within the same class), or “protected” (accessible only through the
class methods and the class methods of classes inheriting from the
class.

 Note that unless a property is going to be explicitly declared as


public, private, or protected, it need not be declared before being
used (like regular PHP variables).
Declaring a class (cont.)
<?php

class Person

protected $name;

protected $age;

function set_name($new_name) {

$name = $this -> new_name;

function get_name() {

return $this -> name;

}
Declaring a class (cont.)

• Classes can also have their own constants defined (using the
“const” keyword), can have their own static properties and
functions (using the keyword “static” before “var” or “function”),
and can also can constructors and destructors (see below).

• Static properties and functions are accessed (see below) using a


different format than usual for objects, and static functions cannot
access the objects properties (i.e. the variable $this is not defined
inside of a static function).
• The ClassName portion of the class definition is the name of the new class
• Class names usually begin with an uppercase letter to distinguish them from
other identifiers
• Within the class’s curly braces, declare the data type and field names for
each piece of information stored in the structure
Declaring a class (cont.)
• Class names in a class definition are not followed by
parentheses, as are function
names in a function definition

$Checking = new BankAccount();


echo 'The $Checking object is instantiated from the '
. get_class($Checking) . " class.</p>";
• Use the instanceof operator to determine whether an
object is instantiated from a given class
Declaring a class (cont.)
<?php

class HTMLtable {

static function start() {

echo “<table> \n”;

static function end() {

echo “</table> \n”;

HTMLtable::start();

?>
Accessing properties and methods
Once you have an object, you access methods and properties (variables) of
the object using the -> notation.

<?php

$me = new Person;

$me -> set_name(‘Russ’);

$me -> print_name();

$name = $me -> get_name();

echo $me -> get_name();

$age = 36;

$me -> set_age($age);

?>
Using Access Specifiers
• Access specifiers control a client’s access to individual data members and
member functions

• There are three levels of access specifiers in PHP: public, private, and
protected

• The public access specifier allows anyone to call a class’s member function
or to modify a data member.

• The private access specifier prevents clients from calling member functions
or accessing data members and is one of the key elements in information
hiding

• Private access does not restrict a class’s internal access to its own members

• Private access restricts clients from accessing class members


Working with Member Functions

• Create public member functions for any functions


that clients need to access

• Create private member functions for any functions


that clients do not need to access

• Access specifiers control a client’s access to


individual data members and member functions
Working with Member Functions
class BankAccount {
public $Balance = 958.20;
public function withdrawal($Amount) {
$this->Balance -= $Amount;
}
}
if (class_exists("BankAccount"))
$Checking = new BankAccount();
Working with Member Functions
else

exit("<p>The BankAccount class is not available!</p>");

printf("<p>Your checking account balance is $%.2f.</p>",

$Checking->Balance);

$Cash = 200;

$Checking->withdrawal(200);

printf("<p>After withdrawing $%.2f, your checking account

balance is $%.2f.</p>", $Cash, $Checking->Balance);


Constructors
Constructors are methods that are (generally) used to initialize
the object’s properties with values as the object is created. Declare
a constructor function in an object by writing a function with the
name __construct().

<?php

class Person {

protected $name;

protected $age;

function __construct($new_name, $new_age) {


Constructors
$this -> name = $new_name;
$this -> age = $new_age;
}
// . . . other functions here . . .
}
$p = new Person(‘Bob Jones’, 45);
$q = new Person(‘Hamilton Lincoln’, 67);
?>
Destructors
• A default constructor function is called when a class object is first
instantiated

• A destructor function is called when the object is destroyed

• A destructor function cleans up any resources allocated to an object


after the object is destroyed
• Destructors (defined with a function name of __destructor() ) are
called when an object is destroyed, such as when the last reference
to an object is removed or the end of the script is reached (the
usefulness of destructors in PHP is limited, since, for example
dynamic memory allocation isn’t possible in the same way that it is
in C/C++).
Destructors
• A destructor function is commonly called in two ways:
– When a script ends

– When you manually delete an object with


the unset() function

• To add a destructor function to a PHP class, create a function named __destruct()

function __construct() {

$DBConnect = new mysqli("localhost", "dongosselin","rosebud", "real_estate")

function __destruct() {

$DBConnect->close();

}
Inheritance
Use the “extends” keyword in the class definition to define a new object that inherits from another.

<?php

class Employee extends Person {

var $salary;

function __construct($new_name, $new_age, $new_salary); {

$this -> salary = $new_salary;

parent::__construct($new_name, $new_age); // call the constructor

// of parent object

function update_salary($new_salary) {

$this -> salary = $new_salary;

$emp = new Employee(‘Dave Underwood’, 25, 25000);

?>
Inheritance (cont.)
• The constructor of the parent isn’t called unless the child explicitly references it (as in
this previous case). There is no automatic chain of calls to constructors in a sequence
of objects defined through inheritance.

• You could “hard-code” the call to the parent constructor using the function call
“Person::__construct($new_name, $new_age);” but it’s typically better to define it in
the manner given using the parent::method() notation. The same manner is used to call
the method of a parent that has been overridden by its child.

• You can use the “self” keyword to ensure that a method is called on the current class (if
a method might be subclassed), in this style self::method();

• To check if an object is of a particular class, you can use the instanceof operator.

if ($p instanceof Employee) {

// do something here

}
More on classes
• You can also define interfaces for objects (for which any object that uses that
interface must provide implementations of certain methods), and you can
define abstract classes or methods (that must be overridden by its children).

• The keyword “final” can be used to denote a method that cannot be


overridden by its children.

class Person {

var $name;

final function get_name() {

return $this -> name;

}
More on classes (cont.)
• There are methods for “introspection” about classes, i.e. the ability of a program to
examine an object’s characteristics.

For example,

the function class_exists() can be used (surprise!) to determine whether a class


exists or not.

The function get_declared_classes() returns an array of declared classes.

$classes = get_declared_classes();

You can also get an array of method names in any of the following (equivalent)
manners:

$methods = get_class_methods(Person);

$methods = get_class_methods(‘Person’);

$class = ‘Person’;

$methods = get_class_methods($class);
More introspection functions
There are a wide variety of introspection functions, several more are
listed below.

get_class_vars($object); /* gets an associative array that maps property


names to values (including inherited properties),
but it *only* gets properties that have default values
(those initialized with simple constants) */

is_object($object); // returns a boolean value

get_class($object); /* returns the class to which an object belongs */

method_exists($object, $method); // returns a boolean value

get_object_vars($object); /* returns an associative array mapping properties


to values (for those values that are set (i.e.not null) */
A word about object methods…
• When defining the names of your own object methods, you should generally
avoid starting them with a double underscore. Why?

• There are some “built-in” or predefined PHP method names that start in this
manner, most notably constructors and destructors using the __construct()
and __destructor() names. In the future (in new versions of PHP), it’s possible
that further methods might be defined that begin with a double underscore.

• Other reserved method names include __sleep() and __wakeup() which are
used for object serialization and __get() and __set(), which can be defined so
that if you try to access an object property that doesn’t exist, these methods
give an opportunity to either retrieve a value or set the (default?) value for that
property. For example, if a class is used to represent data obtained from a
database, you could write __get() and __set() methods that read and write data
whenever requested.

Você também pode gostar