Web Programming– UFCFB3-30-1 Lecture 24-25-26 Instructor : Mazhar H Malik Email : mazhar@gcet.edu.om Global College of Engineering and Technology
MYSQL and PHP
Performing MySQL queries from PHP 1. Connect to the MySQL database 2. Select the database to use 3. Perform the desired SQL queries 4. Retrieve data returned from the queries 5. Close the connection to the database
1. Connecting to the database Use mysql_connect: mysql_connect([$hostname [,$username [,$password [,$dbname [,$port [,$socket]]]]]]); In the lab: mysql_connect($hostname, $username, $password); Where: $hostname = "localhost"; $username = your MySQL username (by defaut "root") $password = your MySQL password (by default "")
1. Connecting to the database Example, with error handling: $link = mysql_connect("localhost", "root", "''); if (!$link) die('Could not connect: ' . mysql_error()); else echo "Connection successful!";
2. Select the database to use Use mysql_select_db: mysql_select_db($dbname, $link); Example: mysql_select_db('visitdb', $link);
2. Select the database to use Example, with error checking: $db_selected = mysql_select_db('visitdb', $link); if (!$db_selected) die('Can\'t use visitdb: ' . mysql_error());
3. Performing a basic query Use: mysql_query: mysql_query($query [, $link]); Example: $query = "SELECT * FROM visitors"; $result = mysql_query($query, $link);
3. Performing a basic query Example, with error checking: $query = "SELECT * FROM visitors"; $result = mysql_query($query, $link); if (!$result) { $message = 'Invalid query: ' . mysql_error() . "\n"; die($message); }
4. Retrieving data returned by the query Output of the mysql_query function doesn’t hold the data Used as a reference to fetch the table rows returned Fetching done using one of: mysql_fetch_array mysql_fetch_assoc mysql_fetch_row
Using mysql_fetch_array Version 1 – using numerical indexing: while ($row = mysql_fetch_array($result, MYSQL_NUM)) { echo "$row[0]<br>"; } This displays the value of the first field (index=0) of all the records returned by the query
Using mysql_fetch_array Version 2 – using key-value pairs: while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "row[name]<br>"; } This displays the value associated to the key ‘name’ of all the records returned by the query
Using the other fetch functions mysql_fetch_assoc($result) mysql_fetch_array($result, MYSQL_ASSOC) mysql_fetch_row($result) mysql_fetch_array($result, MYSQL_NUM)
5. Closing the db connection Use mysql_close: mysql_close($link); Where $link represents an opened connection
$num = mysql_num_rows($result); Count rows Use mysql_num_rows: $num = mysql_num_rows($result); Where: $result is the result of a query.
Count columns Use mysql_num_fields: $num = mysql_num_fields($result); Example: $result = mysql_query("SELECT name ,email FROM visitors"); echo mysql_num_fields($result); // return 2
Go to (http://localhost/phpmyadmin )Where it says Create database, enter a name and click on the Create button
Create a table to hold the data. Give it a name Create a table to hold the data. Give it a name. Select a number of columns and click Go.
Lecture10a.sql Copy this code and paste it in SQL. create table if not exists visitors( visitorID int unsigned not null auto_increment primary key, name char(50) not null, email char(50), Affiliation char(200)); create table if not exists organisations( organisationID int unsigned not null auto_increment primary key, address char(200), notes text); create table if not exists visits( visitID int unsigned not null auto_increment primary key, visitorID int unsigned not null, organisationID int unsigned not null, date date); insert into visitors (name, email) values ('John Doe', 'j.d@napier.ac.uk'), ('Jim Doe', 'ji.d@napier.ac.uk'), ('Jon Doe', 'jo.d@napier.ac.uk'); insert into organisations (name, address, notes) values ('ACME', 'New York', NULL), ('abcde.com', 'Bathgate', 'No comment!'); insert into visits values (NULL, 1, 2, '2000-12-20'), (NULL, 2, 2, '2004-04-21'), (NULL, 1, 2, '2006-05-06'); Lecture10a.sql Copy this code and paste it in SQL.
Example lecture10b.php Lecture10b.php <?php /*Step 1: Open a connection to the database (server_name=localhost, default username=root and default password=root */ $link= mysql_connect("localhost", "root", ""); //Step 2: Select a database mysql_select_db("visitdb", $link); //Step 3a: Create the query string $query="SELECT * FROM visitors"; //Step 3b: Execute the query $result = mysql_query($query, $link); //Step 4: Loop through the result set, doing something useful with it while ($row = mysql_fetch_array($result, MYSQL_NUM)) { echo "<p>"; foreach ($row as $x) echo $x. " "; echo "</p>"; } //Step 5: Close database connection mysql_close($link); ?> VisitorID Name Email Affiliation 1 John Doe j.d@napier.ac.uk 2 Jim Doe ji.d@napier.ac.uk 3 jo.d@napier.ac.uk
How to run lecture10b.php file? Save the file lecture10b.php in the folder c:/xampp/htdocs Go to Internet Explorer In the URL address type http://localhost/lecture10b.php
Run the lecture10b.php file to get the results below Visitors VisitorID Name Email Affiliation 1 John Doe j.d@napier.ac.uk 2 Jim Doe ji.d@napier.ac.uk 3 jo.d@napier.ac.uk
PDO PDO (PHP Data Objects) is a PHP extension to formalize PHP's database connections by creating a uniform interface. This allows developers to create code which is portable across many databases and platforms. PDO supports the following databases: Microsoft SQL Server / Sybase , Firebird / Interbase, DB2 / INFORMIX (IBM), MySQL, OCI (Oracle Call Interface), ODBC, PostgreSQL, SQLite There are three simple rules to use PDO: Use exec() when there is no result set (will tell you how many rows affected) Use query() when there are rows to return, and the query will be run once, with no variable parameters Use a prepared statement when the query will be run with variable parameters PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL 3.x, 4.x and 5.x databases.
Lecture10c.php 1. Use exec() when there is no result set (will tell you how many rows affected) <?php Try { //steps 1 and 2 $dbh = new PDO("mysql:host=localhost;dbname=visitdb", "root", ""); //step 3 $query = "INSERT INTO visitors(Name,Email,Affiliation) VALUES ('michael', 'michael@yahoo.com', 'Otago University')"; //step 4 $affected = $dbh->exec($query); echo "Total rows affected: $affected"; //step 5 $dbh=null;//close connection } catch(PDOException $e) { echo $e->getMessage(); ?> VisitorID Name Email Affiliation 1 John Doe j.d@napier.ac.uk 2 Jim Doe ji.d@napier.ac.uk 3 jo.d@napier.ac.uk 4 michael michael@yahoo.com
How to run lecture10c.php file? Save the file lecture10c.php in the folder c:/xampp/htdocs Go to Internet Explorer In the URL address type http://localhost/lecture10c.php
Run the lecture10c.php file to get the results below
$dbh = new PDO("mysql:host=localhost;dbname=visitdb", "root", ""); 2. Use query() when there are rows to return, and the query will be run once, with no variable parameters Lecture10d.php <?php Try { $dbh = new PDO("mysql:host=localhost;dbname=visitdb", "root", ""); $query = "SELECT Name, Email FROM visitors"; foreach ($dbh->query($query) as $row) $Name = $row['Name']; $Email = $row['Email']; echo "Name: $Name Email: $Email<br>"; } $dbh=null;//close connection catch(PDOException $e) echo $e->getMessage(); ?> VisitorID Name Email Affiliation 1 John Doe j.d@napier.ac.uk 2 Jim Doe ji.d@napier.ac.uk 3 jo.d@napier.ac.uk 4 michael michael@yahoo.com
Run the lecture10d.php file to get the results below
$dbh = new PDO("mysql:host=localhost;dbname=visitdb", "root", ""); 3. Use a prepared statement when the query will be run with variable parameters Lecture10e.php <?php try{ $dbh = new PDO("mysql:host=localhost;dbname=visitdb", "root", ""); $query = "SELECT * FROM visitors"; $stmt = $dbh->prepare($query); //$stmt->bindParam(":Name", ":John Doe"); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); print_r($result); $dbh=null; //close connection } catch(PDOException $e) { echo $e->getMessage(); ?> VisitorID Name Email Affiliation 1 John Doe j.d@napier.ac.uk 2 Jim Doe ji.d@napier.ac.uk 3 jo.d@napier.ac.uk 4 michael michael@yahoo.com
Run the lecture10e.php file to get the results below