Berner Fachhochschule - HTI
PHP and MySQL
- Dr. E. Benoist
Winter Term 2006-2007
PHP and MySQL 1
PHP and MySQL Dr. E. Benoist Winter Term 2006-2007 PHP and MySQL - - PowerPoint PPT Presentation
Berner Fachhochschule - HTI PHP and MySQL Dr. E. Benoist Winter Term 2006-2007 PHP and MySQL 1 PHP and MySQL Introduction Basics of MySQL Create a Table See the content of a DB Tables: Change rows and Insert data Select
PHP and MySQL 1
PHP and MySQL 2
◮ 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 information
◮ A PHP program for managing MySQL BD’s ◮ Graphical and practical ◮ Do not require to log on the machine (only web access)
◮ The old function-oriented library ◮ The new object-oriented library
PHP and MySQL Introduction 3
◮ Free ◮ Present in any Linux distribution ◮ Available for fast any OS (Windows, Free-BSD, Mac-OS X,...)
◮ LAMP architecture (Linux, Apache, MySQL, PHP) is one of
◮ An application (phpMyAdmin) for managing the DB without
◮ Perfect integration within PHP.
PHP and MySQL Introduction 4
◮ Create a new table ◮ Set the properties of fields (auto-increment, default value,...)
◮ 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
PHP and MySQL Basics of MySQL 5
◮ CREATE TABLE table name (definition of the fields)
◮ Create a table with two fields ◮ a string which length can not exceed 100 ◮ A primary key that is a counter
PHP and MySQL Basics of MySQL: Create a Table 6
◮ TINYINT SMALLINT MEDIUMINT INT BIGINT that are integers
◮ 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, . . . ) ◮ . . .
PHP and MySQL Basics of MySQL: Create a Table 7
◮ NULL or NOT NULL ◮ AUTO INCREMENT for counters
◮ PRIMARY KEY ◮ COMMENT description of the table
PHP and MySQL Basics of MySQL: Create a Table 8
PHP and MySQL Basics of MySQL: Create a Table 9
PHP and MySQL Basics of MySQL: See the content of a DB 10
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)
PHP and MySQL Basics of MySQL: See the content of a DB 11
PHP and MySQL Basics of MySQL: Tables: Change rows and Insert data 12
◮ INSERT INTO tablename [(list of fields)] VALUES (list of
◮ all not null fields must be set, other can be just two
PHP and MySQL Basics of MySQL: Tables: Change rows and Insert data 13
PHP and MySQL Basics of MySQL: Tables: Change rows and Insert data 14
◮ SELECT Field list FROM list of tables [WHERE conditions]
◮ Field list can also be a joker (*) ◮ Conditions can be combined with boolean connectors (AND,
◮ If we only want to see a part of a list, we can limit it.
PHP and MySQL Basics of MySQL: Select Information 15
PHP and MySQL Basics of MySQL: Select Information 16
PHP and MySQL Basics of MySQL: Select Information 17
◮ Fields must know from which table they come (the same field
◮ We can rename a requested field with the AS keyword.
PHP and MySQL Basics of MySQL: Select Information 18
PHP and MySQL Basics of MySQL: Select Information 19
PHP and MySQL Basics of MySQL: Select Information 20
PHP and MySQL Basics of MySQL: Select Information 21
PHP and MySQL Basics of MySQL: Select Information 22
PHP and MySQL Basics of MySQL: Select Information 23
◮ A PHP program for managing MySQL Data Bases ◮ Free available at http://www.phpmyadmin.net ◮ Included in most of the Linux distrib ◮ Internationalization
◮ Create a new Data Base ◮ Create a new Table ◮ Add or remove a column in a table
PHP and MySQL PhpMyAdmin 24
◮ Select data made easy ◮ Update using a visual interface (does not work for BLOBs) ◮ A lot of selection boxes containing all the possible values
◮ Can create SQL Dump ◮ Can export in a lot of formats: SQL, CSV, LaTeX, CSV for
◮ With a lot of properties (zipped, gzipped, with delete tables or
PHP and MySQL PhpMyAdmin 25
◮ MySQL does not implement all of SQL ◮ It is enough to handle a small web site ◮ Very useful and easy to install, configure and manage
◮ Oracle ◮ ODBC (MS-SQL server, Access) ◮ Postgess ◮ DBase ◮ . . .
PHP and MySQL PhpMyAdmin 26
◮ mysql old library ◮ mysqli new library ◮ pearDB multi-database library
◮ Used from the beginning of the language ◮ Compatible with a lot of existing code
◮ New since php5 ◮ Contains objects and encapsulation
◮ Compatible with almost any Data Base ◮ Syntax is the same and is platform independent ◮ Not as optimized as the two dedicated routines
PHP and MySQL PHP and MySQL together 27
PHP and MySQL PHP and MySQL together: mysql 28
◮ Returned by the connection ◮ One can play with more than one connection (multi-server) ◮ Is a number
PHP and MySQL PHP and MySQL together: mysql 29
<?php $host=’localhost’; $user=’root’; $pwd=’toto14’; $dbase=’example’; $conn = @mysql connect($server,$user,$pwd); /∗ // A persistant connection should be established if the server // should open a lot of connexions (which costs lot of time). $conn = @mysql pconnect($server,$user,$pass); ∗/ if($conn){ mysql select db($dbase, $conn); } else{ die(”The connection could not be established”); } ?>
PHP and MySQL PHP and MySQL together: mysql 30
◮ Establish TCP/IP connexion ◮ Exchange username password
◮ The connection is not broken by mysql close() ◮ It is reused if the parameters are the same
PHP and MySQL PHP and MySQL together: mysql 31
PHP and MySQL PHP and MySQL together: mysql 32
PHP and MySQL PHP and MySQL together: mysql 33
◮ Handler $result is 0 when an error occurs ◮ Call function mysql error() to access to the error;
PHP and MySQL PHP and MySQL together: mysql 34
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:<br>$query <br>\n”; // arrayType can be : MYSQL ASSOC, MYSQL NUM, MYSQL BOTH while( $row = mysql fetch array($result, MYSQL ASSOC)){ echo implode(”,”,$row).”<br>\n”; } } else{ echo mysql error(); } mysql close($conn);
PHP and MySQL PHP and MySQL together: mysql 35
◮ MYSQL ASSOC keys are field names ◮ MYSQL NUM keys are numbers ◮ MYSQL BOTH keys are both numbers and field names
PHP and MySQL PHP and MySQL together: mysql 36
PHP and MySQL PHP and MySQL together: mysql 37
$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<br>\n”;
PHP and MySQL PHP and MySQL together: mysql 38
◮ Create a new record in the table ◮ ID automatically generated (with auto increment) ◮ We need to access this counter: ◮ $newID = mysql insert id();
◮ Useful to change the tables ◮ Programmer want to know if it worked ◮ Indication: the number of affected rows: ◮ mysql affected rows($conn)
PHP and MySQL PHP and MySQL together: mysql 39
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 ”<b>$dataBase</b>has $nbTables tables <br>\n”; while( $row = mysql fetch array($result, MYSQL ASSOC)){ echo implode(”,”,$row).”<br>\n”; } } } mysql close($conn);
PHP and MySQL PHP and MySQL together: mysql 40
PHP and MySQL PHP and MySQL together: mysql 41
Available since version MySQL 4.1
◮ Object oriented syntax; ◮ more efficient to access the DB; ◮ functionalities are the same
Example $host=’localhost’; $user=’root’; $pwd=’toto14’; $dbase=’example’; $mi = new mysqli($host,$user,$pwd,$dbase); if(mysqli connect errno()!=0){ Die (”Connection aborted”.mysqli connect error()); } echo $mi−>stat(); $mi−>close();
PHP and MySQL PHP and MySQL together: mysqli 42
$host=’localhost’; $user=’root’; $pwd=’toto14’; $dbase=’example’; $mi = new mysqli($host,$user,$pwd,$dbase); if(mysqli connect errno()!=0){ Die (”Connection aborted”.mysqli connect error()); } $sql = ’select ∗ from article’; $result = $mi−>query($sql); if(is object($result)){ $number = $result−>num rows; echo ”Number of rows: $number<br>\n”; while ($row = $result−>fetch array(MYSQLI ASSOC)){ echo implode(”, ”, $row); } } else{ Die($mi−>error); } $mi−>close();
PHP and MySQL PHP and MySQL together: mysqli 43
◮ dBase (dbase) ◮ FrontBase (fbsql) ◮ InterBase (ibase) ◮ Informix (ifx) ◮ MiniSQL (msql) ◮ Microsoft SQL Server (mssql) ◮ Mysql (mysql) ◮ Mysqli (mysqli) ◮ Oracle, version 7, 8 and 9 (oci8) ◮ PostgreSQL (pgsql) ◮ SQLite (sqlite) ◮ Sybase (sybase)
PHP and MySQL PHP and MySQL together: Pear DB Library 44
◮ Development does not depend too much of the server ◮ Should be possible to replace a server by another one just
PHP and MySQL PHP and MySQL together: Pear DB Library 45
PHP and MySQL PHP and MySQL together: Pear DB Library 46
require ’DB.php’; $db=DB::connect(’mysql://root:toto14@localhost/example’); if(DB::isError($db)){ Die(”Error ”.$db−>getMessage().”<br>\n”); } $query = ”insert into vat values(’’,19.6)”; $q = $db−>query($query); echo ”execute <code>$query</code><br>\n”; if (DB::isError($q)){ Die(”query error :”.$q−>getMessage()); } /∗ //equals $db−>setErrorHandling(PEAR ERROR DIE); $q = $db−>query($query); ∗/
PHP and MySQL PHP and MySQL together: Pear DB Library 47
// We can use a placeholder in a query : ? $db−>setErrorHandling(PEAR ERROR DIE); $query = ”insert into vat values(’’,?)”; $val1 = 20.6; $db−>query($query, $val1); // We can also use many placeholders $query = ”insert into article values(’’,?,1,1,?,?)”; $name = ’Computer’; $price=1500; $description=’This computer is tip−top, very cheap and fast’; $price <br>\$description = $description<br>\n”; $db−>query($query, array($name,$price,$description));
PHP and MySQL PHP and MySQL together: Pear DB Library 48
PHP and MySQL PHP and MySQL together: Pear DB Library 49
PHP and MySQL PHP and MySQL together: Pear DB Library 50
Each row is put in an associative array $db−>setFetchMode(DB FETCHMODE ASSOC); $query = ”select ∗ from article”; $res = $db−> query($query); while($row = $res−>fetchRow()){ echo ”The price of $row[name] is $row[price]<br>\n”; } $rows = $db−>getAll($query); foreach($rows as $row){ echo ”{$row[’name’]} at CHF {$row[’price’]}<br>\n”; } $expensive = $db−>getRow(”select ∗ from article ”. ”order by price desc limit 1”); echo ”The most expensive article is $expensive[name]”. ” at CHF $expensive[price]<br>\n”;
PHP and MySQL PHP and MySQL together: Pear DB Library 51
PHP and MySQL PHP and MySQL together: Pear DB Library 52
◮ Do not require a programmer to write HTML ◮ they are used to access DB’s ◮ forms and db’s are the two pillars of web programming ◮ a lot of other finesses to be discovered ◮ SQL : a semester course of 2 hours a week
◮ A standard web architecture is LAMP: Linux Apache MySQL
PHP and MySQL Conclusion 53