+ All Categories
Home > Documents > Accessing Your MySQL Database from the Web with PHP (Ch 11)

Accessing Your MySQL Database from the Web with PHP (Ch 11)

Date post: 02-Jan-2016
Category:
Upload: daria-allison
View: 31 times
Download: 1 times
Share this document with a friend
Description:
Accessing Your MySQL Database from the Web with PHP (Ch 11). The Web Database Architecture…. Architecture for delivering a DB-backed website (= 3-tier web application) Browser issues HTTP request for page x.php - PowerPoint PPT Presentation
17
Accessing Your MySQL Database from the Web with PHP (Ch 11) 1
Transcript
Page 1: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

Accessing Your MySQL Database from

the Web with PHP (Ch 11)

1

Page 2: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

2

Architecture for delivering a DB-backed website (= 3-tier web application)

1. Browser issues HTTP request for page x.php

2. Web server receives request, retrieves page, passes it for processing to PHP engine

3. PHP engines parses script; if statements to connect to a DB and execute queries PHP opens a connection to the MySQL server, sends the appropriate queries

4. MySQL server receives query, processes it, sends results to the PHP engine

5. PHP finishes processing the script, which usually involves formatting query results (= a set of tuples for SELECT) in HTML; returns resulting HTML to the web server

6. Web server passes the HTML document back to browser, which renders it

Note: the process is the same regardless of what web & DB servers are used, or if they are on the same or on different machines.

The Web Database Architecture…

Page 3: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

PHP supports libraries for connecting to a large number of DBMS products: Oracle, Ms SQL Server, PostgreSQL, MySQL

The mySQL library is specific to the MySQL system we use: MySQL Improved library → our focus;

The PEAR::DB database library is database independent Specific backends support many different databasesMore limited as it has to cover the common features of all DBMSs to

which it can connect.

In general, the principles of connecting to and querying any db through different libraries are the sameSome differences in function names, functionality for different librariesYou should be able to easily adapt your knowledge from one to another

Database Libraries

3

Page 4: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

Accessing MySQL DBs from PHP

How to connect a MySQL db to a web-based front end.

Key topics: Setting up connections to a MySQL server Selecting a db to use Querying the db and retrieving query results Changing the data in the db Using prepared statements Disconnecting from the MySQL server (http://us.php.net/manual/en/intro.mysqli.php)

4

Page 5: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

Chapter11/search.htmlhttp://cscdb.nku.edu/csc301/frank/Chapter11/search.html

http://www.nku.edu/~frank/csc301/Examples/MySQL/search_html.pdf

Page 6: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

A web-based front end search form:

<form action="results.php" method="post"> Choose Search Type:<br /> <select name="searchtype">

<option value="author"> Author </option> <option value="title"> Title </option> <option value="isbn"> ISBN </option>

</select> <br /> <br /> Enter Search Term:<br />

<input name="searchterm" type="text" size="40" /> <br />

<input type="submit" name="submit" value="Search" /> </form>

results.php = the script that queries the db and presents results

Querying a DB from the Web

6

Page 7: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

Chapter11/result.phphttp://www.nku.edu/~frank/csc301/Examples/MySQL/

results_php.pdf

Page 8: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

I. Checking and filtering input data coming from the user

strip any whitespace from the appropriate form variables:$searchtype = $_POST['searchtype'];

$searchterm = trim($_POST['searchterm']);

verify that the data your script needs has been entered:if (!$searchtype || !$searchterm) {

// … display a warning message and exit script;

}

Querying a DB from the Web

8

Page 9: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

I. Checking and filtering input data coming from the userfilter user input for control characters when submitting it to a db;

un-escape data coming from the db if magic quotes is on:if (!get_magic_quotes_gpc()){

$searchtype = addslashes($searchtype);

$searchterm = addslashes($searchterm);

}

$data = stripslashes($dbdata);

use htmlspecialchars() to encode for display the db data that might contain characters with special meaning in HTML (&, <, > etc.)

echo htmlspecialchars($data);

Querying a DB from the Web

9

Page 10: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

II. Setting up a connection to MySQL server (mysqli library) mysqli_resource mysqli_connect ( string $server, string $username,

string $password, string $database)

mysqli_connect() returns a resource representing the connection to a database on success, and false on failure

The resource returned will be passed to all the other mysqli functions that work over that connection → similar to file-handling functions

@ $db =

mysqli_connect('localhost',’frank',’mypassword’,’db_frank’);

Querying a DB from the Web

10

Page 11: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

Querying a DB from the Web

Check if the attempted connection succeeded: if (!$db) { echo '<p>'. mysqli_connect_error().'</p></body></html>';

exit; // = display error string message from previous mysqli_connect() & exit}

Page 12: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

III. Choosing a database to use:When using MySQL from a command-line interface:

use db_books;When connecting from PHP:

bool mysqli_select_db (mysqli_resource $link, string $db_name )

Returns true on success or false on failure.

Example:if (!mysqli_select_db ($link, "db_books")) {

echo '<p>Error db select ' . mysqli_error($link) . '</p> </body> </html>';

exit; // = display error string message from previous mysqli operation & exit }

Querying a DB from the Web

12

Page 13: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

IV. Querying the database:

Set up as a string the query you want to run:

$query = “select * from books where ” . $searchtype . “ like ‘%” . $searchterm . “%’”;

Note: the query you send to MySQL doesn’t need “;” at the end!

Run the query and store the result in a variable for later use:

mixed mysqli_query (mysqli_resource $link , string $query)

For SELECT query, returns a result resource on success, or F on error.

$result = mysqli_query($link, $query);

Querying a DB from the Web

13

Page 14: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

V. Retrieving the query results:

Retrieve the number of rows returned by the query:

int mysqli_num_rows ( mysqli_result_resource $result )

$num_results = mysql_num_rows($result);

Retrieve each row from the resultset and process it → in our example, display it.

array mysqli_fetch_assoc(mysqli_result_resource $result );

Returns: next row from the resultset, in an associative array: keys = attribute names,

values = the values in the row → each field accessible as an array element; false if there are no more rows.

Querying a DB from the Web

14

Page 15: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

V. Retrieving the query results: for ($i=0; $i < $num_results; $i++) {

$row = mysqli_fetch_assoc($result);

echo "<p><strong>".($i+1).". Title: ";

echo htmlspecialchars(stripslashes($row['title']));

echo "</strong><br />Author: ";

echo stripslashes($row['author']);

echo "<br />ISBN: ";

echo stripslashes($row['isbn']);

echo "<br />Price: ";

echo stripslashes($row['price']);

echo "</p>";

}

Querying a DB from the Web

15

Page 16: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

V. Retrieving the query results - alternatives:array mysqli_fetch_row (mysqli_result_resource $result );

Returns: next row from the resultset, in a numerically indexed array: indexes start at 0,

values are the values in the row; false if there are no more rows.

array mysqli_fetch_array (mysqli_result_resource $result [, int $result_type = MYSQL_BOTH ] );

Returns: next row, in an array with: associative keys for MYSQL_ASSOC, number

indices for MYSQL_NUM, associative keys & number indices for MYSQL_BOTH

false if there are no more rows.

Querying a DB from the Web

16

Page 17: Accessing Your  MySQL  Database from  the Web with PHP (Ch 11)

VI. Disconnecting from the database:

Free up the resultset:

void mysqli_free_result (mysqli_result_resource $result )

Note: not strictly necessary, as all associated result memory is automatically freed at the end of the script's execution; good idea if you use more memory-intensive resources before the end of script

Close the database connection:

bool mysqli_close( mysqli_resource $link )

This function returns true on success or false on failure.

Querying a DB from the Web

17


Recommended