Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web Programming– UFCFB Lecture

Similar presentations


Presentation on theme: "Web Programming– UFCFB Lecture"— Presentation transcript:

1 Web Programming– UFCFB3-30-1 Lecture 24-25-26
Instructor : Mazhar H Malik Global College of Engineering and Technology

2 MYSQL and PHP

3 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

4 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 "")

5 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!";

6 2. Select the database to use
Use mysql_select_db: mysql_select_db($dbname, $link); Example: mysql_select_db('visitdb', $link);

7 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());

8 3. Performing a basic query
Use: mysql_query: mysql_query($query [, $link]); Example: $query = "SELECT * FROM visitors"; $result = mysql_query($query, $link);

9 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); }

10 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

11 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

12 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

13 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)

14 5. Closing the db connection
Use mysql_close: mysql_close($link); Where $link represents an opened connection

15 $num = mysql_num_rows($result);
Count rows Use mysql_num_rows: $num = mysql_num_rows($result); Where: $result is the result of a query.

16 Count columns Use mysql_num_fields: $num = mysql_num_fields($result);
Example: $result = mysql_query("SELECT name , FROM visitors"); echo mysql_num_fields($result); // return 2

17 Go to ( )Where it says Create database, enter a name and click on the Create button

18 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.

19 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, 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, ) values ('John Doe', ('Jim Doe', ('Jon Doe', insert into organisations (name, address, notes) values ('ACME', 'New York', NULL), ('abcde.com', 'Bathgate', 'No comment!'); insert into visits values (NULL, 1, 2, ' '), (NULL, 2, 2, ' '), (NULL, 1, 2, ' '); Lecture10a.sql Copy this code and paste it in SQL.

20 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 Affiliation 1 John Doe 2 Jim Doe 3

21 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

22 Run the lecture10b.php file to get the results below
Visitors VisitorID Name Affiliation 1 John Doe 2 Jim Doe 3

23 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.

24 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, ,Affiliation) VALUES ('michael', '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 Affiliation 1 John Doe 2 Jim Doe 3 4 michael

25 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

26 Run the lecture10c.php file to get the results below

27 $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, FROM visitors"; foreach ($dbh->query($query) as $row) $Name = $row['Name']; $ = $row[' ']; echo "Name: $Name $ <br>"; } $dbh=null;//close connection catch(PDOException $e) echo $e->getMessage(); ?> VisitorID Name Affiliation 1 John Doe 2 Jim Doe 3 4 michael

28 Run the lecture10d.php file to get the results below

29 $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 Affiliation 1 John Doe 2 Jim Doe 3 4 michael

30 Run the lecture10e.php file to get the results below


Download ppt "Web Programming– UFCFB Lecture"

Similar presentations


Ads by Google