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:
View:27 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
Transcript:
  • Accessing Your MySQL Database from the Web with PHP (Ch 11)*

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

    Browser issues HTTP request for page x.phpWeb server receives request, retrieves page, passes it for processing to PHP enginePHP engines parses script; if statements to connect to a DB and execute queries PHP opens a connection to the MySQL server, sends the appropriate queriesMySQL server receives query, processes it, sends results to the PHP enginePHP finishes processing the script, which usually involves formatting query results (= a set of tuples for SELECT) in HTML; returns resulting HTML to the web serverWeb server passes the HTML document back to browser, which renders itNote: 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

  • PHP supports libraries for connecting to a large number of DBMS products: Oracle, Ms SQL Server, PostgreSQL, MySQLThe 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 anotherDatabase Libraries*

  • Accessing MySQL DBs from PHPHow to connect a MySQL db to a web-based front end.Key topics:Setting up connections to a MySQL serverSelecting a db to useQuerying the db and retrieving query resultsChanging the data in the dbUsing prepared statementsDisconnecting from the MySQL server(http://us.php.net/manual/en/intro.mysqli.php)

    *

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

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

  • A web-based front end search form:

    Choose Search Type: Author Title ISBN Enter Search Term: results.php = the script that queries the db and presents resultsQuerying a DB from the Web*

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

  • Checking and filtering input data coming from the userstrip 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*

  • 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*

  • 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 failureThe 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*

  • Querying a DB from the WebCheck if the attempted connection succeeded:if (!$db) { echo ''. mysqli_connect_error().''; exit; // = display error string message from previous mysqli_connect() & exit}

  • 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 'Error db select ' . mysqli_error($link) . ' ';exit; // = display error string message from previous mysqli operation & exit }Querying a DB from the Web*

  • 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 doesnt 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*

  • 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*

  • Retrieving the query results: for ($i=0; $i < $num_results; $i++) { $row = mysqli_fetch_assoc($result); echo "".($i+1).". Title: "; echo htmlspecialchars(stripslashes($row['title'])); echo "Author: "; echo stripslashes($row['author']); echo "ISBN: "; echo stripslashes($row['isbn']); echo "Price: "; echo stripslashes($row['price']); echo ""; }Querying a DB from the Web*

  • 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_BOTHfalse if there are no more rows.Querying a DB from the Web*

  • 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 scriptClose 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*

    **************

of 17/17
Accessing Your MySQL Database from the Web with PHP (Ch 11) 1
Embed Size (px)
Recommended