Download lecture6

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Relational algebra wikipedia , lookup

Microsoft Access wikipedia , lookup

IMDb wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Oracle Database wikipedia , lookup

SQL wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

PL/SQL wikipedia , lookup

Ingres (database) wikipedia , lookup

Concurrency control wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Open Database Connectivity wikipedia , lookup

ContactPoint wikipedia , lookup

Versant Object Database wikipedia , lookup

Clusterpoint wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
1
CISC 3140 (CIS 20.2)
Design & Implementation of
Software Application II
Instructor : M. Meyer
Email Address:
[email protected]
Course Page:
http://www.sci.brooklyn.cuny.edu/~meyer/
CISC3140-Meyer-lec6
2
CISC3140-Meyer-lec6
Content
•
•
•
•
•
•
Connecting to a MySQL Database
Disconnecting from a MySQL Database
Error Checking
Executing SQL Statements
Useful Functions
Sample Code
3
CISC3140-Meyer-lec6
Using MySQL and PHP
• There are five things you want to be able to do from
within PHP in relation to a MySQL database
1.
2.
3.
4.
5.
Connect to the MySQL database
Disconnect from the MySQL database
Execute MySQL queries
Work with the results from an SQL query
Check the status of your MySQL commands
• Queries can be any kind of MySQL query, including
SELECT,UPDATE,INSERT, etc.
• Following SELECT queries, you can execute MySQL
/ PHP functions to put the data read from the
MySQL database into your PHP variables
4
CISC3140-Meyer-lec6
Connecting to a MySQL database
• Connecting to the database:
$conn = mysql_connect(
$mysql_host,
$mysql_user,
$mysql_password )
or die('Could not connect:'.mysql_error() );
print "Connected successfully";
mysql_select_db($mysql_db)
or die('Could not select database’);
• Replace the variables $mysql_host, $mysql_user,
$mysql_password and $mysql_db with strings
containing the values for your database
• Notice that there are two functions invoked
•
•
One that logs into MySQL: mysql_connect()
One that selects the database to use: mysql_select_db()
5
CISC3140-Meyer-lec6
On " or die() "
• According to the PHP manual die() is a
"language construct equivalent to exit()."
• die() can be called independently and used to
dump error information to the screen or to a file.
• "or die()" uses short circuit testing to call die IF
the statement preceding die returns false.
• Increasingly using "or die()" in production code
is seen as bad form and/or a security risk… thus
6
CISC3140-Meyer-lec6
PHP Exceptions
• PHP also support error handling in ways other
than die() including exceptions:
if ( !$result = mysql_query('SELECT foo FROM bar', $db) ) {
throw new Exception('You fail: ' . mysql_error($db));
}
• Placed within a try/catch block the code above
could recover "gracefully" from a db error.
• Feel free to use "or die()" in this class.
• See also: trigger_error()
7
CISC3140-Meyer-lec6
Disconnecting From the MySQL
Database
• Disconnect from MySQL database:
mysql_close( $conn );
8
CISC3140-Meyer-lec6
Check the Status of your MySQL
Commands
• If errors occur, the functions return errors
• These errors can be read as strings using:
mysql_error()
• Note the usage in this statement:
$conn = mysql_connect( $mysql_host,
$mysql_user,
$mysql_password)
or die('Could not connect:’.mysql_error());
echo 'Connected successfully‘;
9
CISC3140-Meyer-lec6
Execute MySQL Queries (SELECT)
// set up and execute the MySQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ‘.mysql_error());
// print the results as an HTML table
print "<table>\n";
while ($row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
echo "\t<tr>\n";
foreach ( $row as $item ) {
echo "\t\t<td>$item</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// free result
mysql_free_result( $result );
10
CISC3140-Meyer-lec6
Database Functions
Execute the query and store the result in a local variable:
mysql_query()
Parse the data read returned from the query as an array:
mysql_fetch_array()
Free the memory used by the query result:
mysql_free_result()
NOTE that if the result returned is a scalar and not an
array, then only mysql_query() needs to be called and
does not need to be followed by a call to
mysql_fetch_array(). Finally, note the use of
mysql_error() in the query function.
11
CISC3140-Meyer-lec6
Other Handy Functions
Here are a few of the more handy functions:
int mysql_num_rows ( $result )
Returns the number of rows contained in a $result; this is
relevant when the result returned from mysql_query() is
an array and not a scalar
int mysql_affected_rows ($conn)
This function returns the number of rows that were
affected by the most recently executed INSERT, UPDATE,
REPLACE or DELETE query (i.e. if the number of rows
you expected to be updated were actually updated)
12
CISC3140-Meyer-lec6
Even more handy functions
int mysql_insert_id ( $conn )
this function is used when inserting a row into a
table that has an AUTO_INCREMENT ID field;
the function returns the ID number that was
generated
string mysql_stat ( $conn )
This function returns a string containing
information about the status of the current
database connection
13
Sample Program
CISC3140-Meyer-lec6
<html>
<body>
<?php
$conn = mysql_connect("localhost",“username",”password”)
or die('Could not connect:'.mysql_error());
$db_found = mysql_select_db("pgrabowiec");
if ($db_found) {
$query = "SELECT thename FROM friends";
$result = mysql_query($query) or die('Query failed: '.mysql_error());
print "<table>\n";
while ($db_fields = mysql_fetch_assoc($result)) {
print "\t<tr><td>".$db_fields['thename']."</td></tr>“;
}
print "</table>\n";
}
else
print "Database not found";
mysql_close($conn);
?>
</body></html>
14
CISC3140-Meyer-lec6
You Can Do This!!!
• MySQL and PHP online documentation
• PHP Site
▫ http://www.php.net/manual/en/ref.mysql.php
• W3c-Schools
▫ http://www.w3schools.com/php/php_mysql_intro.asp
15
CISC3140-Meyer-lec6
Lab 4.0 – PHP & MySQL
• Available online
• Assumes you have completed the MySQL labs.
• Get started, if you can't finish it in class, then
finish it over the weekend.
• Hook the pages that you create to the index page
in your public_html folder.
• Check out the following site for help:
http://146.245.250.215/~mmeyer/classexamples.html