Slides 2008
Transcript of Slides 2008
-
7/30/2019 Slides 2008
1/62
Berner Fachhochschule-Technik und Informatik
Web Programming
5) PHP and MySQL
Dr. E. Benoist
Fall Semester 2010/2011
Web Programming 5) PHP and MySQL
1
-
7/30/2019 Slides 2008
2/62
PHP and MySQL
Introduction
Basics of MySQLCreate a TableSee the content of a DBTables: Change rows and Insert data
Select Information
PhpMyAdmin
PHP and MySQL together
PDOmysql
Conclusion
Web Programming 5) PHP and MySQL
2
-
7/30/2019 Slides 2008
3/62
PHP and the Data BasesMySQL syntax
Create a new Data Base Set the rights for a DB Create tables Fill information into tables Select information (can sometime be very tricky)
Update informationPHP MyAdmin
A PHP program for managing MySQL BDs Graphical and practical
Do not require to log on the machine (only web access)PHP Library for MySQL
The old function-oriented library The new object-oriented library
Web Programming 5) PHP and MySQL
Introduction 3
-
7/30/2019 Slides 2008
4/62
MySQL a Data Base for theWeb
Open-Source DB
Free
Present in any Linux distribution
Available for fast any OS (Windows, Free-BSD, Mac-OS X,...)The perfect solution for web
LAMP architecture (Linux, Apache, MySQL, PHP) is one ofthe web standards
An application (phpMyAdmin) for managing the DB withoutshell access
Perfect integration within PHP.
Web Programming 5) PHP and MySQL
Introduction 4
-
7/30/2019 Slides 2008
5/62
Basics of MySQL commands
Creation functions (often done within PHP-MyAdmin)
Create a new table
Set the properties of fields (auto-increment, default value,...)
Routine functions (will be used in your programs)
Insert an element in a table
Select elements out of a table
Select elements out of many tables
Change the content of a record Delete some records
Web Programming 5) PHP and MySQL
Basics of MySQL 5
-
7/30/2019 Slides 2008
6/62
Creation of a tableSyntax
CREATE TABLE table name (definition of the fields)
Create a small table
CREATE TABLE category (
name VARCHAR( 100 ) NOT NULL ,categoryID TINYINT NOT NULL AUTO_INCREMENT ,
PRIMARY KEY ( categoryID )
);
Create a table with two fields
a string which length can not exceed 100
A primary key that is a counter
Web Programming 5) PHP and MySQL
Basics of MySQL: Create a Table 6
-
7/30/2019 Slides 2008
7/62
Create a new tableThe table can have fields of the following types:
TINYINT SMALLINT MEDIUMINT INT BIGINT that are integers(more or less long)
VARCHAR for short strings (smaller than 256 chars)
TEXT for texts with a fixed length (max 64 kB)
DATE date in format YYYY-MM-DD TIMESTAMP contains a unix timestamp
TIME format hh:mm:ss
DECIMAL number with a point.
FLOAT DOUBLE real numbers
BLOB Any Binary data (image, sound, long text, . . . )
. . .
Web Programming 5) PHP and MySQL
Basics of MySQL: Create a Table 7
-
7/30/2019 Slides 2008
8/62
Create a new table (Cont.)
Other attributes or features
NULL or NOT NULL
AUTO INCREMENT for counters
The table has also properties
PRIMARY KEY
COMMENT description of the table
Web Programming 5) PHP and MySQL
Basics of MySQL: Create a Table 8
-
7/30/2019 Slides 2008
9/62
Create other tablesThe article and vat tables
CREATE TABLE article (articleID INT NOT NULL AUTO_INCREMENT ,
name VARCHAR( 100 ) NOT NULL ,
vatID TINYINT NOT NULL ,
categoryID INT NOT NULL ,
Price DECIMAL NOT NULL ,PRIMARY KEY ( articleID )
);
CREATE TABLE vat (
vatID TINYINT NOT NULL AUTO_INCREMENT ,
rate DECIMAL NOT NULL ,
PRIMARY KEY ( vatID )
) COMMENT = The table containing VAT rates;
Web Programming 5) PHP and MySQL
Basics of MySQL: Create a Table 9
-
7/30/2019 Slides 2008
10/62
See the content of a data base
See all tables
mysql> show tables;
+-------------------+
| Tables_in_example |
+-------------------+| article |
| category |
| vat |
+-------------------+
3 rows in set (0.00 sec)
Web Programming 5) PHP and MySQL
Basics of MySQL: See the content of a DB 10
-
7/30/2019 Slides 2008
11/62
See the content of a data base(Cont.)
See all columns of a table
mysql> show columns from vat;
+-------+---------------+------+-----+---------+----------------| Field | Type | Null | Key | Default | Extra
+-------+---------------+------+-----+---------+----------------
| vatID | tinyint(4) | | PRI | NULL | auto_increment
| rate | decimal(10,2) | | | 0.00 |
+-------+---------------+------+-----+---------+----------------
2 rows in set (0.00 sec)
Web Programming 5) PHP and MySQL
Basics of MySQL: See the content of a DB 11
-
7/30/2019 Slides 2008
12/62
Change a Table - ALTER
Remove columns
ALTER TABLE t2 DROP COLUMN c, DROP COLUMN d;
Add a new column
ALTER TABLE article ADD description BLOB
NOT NULL ;
Change an existing column
ALTER TABLE article CHANGE Price price
DECIMAL( 10, 2 ) DEFAULT 0 NOT NULL;
Web Programming 5) PHP and MySQL
Basics of MySQL: Tables: Change rows and Insert data 12
-
7/30/2019 Slides 2008
13/62
Fill data into a table - INSERTSyntax
INSERT INTO tablename [(list of fields)] VALUES (list ofvalues);
all not null fields must be set, other can be just twocommas.
Insert a row in a table
INSERT INTO article ( articleID , name , vatID ,
categoryID , price , description )
VALUES (, Pencil, 0, 0, 1.50, );
Other possibility
INSERT INTO article values
(,Mercedes Class E,0,0,100000,
The same Mercedes Lady Diana has used
);
Web Programming 5) PHP and MySQL
Basics of MySQL: Tables: Change rows and Insert data 13
-
7/30/2019 Slides 2008
14/62
Change the content of one ormany rows
UPDATE a table
UPDATE article SET description =
A very nice black pencil with white stripes
WHERE articleID = 1 LIMIT 1 ;
Web Programming 5) PHP and MySQL
Basics of MySQL: Tables: Change rows and Insert data 14
-
7/30/2019 Slides 2008
15/62
Select informationSyntax
SELECT Field list FROM list of tables [WHERE conditions]
[LIMIT limits] Field list can also be a joker (*) Conditions can be combined with boolean connectors (AND,
OR, NOT)
If we only want to see a part of a list, we can limit it.Select all the rows and columns of a table
mysql> select * from vat;
+-------+------+
| vatID | rate |
+-------+------+
| 1 | 7.00 |
| 2 | 7.65 |
+-------+------+
Web Programming 5) PHP and MySQL
Basics of MySQL: Select Information 15
-
7/30/2019 Slides 2008
16/62
Select information(Cont.)
Select only some columns
mysql> select name, price from article;
+------------------+-----------+
| name | price |+------------------+-----------+
| Pencil | 1.70 |
| Mercedes Class E | 100000.00 |
+------------------+-----------+
2 rows in set (0.00 sec)
Web Programming 5) PHP and MySQLBasics of MySQL: Select Information 16
-
7/30/2019 Slides 2008
17/62
Select data
Select only some rows
mysql> select name, price from article
-> where articleID=1;
+--------+-------+
| name | price |
+--------+-------+
| Pencil | 1.70 |
+--------+-------+
1 row in set (0.01 sec)
Web Programming 5) PHP and MySQLBasics of MySQL: Select Information 17
-
7/30/2019 Slides 2008
18/62
Merge data from differenttables
Merge two tables Fields must know from which table they come (the same field
can be in the two tables).
We can rename a requested field with the AS keyword.
mysql> select article.name, vat.rate, article.price
-> from article, vat where article.vatID= vat.vatID;
+------------------+------+-----------+
| name | rate | price |
+------------------+------+-----------+| Pencil | 7.00 | 1.70 |
| Mercedes Class E | 7.00 | 100000.00 |
+------------------+------+-----------+
Web Programming 5) PHP and MySQLBasics of MySQL: Select Information 18
-
7/30/2019 Slides 2008
19/62
Merge ...(Cont.)
Merge and compute
mysql> select article.name, vat.rate, article.price,
-> article.price*(1+vat.rate/100) as priceWithVAT
-> from article, vat where article.vatID= vat.vatID;
+------------------+------+-----------+--------------+| name | rate | price | priceWithVAT |
+------------------+------+-----------+--------------+
| Pencil | 7.00 | 1.70 | 1.8190 |
| Mercedes Class E | 7.00 | 100000.00 | 107000.0000 |
+------------------+------+-----------+--------------+2 rows in set (0.00 sec)
Web Programming 5) PHP and MySQLBasics of MySQL: Select Information 19
-
7/30/2019 Slides 2008
20/62
Join
INNER JOIN If there is no match, the row is not shownselect article.name, vat.rate, article.price
from article inner join vaton article.vatID= vat.vatID;
LEFT JOIN If there is no match, the second table is replaced byan empty record.
select article.name from article left join vaton article.vatID= vat.vatID
where vat.rate is null;(gives the list of articles with undefined VAT)
Web Programming 5) PHP and MySQLBasics of MySQL: Select Information 20
-
7/30/2019 Slides 2008
21/62
More on SELECTResult of a select can be put into a temporary table
create temporary table valueVAT
(select vat.rate, article.name
from vat,article
where vat.vatID=article.vatID
);
You can access to the content and then delete this table
select * from valueVAT;
drop table IF EXISTS valueVAT;
Web Programming 5) PHP and MySQLBasics of MySQL: Select Information 21
S l d i
-
7/30/2019 Slides 2008
22/62
Select and more optionsOrder result (DESC or ASC)
select name, price from article order by price desc;
Group rows
mysql> select vatID, count(vatID)
> from article GROUP BY vatID;
+-------+--------------+
| vatID | count(vatID) |
+-------+--------------+
| 1 | 2 |+-------+--------------+
1 row in set (0.00 sec)
SELECT can have a lot of functions an combine all of them
Web Programming 5) PHP and MySQLBasics of MySQL: Select Information 22
D l fi ld
-
7/30/2019 Slides 2008
23/62
Delete fields
Delete the content of a table respectively to a where clause
delete from article where articleID=3;
Web Programming 5) PHP and MySQLBasics of MySQL: Select Information 23
Ad i i M SQL i h
-
7/30/2019 Slides 2008
24/62
Administrate MySQL with aWeb interface
phpMyAdmin
A PHP program for managing MySQL Data Bases
Free available at http://www.phpmyadmin.net
Included in most of the Linux distrib Internationalization
Management made easyGenerate and displays the SQL query corresponding.
Create a new Data Base Create a new Table
Add or remove a column in a table
Web Programming 5) PHP and MySQLPhpMyAdmin 24
h M Ad i
http://www.phpmyadmin.net/http://www.phpmyadmin.net/ -
7/30/2019 Slides 2008
25/62
phpMyAdmin
Management of data
Select data made easy
Update using a visual interface (does not work for BLOBs)
A lot of selection boxes containing all the possible values
Import / Export of data
Can create SQL Dump
Can export in a lot of formats: SQL, CSV, LaTeX, CSV forexcel, XML
With a lot of properties (zipped, gzipped, with delete tables ornot, . . . )
Web Programming 5) PHP and MySQLPhpMyAdmin 25
C l i
-
7/30/2019 Slides 2008
26/62
Conclusion -MySQL/phpMyAdmin
Not as much powerful as other DBs
MySQL does not implement all of SQL
It is enough to handle a small web site
Very useful and easy to install, configure and managePHP supports all other DBs
Oracle
ODBC (MS-SQL server, Access)
Postgess
DBase
. . .
Web Programming 5) PHP and MySQLPhpMyAdmin 26
PHP d M SQL
-
7/30/2019 Slides 2008
27/62
PHP and MySQL
Four Libraries
mysql old library
mysqli new library
pear MDB2 multi-database library and abstraction layer(merge of PEAR DB and Metabase abstraction layer)
PDO Object Oriented generic library
Web Programming 5) PHP and MySQLPHP and MySQL together 27
PHP d M SQL (C t )
-
7/30/2019 Slides 2008
28/62
PHP and MySQL (Cont.)
mysql
Used from the beginning of the language
Compatible with a lot of existing code
mysqli
New since php5 Contains objects and encapsulation
PDO
Compatible with almost any Data Base
Syntax is the same and is platform independent
Not as optimized as the two dedicated routines
Web Programming 5) PHP and MySQLPHP and MySQL together 28
PHP Data Objects PDO
-
7/30/2019 Slides 2008
29/62
PHP Data Objects - PDO
PDO is a generic connector for any database
Code is (almost) platform independant Support is provided for all major Data Bases servers (MySQL,
Oracle, MS SQL Server, Sybase, Informiy, ODBC, PostgreSQL,SQLITE)
PDO is an oject oriented interface
Creates a connection object Creates Statements and Results that are objects
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 29
Create a connection
-
7/30/2019 Slides 2008
30/62
Create a connection The first step is to create a connection to the DB server
Needs an URL for connecting:
protocol:host=;dbname= Arguments are username and password
Close the connection by setting the handler to null
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 30
Execute a SQL query
-
7/30/2019 Slides 2008
31/62
Execute a SQL query Execute a SQL Query : $dbh->exec($sql);
Value returned = number of affected rows
Should be used if no result set is returned (INSERT / UPDATE)
try {$dbh = new PDO(mysql:host=$hostname;dbname=animals,
$username, $password);
/ INSERT data /$sql = INSERT INTO article (name, price) VALUES (Journal, 1.9);$count = $dbh>exec($sql);/ echo the number of affected rows/echo $count;/ close the database connection /
$dbh = null;}catch(PDOException $e){
echo $e>getMessage();}
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 31
Update records
-
7/30/2019 Slides 2008
32/62
Update records
PDO::exec() is used each time no selection is needed
/ INSERT data /
$query=UPDATE animals SET animal name=bruce;$query .= WHERE animal name=troy;$count = $dbh>exec($query);/ echo the number of affected rows /echo $count;
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 32
Select queries
-
7/30/2019 Slides 2008
33/62
Select queries
SELECT returns a result set Method is PDO::query()
Returned statement can be visited like an array(implements the SPL traversible iterator)
/ The SQL SELECT statement /$sql = SELECT FROM animals;foreach ($dbh>query($sql) as $row)
{print $row[animal type] . .
$row[animal name] .
;}Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 33
Fetch the result set
-
7/30/2019 Slides 2008
34/62
Fetch the result set There are multiple ways to visit a result set
The SPL traversible iterator (i.e. a foreach on the resultset
itself) Fetch the result in arrays or objects Fetch :
$result = $stmt->fetch(PDO::FETCH ASSOC); : Createsan associative array $result containing one record.
If fetch is repeated, moves one record ahead Visit with a while (fetch returns false at the end of the
selection)
$sql = SELECT FROM article;/ fetch into an PDOStatement object /
$stmt = $dbh>query($sql);while ($result = $stmt>fetch(PDO::FETCH ASSOC)){
echo Name = .$result[name]., price=.$result[price].
\n;}Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 34
Different types of Fetch
-
7/30/2019 Slides 2008
35/62
Different types of Fetch Into an associative array:
$result = $stmt>fetch(PDO::FETCH ASSOC);...echo $result[name];
Into a numeric array
$result = $stmt>fetch(PDO::FETCH NUM)..echo $result[1]
Into both associative and numeric array
$result = $stmt>fetch(PDO::FETCH BOTH)..echo $result[1]., .$result[name];
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 35
Fetch into Objects
-
7/30/2019 Slides 2008
36/62
Fetch into Objects
Fetch can create a ad-hoc object, having the columnsnames as properties
$obj = $stmt>fetch(PDO::FETCH OBJ);
/ Visit the object directly /echo $obj>name.
\n;echo $obj>price;Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 36
Fetch Lazy
-
7/30/2019 Slides 2008
37/62
Fetch Lazy
PDO::FETCH LAZY is odd as it combines PDO::FETCH BOTHand PDO::FETCH OBJ.
$obj = $stmt>fetch(PDO::FETCH LAZY);
/ Visit the object directly /echo $obj>name.
\n;echo $obj[1].
\n;echo $obj[price];Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 37
Fetch a record into an object of
-
7/30/2019 Slides 2008
38/62
Fetch a record into an object ofa given class
PDO::FETCH CLASS instantiates a new instance of thespecified class.
The field names are mapped to properties (variables) withinthe class called.
This saves quite a bit of code and speed is enhanced as themappings are dealt with internally.
method fetchALL() creates an array containing all the
records.
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 38
Fetch a record into an object of
-
7/30/2019 Slides 2008
39/62
Fetch a record into an object ofa given class (Cont.)
class article{public $articleID;public $name;public $vatID;public $categoryID;public $price;public $description;public function displayElementLine(){
echo $this>name.,.$this>price.
\n;}}
...$stmt = $dbh>query($sql);$obj = $stmt>fetchALL(PDO::FETCH CLASS, article);foreach($obj as $article){
$article>displayElementLine();}
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 39
Fetching into an new Object
-
7/30/2019 Slides 2008
40/62
Fetching into an new Object
We define the fetch mode of a statement
$sql = SELECT FROM article;
/ fetch into an PDOStatement object /$stmt = $dbh>query($sql);
/ set the fetch mode with PDO::setFetchMode() /$stmt>setFetchMode(PDO::FETCH INTO, new article);
/ loop over the PDOStatement directly /foreach($stmt as $article){
$article>displayElementLine();}
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 40
Error Handling
-
7/30/2019 Slides 2008
41/62
Error Handling
Default: Errors are Dye statements
Program is interrupted Error is displayed on Screen
We should throw exceptions Change the error mode such that it sends exceptions, Then catch all axceptions It prevents an attacker to access to internal information.
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 41
Error Handling (Cont.)
-
7/30/2019 Slides 2008
42/62
Error Handling (Cont.)
try {
$dbh = new PDO(mysql:host=$hostname;dbname=animals,$username, $password);
/ echo a message saying we have connected /echo Connected to database
;/ set the error reporting attribute /$dbh>setAttribute(PDO::ATTR ERRMODE,PDO::ERRMODE EXCEPTION);
...$dbh = null;
}catch(PDOException $e){
echo $e>getMessage();}
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 42
Prepared Statement
-
7/30/2019 Slides 2008
43/62
p St t t A precompiled SQL statement
Accepts 0 or more parameters Usefull for using a query multiple times Usefull for preventing SQL Injection
$sql = SELECT FROM article.WHERE articleID = :article id OR name = :name;
$stmt = $dbh>prepare($sql);$stmt>bindParam(:article id, $article id, PDO::PARAM INT);$stmt>bindParam(:name, $name, PDO::PARAM STR, 5);$stmt>execute();$result = $stmt>fetchAll();
foreach($result as $row){echo $row[articleID]., ;echo $row[name]., ;echo $row[price].
\n;}
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 43
Using a prepared statement
-
7/30/2019 Slides 2008
44/62
g p p$article id = 6; $name = 20 Minuten;$sql = SELECT FROM article WHERE articleID=:article id OR name=:name;
$stmt = $dbh>prepare($sql);$stmt>bindParam(:article id, $article id, PDO::PARAM INT);$stmt>bindParam(:name, $name, PDO::PARAM STR, 5);$stmt>execute();$result = $stmt>fetchAll();foreach($result as $row){ echo $row[name].
\n; }$article id = 5;$name = 24 Heures;$stmt>execute();$result = $stmt>fetchAll();foreach($result as $row){ echo $row[name].
\n; }$article id = 1;$name = Nesquik;$stmt>execute();$result = $stmt>fetchAll();foreach($result as $row){ echo $row[name]., ; }Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 44
Transaction
-
7/30/2019 Slides 2008
45/62
Transactions are used to group requests that mustremain together
For efficiency reason (do not lock the file too many times) For consistency of database (Group some queries that should
remain together)
Examples
Insertion of many records Credit and Debit operations (Bookkeeping) Delivering and stock management . . .
Syntax
At the begining of the transaction$dbh->beginTransaction(); At the end of the transaction $dbh->commit(); In order to cancel a transaction (before commit)
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 45
Transaction (Example)
-
7/30/2019 Slides 2008
46/62
( p )try{...
$dbh>beginTransaction();$table = CREATE TABLE animals (
animal id MEDIUMINT(8) NOT NULL AUTO INCREMENT PRIMARY KEY,animal type VARCHAR(25) NOT NULL,animal name VARCHAR(25) NOT NULL
);
$dbh>exec($table);$dbh>exec(INSERT INTO animals (animal type, animal name) VALUES (em...$dbh>exec(INSERT INTO animals (animal type, animal name) VALUES (liza$dbh>commit();echo Data entered successfully
;}catch(PDOException $e){
$dbh>rollback();echo $sql .
. $e>getMessage();}
Web Programming 5) PHP and MySQLPHP and MySQL together: PDO 46
Get the index of the last
-
7/30/2019 Slides 2008
47/62
inserted element When inserting an element, index may be
autoinctemented
Programmer needs a way to access the index Can update other tables Can create cross reference with new records
/ INSERT a new row /$sql = INSERT INTO article (name, price) VALUES (Laptop, 500);$dbh>exec($sql);
/ display the id of the last INSERT /echo The last inserted element has ID: ;echo $dbh>lastInsertId().
\n;Web Programming 5) PHP and MySQL
PHP and MySQL together: PDO 47
Use the Singleton pattern for
-
7/30/2019 Slides 2008
48/62
g pthe connection object
Connection to the DB should be unique
Connection requires a lot of time Number of connections to the DB may be limited
A design Pattern exists for creating only one instance of
a class The singleton design pattern
Ideas:
Make the constructor private Make the clone private
Create an instance as class parameter Create a static method getInstance() that creates the
instance if it did not exist or returns the existing one.
Web Programming 5) PHP and MySQL
PHP and MySQL together: PDO 48
The Singleon
-
7/30/2019 Slides 2008
49/62
class db{private static $instance = NULL;private function construct() {
/ maybe set the db name here later /}public static function getInstance() {
if (!self::$instance){
self::$instance = new PDO(mysql:host=localhost;dbname=example, root, );;
self::$instance> setAttribute(PDO::ATTR ERRMODE,PDO::ERRMODE EXCEPTION);
}
return self::$instance;}private function clone(){ }
} / end of class /
Web Programming 5) PHP and MySQL
PHP and MySQL together: PDO 49
Usage
-
7/30/2019 Slides 2008
50/62
try {
/ query the database /$result = DB::getInstance()>query(SELECT FROM article);
/ loop over the results /foreach($result as $row)
{print $row[name] . . $row[price] .
;}}catch(PDOException $e)
{echo $e>getMessage();
}
Web Programming 5) PHP and MySQL
PHP and MySQL together: PDO 50
mysql :(The old library)
-
7/30/2019 Slides 2008
51/62
Web Programming 5) PHP and MySQL
PHP and MySQL together: mysql 51
Connection to a DB
-
7/30/2019 Slides 2008
52/62
Establish the connection
$db = @mysql connect(localhost,root,toto14);Handle
Returned by the connection
One can play with more than one connection (multi-server)
Is a number
Error handling
echo mysql error();
Disconnect from the DB
mysql close();
Web Programming 5) PHP and MySQL
PHP and MySQL together: mysql 52
Execute Queries
-
7/30/2019 Slides 2008
53/62
execute a SQL query: mysql query(sql,conn)SQL queries are stored in an array and executed
require(connDB.php);
$querys= array();
$querys[]=insert into article values(0,Milk,1,1,.10.90,Super milk for the kids);;
$querys[]=insert into article values(0,Cafe,1,.1,10.90,Super cafe for the adults);;
foreach($querys as $query){mysql query($query , $conn);
}mysql close($conn);
Web Programming 5) PHP and MySQL
PHP and MySQL together: mysql 53
Fetch result of a select
-
7/30/2019 Slides 2008
54/62
require once(connDB.php);
$query = select from article;
$result = mysql query($query , $conn);
if($result){$nbRows = mysql num rows($result);echo $nbRows have been selected by query:
$query
\n;// arrayType can be : MYSQL ASSOC, MYSQL NUM, MYSQL BOTHwhile( $row = mysql fetch array($result, MYSQL ASSOC)){
echo implode(,,$row).
\n;}}else{echo mysql error();
}mysql close($conn);
Web Programming 5) PHP and MySQL
PHP and MySQL together: mysql 54
Fetch result of a select (Cont.)
-
7/30/2019 Slides 2008
55/62
Types of arrays
MYSQL ASSOC keys are field names
MYSQL NUM keys are numbers
MYSQL BOTH keys are both numbers and field namesfetch a single row until no more is accessible
while( $row = mysql fetch array($result, MYSQL ASSOC))
Web Programming 5) PHP and MySQL
PHP and MySQL together: mysql 55
Fetch a row into an object
-
7/30/2019 Slides 2008
56/62
Creates an object whose member variables are fields
if($result){$nbRows = mysql num rows($result);echo $nbRows have been selected by query:
$query
\n;while( $obj = mysql fetch object($result)){echo {$obj>name}, => CHF {$obj>price}
\n;}}
Web Programming 5) PHP and MySQL
PHP and MySQL together: mysql 56
Insert data into a table
-
7/30/2019 Slides 2008
57/62
$query = insert into article values(0,Milk UHT, .1,1,7.90,Super milk for kids);
$result= mysql query($query , $conn);
if(!$result){echo mysql error;
}$newID = mysql insert id();
$query2 = update article set price=5.5. where articleID=$newID;
$result2= mysql query($query2 , $conn);
if(!$result2){die(Could not execute $query2 .mysql error());}$affectedRows = mysql affected rows($conn);echo number of affected rows:$affectedRows
\n;Web Programming 5) PHP and MySQL
PHP and MySQL together: mysql 57
Insert and Update
-
7/30/2019 Slides 2008
58/62
Insert
Create a new record in the table
ID automatically generated (with auto increment)
We need to access this counter:
$newID = mysql insert id();
Update
Useful to change the tables
Programmer want to know if it worked
Indication: the number of affected rows: mysql affected rows($conn)
Web Programming 5) PHP and MySQL
PHP and MySQL together: mysql 58
Manipulate the Data Base itself
-
7/30/2019 Slides 2008
59/62
require once(connDB.php);$res = mysql list dbs($conn);
for($i=0;$i < mysql num rows($res);$i++){$dataBase= mysql tablename($res,$i);$result=0;$query = show tables from $dataBase;$result = mysql query($query , $conn);if($result){
$nbTables = mysql num rows($result);echo $dataBasehas $nbTables tables
\n;while( $row = mysql fetch array($result,MYSQL ASSOC)){
echo implode(,,$row).
\n;}}
}mysql close($conn);
Web Programming 5) PHP and MySQL
PHP and MySQL together: mysql 59
Conclusion I
-
7/30/2019 Slides 2008
60/62
mysql Library Uses no objects,
Based and handles that can be passed as parameters tofunctions
PDO Generic Access to any database
Most of the code is plattform independant
Must sometime be adapted
Web Programming 5) PHP and MySQL
Conclusion 60
Conclusion II
-
7/30/2019 Slides 2008
61/62
DB are the center of our work
Do not require a programmer to write HTML
they are used to access DBs
forms and dbs are the two pillars of web programming
a lot of other finesses to be discovered SQL : a semester course of 2 hours a week
PHP supports all data bases
A standard web architecture is LAMP: Linux Apache MySQL
PHP
Web Programming 5) PHP and MySQL
Conclusion 61
Resources
-
7/30/2019 Slides 2008
62/62
Pear Documentationhttp://pear.php.net
Web Programming 5) PHP and MySQL
Conclusion 62
http://pear.php.net/http://pear.php.net/