* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download PHP and MySQL - University of Alabama
Microsoft Access wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Oracle Database wikipedia , lookup
Relational algebra wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Clusterpoint wikipedia , lookup
Database model wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Relational model wikipedia , lookup
SQL in higher level languages SQL in higher level languages Why do we want to use SQL in a higher level language? 1) Read in data from file, manipulate data before insert into relation Loop until the EOF read values from file – higher level code manipulate values with higher level code insert into relation values (SQL) End loop 2 Why cont’d 2) Compute results based on result from query e.g. generate a report Query database Compute results from query Print results 3) Provide a user interface (Web) for SQL if the current one is lacking Prompt user for query Send query to DBMS Receive results Display results to user 3 Must have: to do 1) must read in values into C/C++ variables then use those values to insert using SQL still need SQL statement to insert, select tuples to do 2) must be able to manipulate results from SQL query, but mismatch between C/C++/PHP and SQL sets versus one record at a time to do 3) need to accept queries from user - create SQL queries 4 To do this? Given the query: Select * From department, employee Where dno=dnumber and lname=?? What is needed? – Variables in which to place result, select condition (Host variables) – Processing of result table (cursors) – Data structure for communicating with DBS in case of errors (SQLCA) – What if we want to process any query typed in? (Dynamic SQL) – Also must connect to the DB, must connect to DBMS • connect :user_name identified by :user_pwd using :host_string; 5 To do this 1. Embedded SQL Precede each statement with EXEC SQL 2. Platform specific classes, interfaces Oracle’s OLE 3. Platform independent classes, interfaces JDBC 4. Programming language that controls a software application PHP 6 Embedded SQL Embedded SQL – not used much these days – basis for all others Precede each statement with EXEC SQL Embedded Select statement EXEC SQL Select [distinct] expr {, expr} into host_var {, host_var} From table_name [alias] {, table_name [alias]} [Where search_cond] [Group by col {, col}] [Having search_cond] Embedded SQL Only returns 1 value: EXEC SQL select lname, salary into :lname, :sal From employee Where ssn=123456789; If Returns multiple values: char emp_name[50][20]; int emp_number[50]; float salary[50]; EXEC SQL SELECT ENAME, EMPNO, SAL INTO :emp_name, :emp_number, :salary FROM EMP WHERE SAL > 1000; Embedded SQL EXEC SQL declare c1 cursor for Select essn, hours From WORKS_ON Where pno = :proj_id; EXEC SQL open c1; EXEC SQL fetch c1 into :essn_id, :hrs; while (sqlca.sqlcode == 0) // checks for EOT { cout << essn_id << “ “ << hrs << endl; EXEC SQL fetch c1 into :essn_id, :hrs; }; . 2. Platform specific classes, interfaces Oracle’s OLE a middleware product manufactured by Oracle Corporation that allows native access (no ODBC) to Oracle databases from client applications via Microsoft OLE (Object Linking and Embedding) and COM (Component Object Model) • Native Access to Oracle and only Oracle databases • Runs slightly faster than ODBC access • Some people feel it is VERY convenient OLE • Use OLE Classes • Example: execute SQL statements directly with the ExecuteSQL method. db.ExecuteSQL("insert into project values (:projectName, :projectNumber, :projectLocation, :departmentNumber)") OLE Using a cursor: ODynaset results(db, "Select * from employee"); cout << "salary" << endl; cout << "========" << endl; double salary; while (!results.IsEOF()) { if (results.GetFieldValue ("salary", &salary) == OFAILURE) { cout << db.GetServerErrorText() << endl; // example of character string // char first [10]; // results.GetFieldValue("fname", first, 10); } else { cout << salary << endl; results.MoveNext(); } } JDBC 3. Platform independent classes, interfaces JDBC 4. PHP (and MYSQL) PHP • Written as a set of CGI binaries in C in 1994 by R. Lerdorf – Didn’t just want to post his resume – Created PHP to display resume and collect data about page traffic, e.g. dynamic web pages – Personal Home Page tools publicly released 1995 – In 1998 became PHP: Hypertext Preprocessor PHP • Creates DYNAMIC web pages – HTML traditionally static – Contents regenerated every time visit or reload site • (e.g. can include current time) • PHP is a scripting language – a programming language that controls a software application (program is independent of any other application) – Strong at communicating with program components written in other languages • E.g. can embed PHP statements within HTML – Script like a dialogue for play interpreted by actors • PHP parser with web server and web browser, model similar to MS ASP.NET, Sun JavaServer Pages JSP PHP • Takes input from a file or stream containing text and PHP instructions • Outputs stream of data for display • PHP originally interpreted, not converted to binary executable files • PHP 4 – parser compiles input to produce bytecode (semi-compiled) – Zend engine (better performance than interpreted PHP 3) • PHP 5 – robust support for OO programming, better support for MySQL, support for SQLite, performance enhancements – – – SQLite – ACID compliant embedded relational DB contained in small C programming library. Source code in public domain. SQLite library is linked in and part of application program, uses simple function calls, reducing latency. Entire DB stored as a single file on a host machine. PHP 6 PHP 7 PHP - specifics • • • • • Delimiters: <?php ?> or just <? ?> PHP parses code within delimiters Code outside delimiter sent to output, not parsed Block comments /* */ Inline comments // # PHP vs. C++ • Similarities: – Requires semicolons after each statement ; – Types are nearly the same (booleans, integers, strings, etc.) – Syntax nearly the same (For/While/If) – Assignment is right to left ($num = 56;) – Object-Oriented (Class support, inheritance, virtuals, polymorphism) – Functions! PHP Versus C++ • Differences: – Variables begin with $ sign ($name = “John Doe”;) – No explicit declaration of variable types – Introduction of “lazy” functions (foreach, explode, mail) – No Function Overloading – “Hidden” functions-within-a-function – Compiled/interpreted during every page load – Documented! – Echo for output – Concatenate is dot . PHP Versus C++ • Web Specific: – Cookies and “Sessions” – Dynamic HTML based on user-defined logic – Interact and process a form’s action – Process URL Parameters – Easy Database Integration Sample code <?php // do not put a space between ? and php Echo “Hello CS457”; // can use either “ or ‘ ?> To run this, only need to specify a link to this program http://bama.ua.edu/~login/hello.php Example Easy Database Integration • For example: MySQL MySQL • MySQL is a relational DBMS • Has many of the same capabilities as traditional DBMSs (newest releases) • MySQL queries mostly the same as SQL in Oracle (subsidiary of Sun) • Popular for web databases • It’s freeware! MariaDB • open source – community maintenance GNU GPL • Fork of MySQL • High compatibility with MySQL • Developer (“Monty” Widenius) of MariaDB is founder of MySQL –sold it to Sun (bought by Oracle) for $1B • Maria is his daughter • You can connect to MySQL directly • OR • You can connect to MySQL through .php Connecting directly • You can use a tool to create tables, insert them into your DB, query tables, etc. • Possible tools: – Toad: http://www.quest.com/toad-for-mysql/ – phpmyadmin MySQL • Or you can use a command line • You must be able to connect to the machine hosting the MySQL DB MySQL • To use a command line • To start up MySQL type in: mysql –u yourlogin –D yourlogin_db –p [–h IP_address ] It will then prompt you for your password • You need to specify a db to use, that is the –D parameter above MySQL commands Can connect directly to MySQL: mysql> SHOW databases; mysql> USE db_name; // must specify this each time mysql> SHOW tables; mysql> DESCRIBE table_name; mysql> create table … mysql> insert into table values (… mysql> select * from table_name; mysql> delete … mysql> update • You can connect to MySQL directly • OR • You can connect to MySQL through .php, ruby on rails, etc. Some php mysql functions • Connecting to MySQL through PHP – Mysql_connect (“IP_address”, “login”, “pw”) – Mysql_select_db (‘name_db’, $link_id) – mysql_query (string [, resource $link_id]) • Executes a query, place result in variable, like a cursor • Resource specifies a connection, otherwise last connection opened used • Returns a special variable holding a reference to external resource – mysql_error ( ) • Returns error message from previous sql operation – mysql_fetch_array ($result, how) • Returns array corresponding to fetched row, moves pointer to next row • Traverses through cursor of query result • How is either mysql_assoc (use col. names) or mysql_num (use index number) or mysql_both – Mysql_num_fields ( $result) • Returns number of columns in table (fields in recordset) http://dk1.php.net/mysql_query PHP and MySQL – ex1 <?php $link=mysql_connect (“vrbsky-oracle.cs.ua.edu”, “login”, “pw”); mysql_select_db('svrbsky_db') or die('Cannot select database'); $query = 'CREATE TABLE testit( '. 'id INT NOT NULL, '. 'age int)'; $result = mysql_query($query, $link); if(!$result) {die( 'Error in SQL: ' . mysql_error());} echo "table created"; mysql_close($link); ?> • Example 1 Example ex2 <?php echo "Welcome to Vrbsky's DB"; // Connect to MySQL $link = mysql_connect(“vrbsky-oracle.cs.ua.edu", “login", “pw"); if (!$link) {die('Not connected: '. mysql_error()); } // see if connected // Select DB will use mysql_select_db('svrbsky') or die ('Could not select database'); // see if worked // Now the query $query = "Select * from testit"; // testit has 2 columns, id and age $result = mysql_query($query, $link); if (!$result) {die( 'Error in SQL: ' . mysql_error());} // process results using cursor while ($row = mysql_fetch_array($result)) { echo "<hr>"; //horizontal line echo "id: ". $row["id"] . "<br />"; echo "age: " . $row["age"] . "<br />"; } mysql_free_result ($result); mysql_close($link); // disconnecting from MySQL ?> Try example 2 Accessing result rows <?php $link=mysql_connect (“vrbsky-oracle.cs.ua.edu", “login", “pw"); mysql_select_db('svrbsky') or die('Cannot select database'); $query = "SELECT id, age FROM testit"; $result = mysql_query($query, $link); // Using an index while($row = mysql_fetch_array($result, MYSQL_NUM)) { echo “ID:{$row[0]} <br>" . “Age: {$row[1]} <br><br>"; } mysql_close($link); ?> Example using index values Forms and input • Can use HTML to create forms • Users can input values to use as host variables in calls to mysql HTML code • The following code uses a form to ask for input values to a table • When user inputs values, event (action) occurs and php code is executed • To use those values in php file, must use $_POST[‘var_name’] $_POST function <form method="post" action="example.php"> • variables from a form will be placed into $_POST – – – – – $_ POST is an associative array (key, value) Index into array is form data name Info sent from form POST is a superglobal variable, available in all scopes With POST no limits on the amount of info to send • Different from $_GET function where – Info sent is displayed in browser’s address bar – Max 100 characters HTML and PHP and MYSQL ex3.html <html> <head> </head> <center> <!- The following line results in php code executed after input values in form -> <form method="post" action="example3.php"> <table> <tr><td align="left">ID</td> <td><input type="text" name="id"></td> </tr> <tr><td align="left">Age</td> <td><input type="text" name="age" size="15"></td> </tr> <tr><colspan="2"> <p align="center"> <input type="submit" value="Enter record"> </td> </tr> </table> </form> </center> </html> PHP code • PHP code places values input from form into its own local variables • Connects to database • Inserts values into tables • Prints out values example3.php <?php // This is example3.php used in previous .htm code $link = mysql_connect(“vrbsky-oracle.cs.ua.edu", “login", “pw"); if (!$link) {die('Not connected: '. mysql_error()); } mysql_select_db('svrbsky') or die ('Could not select database'); //have 2 host variables $id= $_POST['id']; $age = $_POST['age']; //the query $query = "insert into testit values ('$id', '$age')"; $result = mysql_query($query); if (!$result) {die('SQL error: ' . mysql_error());} mysql_close($link); print "<html><body><center>"; print "<p>You have just entered this record<p>"; print "ID: $id<br>"; print "Age: $age"; print "</body></html>"; ?> • Example 3 • example 2 • Dynamic query Example HTML and PHP ex4.html <html> <body> <center> <form method="post" action="example4.php"> <!-- places values in associative array called $_POST --> <font size="18">Complete the Select Statement</font><br> Select <input type="text" name="select" size="60" value=" " ><br> <input type="submit" value="Get Query"></form> <table border="1"> </table></center></body></html> <?php //This is example4.php referenced in previous .html code $link = mysql_connect('vrbsky-oracle.cs.ua.edu', “login", “pw"); if(!$link) { die('Not connected: '.mysql_error);} mysql_select_db('test'); // isset tests if the value of the variable is set if(isset($_POST['select'])) { //$select = 'select '.$_POST['select']; //echo $select; //can have problems with col=.string., so must get rid of \.s inserted by php for mysql| $select = stripslashes('select '.$_POST['select']); echo $select; $result = mysql_query($select, $link); if(!$result) { echo mysql_error(); } else { while($row = mysql_fetch_array($result, MYSQL_NUM)) { echo "<hr>"; // horizontal line echo "<tr>"; for($count = 0; $count < 10; $count++) { if(isset($row[$count])) echo " <td>{$row[$count]}</td>"; if(!isset($row[$count]) && isset($row[++$count])) { echo "<td></td>"; $count--; } } echo "</tr>"; } } } ?> example4.php code segment There can be problems with col = ‘string’ so use stripslashes() $select = stripslashes(‘select’.$_POST[‘select’]); • http://bama.ua.edu/~svrbsky/ex4.html Our set up • You will use php on bama.ua.edu and MySQL on the vrbsky-oracle machine • The steps on the next slides tell you how to set up your bama account Our setup • You need to use SSH Secure Shell to connect to bama.ua.edu (I use ssh client from windows) • Use vim (or whatever) to create new PHP and HTML files • OR you can just edit files locally then use SSH file transfer to the bama.ua.edu machine First Step – to set up bama • The first step is to create your php and html files on bama but make sure you have done the following first: • Go to: “Change bama Shell” Web helper – Then Put your Username and Password and check the box, bash (Bourne Again shell)- it will enable you to do both SSH, Telnet, FTP – Then SSH/ Telnet to: bama.ua.edu and you can access the public_html – Copy or place your all your php and html files in public_html, e.g. Hello.php Test PHP on bama • Create your php and html files on bama: Create/save a .php file using an editor • Make sure the file is on the bama.ua.edu machine in the public_html directory • Sample program: <?php Echo “Hello World”; ?> • To run it, from a web browser, type in: http:// bama.ua.edu/~yourbamalogin/filename For example, I use: http://bama.ua.edu/~svrbsky/Hello.php html php 1 bama.ua.edu 4 3 2 MySQL Your DB vrbsky-oracle Running Examples • Next copy some of the programs from examples in these slides using php and mySQL and run them. • Make sure you change the login, password and database to yours • Make sure you create any needed tables for the examples. • Lots of great links on the web to get into • Disadvantage: How to determine what is error? • FYI: phpmyadmin is a great tool if you are interested • Need 2 files: – 1 for html 1 for php • You can test your SQL statements first using Toad (or whatever) For the assignment - insert tuples into your tables • You can use a tool to insert tuples into your tables • Possible tools: – Toad: http://www.quest.com/toad-for-mysql/ – Phpmyadmin • Or Write can PHP code to: – insert tuples into your tables/views