Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to SQL Programming Techniques

Similar presentations


Presentation on theme: "Intro to SQL Programming Techniques"— Presentation transcript:

1 Intro to SQL Programming Techniques
Chapter 13 &14 Intro to SQL Programming Techniques & Web DB + PhP

2 Chapter 13 Outline Database Programming: Techniques and Issues
Database Programming with Function Calls: SQL/CLI and JDBC

3 Introduction to SQL Programming Techniques
Database applications Host language Java, C/C++/C#, COBOL, or some other programming language Data sublanguage SQL SQL standards Continually evolving Each DBMS vendor may have some variations from standard

4 Approaches to Database Programming
Embedding database commands in a general-purpose programming language Database statements identified by a special prefix Precompiler or preprocessor scans the source program code Identify database statements and extract them for processing by the DBMS Called embedded SQL

5 Approaches to Database Programming
Using a library of database functions Library of functions available to the host programming language Application programming interface (API) Designing a brand-new language Database programming language designed from scratch First two approaches are more common

6 Impedance Mismatch Differences between database model and programming language model Binding for each host programming language Specifies for each attribute type the compatible programming language types Cursor or iterator variable Loop over the tuples in a query result

7 Typical Sequence of Interaction in Database Programming
Open a connection to database server Interact with database by submitting queries, updates, and other database commands Terminate or close connection to database

8 Embedded SQL, Dynamic SQL, SQLJ
C language SQLJ Java language Programming language called host language

9 Retrieving Single Tuples with Embedded SQL
EXEC SQL Prefix Preprocessor separates embedded SQL statements from host language code Terminated by a matching END-EXEC Or by a semicolon (;) Shared variables Used in both the C program and the embedded SQL statements Prefixed by a colon (:) in SQL statement

10 C Program Segment Embedded SQL

11 Retrieving Single Tuples with Embedded SQL
Connecting to the database CONNECT TO <server name>AS <connection name> AUTHORIZATION <user account name and password> ; Change connection SET CONNECTION <connection name> ; Terminate connection DISCONNECT <connection name> ;

12 Retrieving Single Tuples with Embedded SQL (cont’d.)
SQLCODE and SQLSTATE communication variables Used by DBMS to communicate exception or error conditions SQLCODE variable 0 = statement executed successfully 100 = no more data available in query result < 0 = indicates some error has occurred

13 Retrieving Single Tuples with Embedded SQL (cont’d.)
SQLSTATE String of five characters ‘00000’ = no error or exception Other values indicate various errors or exceptions For example, ‘02000’ indicates ‘no more data’ when using SQLSTATE

14 C Program Segment Embedded SQL

15 Retrieving Multiple Tuples with Embedded SQL Using Cursors
Points to a single tuple (row) from result of query OPEN CURSOR command Fetches query result and sets cursor to a position before first row in result Becomes current row for cursor FETCH commands Moves cursor to next row in result of query

16 C Program Segment Embedded SQL

17 JDBC: SQL Function Calls for Java Programming
Java function libraries Single Java program can connect to several different databases Called data sources accessed by the Java program Class.forName("oracle.jdbc.driver.OracleDriver") Load a JDBC driver explicitly

18 JDBC: SQL Function Calls for Java Programming
Connection object Statement object has two subclasses: PreparedStatement and CallableStatement Question mark (?) symbol Represents a statement parameter Determined at runtime ResultSet object Holds results of query

19 Figure 10.12 Program segment JDBC1, a Java program segment with JDBC.

20 Figure Program segment JDBC2, a Java program segment that uses JDBC for a query with a collection of tuples in its result.

21 Chapter 14 Outline A Simple PHP Example
Overview of Basic Features of PHP Overview of PHP Database Programming

22 Web Database Programming Using PHP
Techniques for programming dynamic features into Web PHP Open source scripting language Interpreters provided free of charge Available on most computer platforms

23 A Simple PHP Example PHP DBMS HTML
Open source general-purpose scripting language Comes installed with the UNIX operating system DBMS Bottom-tier database server Middle-tier Web server HTML Client tier

24 A Simple PHP Example Middle-tier Web Server Database Server
Client Tier

25 Figure 11.1a PHP program segment for entering a greeting.
continued on next slide

26 Figure 11. 1b-d (b) Initial form displayed by PHP program segment
Figure 11.1b-d (b) Initial form displayed by PHP program segment. (c) User enters name John Smith. (d) Form prints welcome message for John Smith.

27 Introduction to PHP From center for communication sciences at RPI

28 You are encouraged to visit the site – it is a great resource.
Welcome This slideshow presentation is designed to introduce you to PHP. It is the first of two PHP workshops available at In addition to the two PHP workshops, there are also workshops on HMTL and CSS. These slides are based on source material found at the w3schools.com website. You are encouraged to visit the site – it is a great resource.

29 Caveat PHP and MySQL are tricky to teach without access to a server and a database. We'll do the best we can in the slides that follow. They are also tricky considering how complex they are. Take a look at the PHP cheat sheet I found online...

30 Yikes

31 PHP Introduction PHP is a recursive acronym for “PHP: Hypertext Preprocessor” -- It is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

32 PHP Introduction > PHP is a server-side scripting language
> PHP scripts are executed on the server > PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)‏ > PHP is open source software > PHP is free to download and use

33 PHP Introduction > PHP runs on different platforms (Windows, Linux, Unix, etc.)‏ > PHP is compatible with almost all servers used today (Apache, IIS, etc.)‏ > PHP is FREE to download from the official PHP resource: > PHP is easy to learn and runs efficiently on the server side

34 PHP Introduction > MySQL is a database server
Some info on MySQL which we will cover in the next workshop... > MySQL is a database server > MySQL is ideal for both small and large applications > MySQL supports standard SQL > MySQL compiles on a number of platforms > MySQL is free to download and use

35 PHP Introduction Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (like in the next slide, it outputs "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode."

36 PHP Introduction <? … ?> has replaced <?php … ?>

37 PHP Introduction PHP code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. A visual, if you please...

38 PHP Introduction

39 PHP Getting Started On windows, you can download and install WAMP. With one installation and you get an Apache webserver, database server and php. On mac, you can download and install MAMP.

40 Above is the PHP source code.
PHP Hello World Above is the PHP source code.

41 It renders as HTML that looks like this:
PHP Hello World It renders as HTML that looks like this:

42 PHP Hello World This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

43 PHP Comments In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.

44 PHP Variables > Variables are used for storing values, like text strings, numbers or arrays. > When a variable is declared, it can be used over and over again in your script. > All variables in PHP start with a $ sign symbol. > The correct way of declaring a variable in PHP:

45 PHP Variables > In PHP, a variable does not need to be declared before adding a value to it. > In the example above, you see that you do not have to tell PHP which data type the variable is. > PHP automatically converts the variable to the correct data type, depending on its value.

46 PHP Variables > A variable name must start with a letter or an underscore "_" -- not a number > A variable name can only contain alpha-numeric characters, underscores (a-z, A-Z, 0-9, and _ )‏ > A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string) or with capitalization ($myString)‏

47 PHP Concatenation > The concatenation operator (.) is used to put two string values together. > To concatenate two string variables together, use the concatenation operator:

48 PHP Concatenation The output of the code on the last slide will be:
If we look at the code you see that we used the concatenation operator two times. This is because we had to insert a third string (a space character), to separate the two strings.

49 PHP Operators Operators are used to operate on values. There are four classifications of operators: > Arithmetic > Assignment > Comparison > Logical

50 PHP Operators

51 PHP Operators

52 PHP Operators

53 PHP Operators

54 PHP Conditional Statements
> Very often when you write code, you want to perform different actions for different decisions. > You can use conditional statements in your code to do this. > In PHP we have the following conditional statements...

55 PHP Conditional Statements
> if statement - use this statement to execute some code only if a specified condition is true > if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false > if...elseif....else statement - use this statement to select one of several blocks of code to be executed > switch statement - use this statement to select one of many blocks of code to be executed

56 PHP Conditional Statements
The following example will output "Have a nice weekend!" if the current day is Friday:

57 PHP Conditional Statements
Use the if....else statement to execute some code if a condition is true and another code if a condition is false.

58 PHP Conditional Statements
If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces { }

59 PHP Conditional Statements
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":

60 PHP Conditional Statements
Use the switch statement to select one of many blocks of code to be executed.

61 PHP Conditional Statements
For switches, first we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

62 PHP Conditional Statements

63 PHP Arrays > An array variable is a storage area holding a number or text. The problem is, a variable will hold only one value. > An array is a special variable, which can store multiple values in one single variable.

64 PHP Arrays If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

65 PHP Arrays > However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? > The best solution here is to use an array. > An array can hold all your variable values under a single name. And you can access the values by referring to the array name. > Each element in the array has its own index so that it can be easily accessed.

66 PHP Arrays In PHP, there are three kind of arrays:
> Numeric array - An array with a numeric index > Associative array - An array where each ID key is associated with a value > Multidimensional array - An array containing one or more arrays

67 PHP Numeric Arrays > A numeric array stores each array element with a numeric index. > There are two methods to create a numeric array.

68 PHP Numeric Arrays In the following example the index is automatically assigned (the index starts at 0): In the following example we assign the index manually:

69 PHP Numeric Arrays In the following example you access the variable values by referring to the array name and index: The code above will output:

70 PHP Associative Arrays
> With an associative array, each ID key is associated with a value. > When storing data about specific named values, a numerical array is not always the best way to do it. > With associative arrays we can use the values as keys and assign values to them.

71 PHP Associative Arrays
In this example we use an array to assign ages to the different persons: This example is the same as the one above, but shows a different way of creating the array:

72 PHP Associative Arrays

73 PHP Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

74 PHP Multidimensional Arrays

75 PHP Multidimensional Arrays

76 PHP Multidimensional Arrays

77 PHP Loops > Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. > In PHP, we have the following looping statements:

78 PHP Loops > while - loops through a block of code while a specified condition is true > do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true > for - loops through a block of code a specified number of times > foreach - loops through a block of code for each element in an array

79 PHP Loops - While The while loop executes a block of code while a condition is true. The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

80 PHP Loops - While

81 PHP Loops – Do ... While The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true. The next example defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5:

82 PHP Loops – Do ... While

83 PHP Loops – Do ... While

84 PHP Loops - For

85 PHP Loops - For Parameters:
> init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)‏ > condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. > increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop)‏

86 PHP Loops - For The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

87 PHP Loops - For

88 PHP Loops - Foreach For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.

89 PHP Loops - Foreach The following example demonstrates a loop that will print the values of the given array:

90 Winner of the most impressive slide award
PHP Loops - Foreach Winner of the most impressive slide award

91 PHP Functions > We will now explore how to create your own functions. > To keep the script from being executed when the page loads, you can put it into a function. > A function will be executed by a call to the function. > You may call a function from anywhere within a page.

92 PHP Functions A function will be executed by a call to the function.
> Give the function a name that reflects what the function does > The function name can start with a letter or underscore (not a number)‏

93 A simple function that writes a name when it is called:
PHP Functions A simple function that writes a name when it is called:

94 PHP Functions - Parameters
Adding parameters... > To add more functionality to a function, we can add parameters. A parameter is just like a variable. > Parameters are specified after the function name, inside the parentheses.

95 PHP Functions - Parameters

96 PHP Functions - Parameters

97 PHP Functions - Parameters
This example adds different punctuation.

98 PHP Functions - Parameters

99 PHP Forms - $_GET Function
> The built-in $_GET function is used to collect values from a form sent with method="get". > Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send (max characters).

100 PHP Forms - $_GET Function
Notice how the URL carries the information after the file name.

101 PHP Forms - $_GET Function
The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array)‏

102 PHP Forms - $_GET Function
> When using method="get" in HTML forms, all variable names and values are displayed in the URL. > This method should not be used when sending passwords or other sensitive information! > However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. > The get method is not suitable for large variable values; the value cannot exceed 100 chars.

103 PHP Forms - $_POST Function
> The built-in $_POST function is used to collect values from a form sent with method="post". > Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. > Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).

104 PHP Forms - $_POST Function
And here is what the code of action.php might look like:

105 PHP Forms - $_POST Function
Apart from htmlspecialchars() and (int), it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP.

106 PHP Forms - $_POST Function
When to use method="post"? > Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. > However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

107 More web workshops can be found at
End of Workshop More web workshops can be found at

108 Intro to PHP A brief overview – Patrick Laverty

109 What is PHP? PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. <? echo “HI!”; ?>

110 What is PHP? Compared to others like:
Java – Sun, compiled and interpreted (jsp) Perl – Open Source, scripting .NET – MS, opposite of Java ColdFusion – Now Adobe, the original Javascript – Netscape, client-side PHP – Open Source, server-side

111 How it works PHP is installed on web server
Our web server is Apache (just an FYI) Server parses files based on extensions Returns plain HTML, no code

112 How To – The Basics Need to name files is a .php extension
Example: index.php, mypage.php Open and close tags: <? ?> Was: <?php ?> Save file to server, view in a browser

113 Hello World helloworld.php <html> <body>
<? echo “Hello World!”; ?> </body> </html>

114 Variables Variables are like a cup The same cup can hold
lots of different things Same with variables

115 Variables In PHP, you create a variable with a dollar sign and some text. Usually the text will be something descriptive of what it is going to hold. $name = “Patrick Laverty”; $dept = “CIS”; $campus_addr = “Box 1885”;

116 Variables There are many different kinds of variables in PHP Scalar
Array Object

117 Scalar Variables Hold single values String/text Numbers
$name = “Josiah”; $dob = “1/1/23”; $age = 84; $waist_size = 36;

118 Array Variables Hold multiple values
All in one step example: $kids = Array(“Tom”,”Dick”,”Harry”); Multiple steps example: $kids = Array(); $kids[0] = “Tom”; $kids[1] = “Dick”; $kids[2] = “Harry”; Individual array values are just a scalar

119 Array Variables Associative Arrays – may be easier to find stuff
$teams = Array(‘bos’=>’Red Sox’, ‘nyy’=>’Yankees’, ’bal’=>’Orioles’); The two-step way works the same: $teams = Array(); $teams[‘bos’] = ‘Red Sox’;

120 Object Variables We’ll talk about these later. We’re in no rush

121 Functions Getting PHP to do some action for you echo() or print()
phpinfo() (phpinfo.php)

122 Functions Be lazy. It’s a good thing.
If you’re going to do the same action more than once, write a function. sayhello.php function sayHello($toWhom) { echo “Hello $toWhom”; }

123 Functions Lots have already been written for you:
If you know the function:

124 A Basic Form How we do things now: eform.cgi
<form method=“POST” action= <input type=“text” name=“name”> <input type=“text” name=“age”> <input type=“submit”> </form>

125 A Basic Form How we do things with PHP: basicform.html
<form method=“POST” action=“output.php”> <input type=“text” name=“name”> <input type=“text” name=“age”> <input type=“submit”> </form>

126 A Basic Form Capturing the data in output.php Variables:
$_POST[‘name’] $_POST[‘age’] Use phpinfo() to see variables

127 A Basic Form Weave HTML and PHP output.php <html><body>
<? $name = $_POST[‘name’]; $age = $_POST[‘age’]; echo “My name is $name and I am $age years old”; ?> </body></html>

128 Data Validation We’ll talk more about validating user input later.

129 A Basic Form Outputting to the screen is nice, but boring
We could the results Let’s store data in a database

130 Layers of a Database Server Database Tables Fields/Columns Records

131 How to Get a Database Use Microsoft Access Use Filemaker
Request a MySQL Database (

132 Request a MySQL Database
You will receive: Server name (it’s not localhost) Database name Username Password Link to phpMyAdmin

133 phpMyAdmin phpMyAdmin is a graphical view of your database Very easy
Let’s take a look (

134 Connecting to DB from PHP
Create one connection script: dbconn.php <? $conn = mysql_connect($server,$user,$pw); mysql_select_db($db,$conn); ?>

135 Connecting to DB from PHP
Remember, “Be Lazy!” At the top of each file that needs the DB: <? require(“dbconn.php”); ?>

136 Database Table Table named ‘info’ has two fields, name and age
Use a SQL INSERT statement: $sql = “INSERT INTO info (name,age) values (‘$name’, ‘$age’)”;

137 Database Table Send it to the Database: mysql_query($sql,$conn);

138 The Whole Picture dbinsert.php <? require(“dbconn.php”);
$name = $_POST[‘name’]; $age = $_POST[‘age’]; $sql = “INSERT into info (name,age) values(‘$name’, ‘$age’);” mysql_query($sql,$conn); ?> <html><body> Thank you, your name and age were received. </body></html>

139 The Whole Picture - Fancier
fancydbinsert.php <? require(“dbconn.php”); $name = $_POST[‘name’]; $age = $_POST[‘age’]; $sql = “INSERT into info (name,age) values(‘$name’, ‘$age’);” $success = mysql_query($sql,$conn); ?> <html><body> <? if($success) { echo “Thank you, your name and age were received.”; } else { echo “Sorry, your info wasn’t received, please contact …”; } </body></html>

140 Getting the Info Back Read it in phpMyAdmin
Create an output page (Just like that little survey you filled out)

141 Create an Output Page Connect to the Server Do a query of the data
Programmatically write the data to a page View the page in a browser Let’s see how to do it

142 Connect to the Server First, include our connection script:
<? require(“dbconn.php”); ?>

143 Do a Query of the Data This time we use SELECT
$sql = “SELECT name, age FROM info”; Or if you have many fields and want to be LAZY! $sql = “SELECT * from info”;

144 Programmatically Write the Data
Here’s the only hard part: <table border=“1”> <? $result = mysql_query($sql, $conn); while($table = mysql_fetch_object($result)) { echo “<tr><td>”; echo $table->name; echo “</td><td>”; echo $table->age; echo “</td></tr>”; } ?> </table>

145 Putting it All Together
statuspage.php <? require(“dbconn.php”); $sql = “SELECT * FROM info”; $result = mysql_query($sql, $conn); ?> <html><body> <table border=“1”> <? while($table = mysql_fetch_object($result)) { echo “<tr><td>”; echo $table->name; echo “</td><td>”; echo $table->age; echo “</td></tr>”; } <table> </body></html>

146 I Hate Objects! If you don’t like using mysql_fetch_object:
mysql_fetch_array($result) mysql_fetch_assoc($result)

147 mysql_fetch_array() Access the columns by numbers:
while($array = mysql_fetch_array($result)) { echo $array[0]; echo $array[1]; }

148 mysql_fetch_assoc() Access the columns by column names:
while($array = mysql_fetch_assoc($result)) { echo $array[‘name’]; echo $array[‘age’]; }

149 One Helpful Function nl2br() – Line breaks in a form are not respected
This function will turn a newline (nl) character into (2) an html <br> (br) tag.

150 Data Validation Very Important!
Without it, your site and all others can be hacked! PHP makes it easier

151 Data Validation Cut down on XSS with htmlentities()
Cut down on SQL-injection with mysql_real_escape_string() Check that you’re getting what you expect Check that you’re getting the length you expect Don’t trust JavaScript

152 Data Validation Cross site scripting vulnerability
Allows a user to input scripts Allows a user to input links to malicious sites Allows a user to steal a session/cookie/password The htmlentities() function turns entities into its harmless entity number. A ‘ is turned into '

153 Data Validation SQL-injection vulnerability
Allows a user to directly access your database Allows a user to get access to other accounts Allows a user to read data you don’t want read Prevention can be as simple as escaping quotes with mysql_real_escape_string to all user input $clean_user = mysql_real_escape_string($_POST[‘username’]);

154 Data Validation Get what you expect to get
Don’t change it, give error message Example: (validinsert.php) Age, should be less than 110, and numeric. Reject anything else if(strlen($age)>3){ //error message } if(!is_int($age)){ //error message } if($age>110 || $age<18){ //error message }

155 Data Validation Get the length you expect
<input type=“text” name=“username” maxlength=“8”> Make sure the username is no longer than 8 if(strlen($username)>8)){ //error message }

156 Data Validation Don’t trust JavaScript
Do client side AND server side validation

157 Slide #50 I think that’s enough webpublishers@listserv.brown.edu
Next topic – to be announced for early May

158 Database Access with PHP and MySQL http://cs. hiram
CS356 Examples from Web Database Applications, by Hugh E. Williams & David Lane, O'Reilly, 2002

159 PHP for Database Access
Connect to the MySQL server $connection = mysql_connect("localhost", $username, $password); Access the database mysql_select_db("winestore", $connection); Perform SQL operations Disconnect from the server mysql_close($connection);

160 Error Handling All mysql_ functions return NULL (or false) if they fail. Several functions are helpful in graceful failure die(string) - halts and displays the string mysql_errno() - returns number of error mysql_error() - returns text of error

161 Error Handling examples
if (!($connection = mysql_connect("localhost",$name,$passwd))) die("Could not connect"); function showerror() { die("Error " . mysql_errno() . " : " . mysql_error()); } if (!(mysql_select_db("winestor", $connection))) showerror();

162 Building a Query Directly Using input information
$query = 'select * from wines'; Using input information $winery = $_POST['winery']; $query = “select * from wines where winery=$winery”;

163 Running a Query mysql_query returns a result handle
$result = mysql_query($query, $connection) mysql_num_rows indicates the number of rows returned $num_rows = mysql_num_rows($result) mysql_fetch_array creates array/hash of result For ($n=0; $n<$num_rows;$n++) $row = mysql_fetch_array($result)

164 Result of fetch_array Contains both numeric and index tags
Values are duplicated Example: Query: select surname, city from customers; Row: ( 0=>'Walker', ‘surname’=>'Walker', 1=>'Kent', 'city'=>'Kent' );

165 Printing the Complete Row
By number for ($i=0; $i<mysql_num_fields($result); $i++) echo $row[$i] . " "; By field echo $row['surname'] . ' ' . $row['city'];

166 Avoiding Special Characters
When building HTML, characters such as '&' in the data can cause problems Function htmlspecialchars() replaces all such characters with HTML escapes such as & print( htmlspecialchars($row['surname'] . ' ' . $row['city']);

167 Special Characters in Input
The same problem exists with special characters in input (e.g. ' ) PHP switch magic_quotes_gpc (default on) inserts backslashes before single & double quotes, backslashes and NULL characters in input data (from GET, PUT and cookie data) Use stripslashes() to remove the slashes Use addslashes() to add the slashes if magic_quotes_gpc is off

168 Avoid Dangerous User Input
Passing user input to other programs opens the door to exploits Eg. exec("/usr/bin/cal $input") Generates a calendar (/usr/bin/cal 2004) But a malevolent user might send '2004 ; cat /etc/passwd' or '2004 ; rm *' Overlong inputs can also cause problems Always clean input $input = escapeshellcmd($input); $input = substr($input,$maxlength);

169 PHP / Form in one Document
Combine the original form with the PHP document that processes data if empty($regionName)) { //parameter provided? //produce the <form> } else { //run the query using data from $_GET or $_POST

170 Inserting Into a Database
Collect data from a form Validate data (JavaScript, PHP or both) Create a query $query = "insert into customer set cust_id = NULL, " . "surname =\"" . $surname ."\"" … Run the query mysql_query($query, $db);

171 Updating a Database Query to find item to update
Present old information Collect new information Validate Construct and run the update query

172 Overview of PHP DB Programming
PEAR DB library Part of PHP Extension and Application Repository (PEAR) Provides functions for database access

173 Connecting to a Database
Library module DB.php must be loaded DB library functions accessed using DB::<function_name> DB::connect('string') Function for connecting to a database Format for 'string' is: <DBMS software>://<user server>

174 Figure 11.6 Connecting to a database, creating a table, and inserting a record.

175 Some Database Functions
Query function $d->query takes an SQL command as its string argument Sends query to database server for execution $d–>setErrorHandling(PEAR_ERROR_DIE) Terminate program and print default error messages if any subsequent errors occur

176 Collecting Data from Forms and Inserting Records
Collect information through HTML or other types of Web forms Create unique record identifier for each new record inserted into the database PHP has a function $d–>nextID to create a sequence of unique values for a particular table Placeholders Specified by ? symbol

177 Retrieval Queries from Database Tables
Variable that holds query result $q->fetchRow() retrieve next record in query result and control loop $allresult = $d->getAll(query) Holds all the records in a query result in a single variable called $allresult

178 Figure 11.7 Illustrating database retrieval queries.

179 Other techniques PHP runs on server
Sends HTML to client Many other languages/technologies for Web Db programming Examples: Java servlets: Java objects on server, interact with client Store information about interaction session

180 Other techniques (cont.)
Java Server Pages (JSP) Creates dynamic Web pages through scripting at server to send to client (somewhat like PHP) JavaScript Scripting language, can run at client or server Java Script Object Notation (JSON): Text-based representation of objects Similar function to XML Used in many NOSQL systems

181 Summary PHP scripting language PHP basics for Web programming
Very popular for Web database programming PHP basics for Web programming Data types Database commands include: Creating tables, inserting new records, and retrieving database records Looping over a query result


Download ppt "Intro to SQL Programming Techniques"

Similar presentations


Ads by Google