Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 10 – MYSQL and PHP (Part 2)

Similar presentations

Presentation on theme: "Lecture 10 – MYSQL and PHP (Part 2)"— Presentation transcript:

1 Lecture 10 – MYSQL and PHP (Part 2)
SFDV3011 – Advanced Web Development

2 Performing 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

3 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 “”)

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

5 Select the database to use
Use mysql_select_db: mysql_select_db($dbname, $link); Example: mysql_select_db(‘visitdb', $link);

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

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

8 Performing a basic query
Example, with error checking: $query = "SELECT * FROM visitors"; $result = mysql_query($query); if (!$result) { $message = 'Invalid query: ' . mysql_error() . "\n";  die($message); }

9 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

10 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

11 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

12 Using the other fetch functions
mysql_fetch_assoc($result)  mysql_fetch_array($result, MYSQL_ASSOC) mysql_fetch_row($result)  mysql_fetch_array($result, MYSQL_ENUM)

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

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

15 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

16 Example <?php /*Step 1: Open a connection to the database (server_name=localhost, default username=root and default password=root */ $conn = mysql_connect(“localhost”, “root”, “”); //Step 2: Select a database mysql_select_db(“visitdb", $conn); //Step 3: Create the query string $query=“SELECT * FROM visitors”; //Step 4: Execute the query $result = mysql_query($query, $conn); //Step 5: Loop through the result set, doing something useful with it while ($row = mysql_fetch_array($result, MYSQL_NUM)) { echo "<p>"; foreach ($row as $attribute) { echo $attribute . " "; } echo "</p>"; //Step 6: Close database connection mysql_close($conn); ?>

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

18 PDO (Insert) <?php try{
$dbh = new PDO("mysql:host=localhost;dbname=visitdb", “root", “"); $query = "INSERT INTO visitors(Name, ,Affiliation) VALUES ('michael', ‘Otago University‘)"; $affected = $dbh->exec($query); echo "Total rows affected: $affected"; $dbh=null;//close connection } catch(PDOException $e) { echo $e->getMessage(); ?>

19 PDO (Select) <?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(); ?>

20 PDO (Prepared Statement)
<?php try{ $dbh = new PDO("mysql:host=localhost;dbname=visitdb", “root", ""); $query = "SELECT * FROM visitors WHERE Name= :Name"; $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(); ?>

Download ppt "Lecture 10 – MYSQL and PHP (Part 2)"

Similar presentations

Ads by Google