3 Pages

Section 6 - PHP and MySQL

Course: INFO 2300, Spring 2008
School: Cornell
Rating:
 
 
 
 
 

Word Count: 866

Document Preview

6: Section Using MySQL and PHP (2/29/08) phpMyAdmin: An Overview phpMyAdmin is a GUI front-end for administering MySQL databases via a web browser. We have phpMyAdmin installed on the 230 server; check it out at http://info230.cs.cornell.edu/phpMyAdmin. Your login information is the same as it is for the 230 site. All the common commands you might wish to run on a MySQL server can be run via phpMyAdmin. You can...

Register Now

Unformatted Document Excerpt

Coursehero >> New York >> Cornell >> INFO 2300

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
6: Section Using MySQL and PHP (2/29/08) phpMyAdmin: An Overview phpMyAdmin is a GUI front-end for administering MySQL databases via a web browser. We have phpMyAdmin installed on the 230 server; check it out at http://info230.cs.cornell.edu/phpMyAdmin. Your login information is the same as it is for the 230 site. All the common commands you might wish to run on a MySQL server can be run via phpMyAdmin. You can select databases with the pulldown at left, and then (when you've got >= 1 table in your database) select which table to work with by clicking on a link below the pulldown. Let's take a look at the top level navigation of phpMyAdmin: Structure: Lets you create and update tables in your database. Browse: Basically, a SELECT * on your table. SQL: A textarea where you can enter SQL commands, as in homework 1. Search: Run SELECT queries using a form interface for setting WHERE or LIKE clauses. Insert: Enter data into your table. Import: Upload a file full of SQL commands and run them all on the database. Export: Create backups of your database tables and their content as SQL statements. Empty: Remove all data from a given table. Drop: Delete the table (obviously also removes all its data). Operations: Ignore this for now. Designing a Simple Schema Together, we're all going to design a simple one-table schema to describe an entity. That entity is 'animals'. In addition to the primary key field, we need 2-4 other properties of animal. Things like num_legs (3), sound (meeeeow), and name (rhino) are good choices. Make sure you're comfortable writing the schema in the following format (* represents the primary key members): Animals (*aid: INT, name, num_legs, sound) Implementing the Schema in phpMyAdmin Using what you've learned about the Structure tab, go implement the section's Animals table using phpMyAdmin. Remember to set the animal ID field to 'auto increment' and to mark it as a primary key. Note that the SQL that phpMyAdmin is using to talk to MySQL is displayed after you hit submit. Next, head over to the Insert tab and convince yourself you can add data to your animals table. Try adding duplicate rows, or adding empty elements, and see what happens. Note that the SQL is again being output for you to see. Reviewing PHP MySQL Functions Connecting to a MySQL Database Okay, we're going to go ahead and create a PHP file that will connect to their brand new animals database and issue some queries to it. Have everyone follow along: $link = mysql_connect('localhost', 'myusername', 'mypassword'); if(!$link){ die('Error connecting to database, please refresh the page.'); } mysql_select_db('name_of_table', $link); Stress the security issues It's here. normally good practice to put your DB login info outside the webroot in a different file. On the 230 server, putting it outside the webroot is not really an option, so we'll have to settle for just putting it in a configuration file. Stress that's important not to do something like call your login include file `db_login.inc`. Although PHP will load the file just fine, `.inc` is not parsed by PHP normally. When someone views `db_login.inc` in their browser, they see your login info! //in password.php <? define(MYSQL_PASS, 'mypassword'); ?> //where password is needed <? require('password.php'); $link = mysql_connect('localhost', 'myusername', MYSQL_PASS); if(!$link){ die('Error connecting to database, please refresh the page.'); } mysql_select_db('info230_SP08_myusername', $link); ?> We'll leave the 'meat' of the application empty for now just to make sure the connection works. Let's make sure we go ahead and close the connection when we're finished. mysql_close(); SELECT Queries Of course, we can query the database for some information: $query = "SELECT * FROM Animals" ; $resource = mysql_query($query); while($animalsarray = mysql_fetch_array($resource, MYSQL_ASSOC)){ print("The $animalsarray['name'] says $animalsarray['sound']"); } You may want to `print_r($animalsarray)` to show what the array contains. It'd be useful to show the different fetch types too. ( mysql_fetch_array docs) INSERT/UPDATE/DELETE Commands And here's how we modify the database. You might want to show how mysql_query returns different things depending on if it's a SELECT or INSERT/UPDATE/DELETE. $query = "UPDATE Animals SET sound = '".$_POST['sound']."' WHERE aid = '".$_POST['aid']."'" ; mysql_query($query); Again, this is a good place to mention security. Doing the above in production code is **bad**. Always escape data, never interpolate _POST information, etc. Advanced / Other Information PHP's PDO Libraries Dean happens to be on a [PDO] kick lately, so he thinks it'd be cool to mention it in section. PDO is a database abstraction layer for PHP. It lets you easily connect to different database types (MySQL, SQLite, Postgres, etc) as well as giving you an OO interface to work with the results. You can do prepared statements, transactions and more all very nicely. You can even define PHP classes and have PDO automatically create instances of them from the results: class Animal { public $name; public $type; public $num_legs; } # elsewhere $stmt = $dbh->query('SELECT * FROM animals'); $animals = $stmt->fetchAll(PDO::FETCH_CLASS, 'Animal'); # animals is now an array of Animal objects!
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Cornell - INFO - 2300
Section this FridayDatabase design: ER diagramsINFO/COM S 230: Intermediate Web Design and Programming First part will be given to meeting with your final project team to talk about organization and finding a client. Second part will be given to
Cornell - ECON - 3330
Spring break awardsFarthest south: Farthest west: Farthest east: Farthest north: Least far: Most socially conscious:The 230 final projectINFO/COM S 230: Intermediate Web Design and ProgrammingInformation Science Open HouseDebuggingCameron an
Cornell - INFO - 2300
AjaxAjax uses instances of a special object XMLHttpRequest. Well defer for the moment how to get such an instance; suppose for now we have an instance ,request.Using `request' to call the serverrequest.open(&quot;GET&quot;, url, true); Prepares a request t
Cornell - INFO - 2300
Midterm infoJavaScript and the Document Object ModelINFO/COM S 230: Intermediate Web Design and ProgrammingTime: 7:30-9PM, Tuesday 3/11 Place: Olin 155 Format: On paper Closed book, closed notes However, you can bring a 4&quot;x6&quot; index card of notes y
Cornell - ECON - 3330
Portfolio Tools 2&quot;A bird in the hand is worth two in the bush&quot; Danthine and Donaldson, p. 83Econ 333 Spring 081Portfolio Tools 2: A brief revue of conceptsIn individual's attitude toward risk can be measured in two ways: The Arrow-Pratt meas
Cornell - ECON - 3330
Portfolio Tools 3Spring 08 Econ 3331Portfolio ToolsModern portfolio theory : Developed to help investors form a portfolio a combination of investments that achieves the highest possible expected return for a given level of risk. The theory as
Cornell - INFO - 2300
More SQLINFO/COM S 230: Intermediate Web Design and ProgrammingCommon problems with P2 Code didn't work Search functionality crippled (e.g. only search on two attributes) Navigation (no way to return to home page from search results) Error che
Cornell - INFO - 2300
LoginsINFO/COM S 230: Intermediate Web Design and ProgrammingPHP commands for MySQLMySQL commandsRecall from last time: mysql_connect(hostname, username, password); Returns a MySQL DB link if successful, false otherwise. mysql_select_db(dbname,
Cornell - INFO - 2300
Calling MySQL from PHPmysql_connect(hostname, username, password); Returns a MySQL DB link if successful, false otherwise. E.g. $link = mysql_connect(,localhost, ,dpwmson, ,mypassword); mysql_select_db(dbname, link); Selects DB dbname for use given
Cornell - INFO - 2300
Modifying DBs and using MySQLINFO/COM S 230: Intermediate Web Design and ProgrammingModifying databases via SQLINSERTsWe can INSERT tuples into a relation, UPDATE tuples, and DELETE tuples from a relation.INSERT INTO relation VALUES (value1, v
Cornell - ECON - 3330
Assessing the Firm's Viability from Its Financial Statements: A Study AidDuring the accounting cycle, the accountants track, organize and record the financial dealings of a company. At the close of each period, accountants use the information they h
Cornell - ECON - 3330
Factor Models and the Arbitrage Pricing TheoryEcon 333 Spring 081Factor Models and the Arbitrage Pricing TheoryOur goals: Be able to decompose the variance of an asset into market-related and non market-related components. i.e. common and fir
Cornell - ECON - 3330
Assets PricingEcon 333 Spring 081Assets pricingOur goals: Understand what the market portfolio is, what assumptions are needed for the market portfolio to be the tangency portfolio, i.e. for the Capital Asset pricing Model (CAPM) to hold. Und
Cornell - INFO - 2300
Project 1Introduction to JavaScriptINFO/COM S 230: Intermediate Web Design and Programming Regrades: Fill out form from server Meet with me Entire project will be regraded (e.g. grade could go up or down). Regrade must be within a week from t
Cornell - INFO - 2300
JavaScript vs. PHPLots of things in JavaScript are relatively similar to what weve already seen in PHP. Here is a very brief summary of some of the similarities and differences.VariablesNot prefixed by ,$ in JavaScript. Can declare by ,var when v
Cornell - INFO - 2300
PHP and MySQLINFO/COM S 230: Intermediate Web Design and ProgrammingReminderMidtermMarch 11 (Tuesday) 7:30-9PM Olin 155FinallyWe've studied two topicsToday they come together1Easy PDF Creator is professional software to create PDF. If y
Cornell - INFO - 2300
Cookies, Sessions, and FilesINFO/COM S 230: Intermediate Web Design and ProgrammingCookiesCookiesCookies are one way to save limited amounts of information between visits of a user.Saving a cookiesetcookie($name, $value) setcookie($name, $va
Cornell - ECON - 3330
Risk, Risk Aversion and Investment DecisionsEcon 333 Spring 081Risk, Risk Aversion and Investment Decisions After studying this sequence (next six chapters) you will know: How financial risk is defined and measured. How an investor's attitud
Cornell - ECON - 3330
Portfolio Tools 1Econ 333 Spring 081Portfolio Tools 1Before one turns to modeling asset pricing it is essential to understand the determinants of the demand for securities of various risk classes (Individuals demand securities (in exchange of
Cornell - ECON - 3330
Econ 333 - Financial Economics Spring 08 Practice Prelim II:Exercise 1: Multiple choice. (3 points each) 1- You recently purchased a stock that is expected to earn 12% in a booming economy, 8% in a normal economy and lose 5% in a recessionary econom
Cornell - ECON - 3330
Econ 333 - Financial Economics Spring 08 Practice Prelim IExercise 1: Multiple choice question. (25 points) 1- The time value of money concept can be defined as: a. b. c. today. d. e. the relationship of interest rate stated and amount paid. None of
Cornell - ILROB - 4710
districts like La Dfense in Paris and planned communities like Reston, Virginia, outside Washington, DC, are cases in point. The time is ripe for similar developments to spring up around other congested cities. A billion or two additional internation
Cornell - ECON - 3330
Second Order Stochastic Dominance Definition Suppose the random variables X and Y have support on [l, u]. Then X second-order stochastically dominates Y ifa aPr[X &gt; t]dt l lPr[Y &gt; t]dtfor all a. Results 1. If X first order stochastically domi
Cornell - H ADM - 476
HA 476 Midterm Review Key Objects: ThisWorkBook!1 Application o SendKeys (imitates keystrokes) o DisplayAlerts = True, False (ignores warning boxes) o ActiveCell: property o GetOpenFileName (opens browse files and gets name, but doesn't open) o Capti
Cornell - INFO - 2300
SectionRelational algebraINFO/COM S 230: Intermediate Web Design and Programming Friday's section (in part): How to install and configure Apache, PHP, and MySQL. You may want to bring your laptop.Brief review of relational DBsLast time we intro
Cornell - ILROB - 4710
Cornell University ILR School Professor WilliamsREFLECTIVE PAPER: SELF-ASSESSMENT and GOALS Monday, March 31, 2008 by 5pm (5-7 pages, double spaced pages, 1650 word limit.) For this assignment, you will analyze your strengths, weaknesses and style a
Cornell - INFO - 2300
What is.?Introduction to relational databasesINFO/COM S 230: Intermediate Web Design and Programming A database is a collection of related data. A database management system (DBMS, database system) is a piece of software used to manage a database e
Cornell - INFO - 2300
Exercise: A relational database schema for Cornell course registrationSuppose you are putting together a database that allows Cornell students to sign up for courses each semester. Give a sample relational database schema for this database. Give som
Cornell - INFO - 2300
&quot;Stand firm in your refusal to remain conscious during algebra. In real life, I assure you, there is no such thing as algebra.&quot; - Fran Lebowitz, Social StudiesSQL: Structured Query LanguageINFO/COM S 230: Intermediate Web Design and Programming&quot;
Cornell - INFO - 2300
Relational algebra operator overviewSelectionThe operator P applied to a relation returns all tuples for which the predicate (or condition) P is true. E.g.Length &gt; 150ProjectionThe operator A1,A2,.,Ak applied to a relation returns a relation wi
Cornell - INFO - 2300
From relational algebra to SQLSelectionC(R)SELECT * FROM R WHERE C; SELECT * FROM Movies WHERE Length &gt; 150;Length &gt; 150 (Movies)Conditions allowed in SQL: &lt;, &gt;, &lt;=, &gt;=, = (note not = =), &lt; &gt; (not equals) Can also take AND and OR of conditio
Cornell - ECON - 3330
Portfolio Tools 4Econ 333 Spring 081Portfolio Tools 4Our goals: Understand the importance of mean-standard deviation diagram and know how to locate within the diagram the efficient frontier of risky assets, the capital market line, the minimu
Cornell - INFO - 2300
A simple login formComplete the code below for a simple login form (login.php) that protects a single page. &lt;?php if (!isset($_POST[,username]) &amp; !isset($_POST[,password]) { ?&gt; &lt;h1&gt;Log in&lt;/h1&gt; &lt;form action=&quot;login.php&quot; method=&quot;post&quot;&gt; Username: &lt;input
Cornell - INFO - 2300
ReminderProject 3, part I due tonight at midnightUploading files and PHP graphicsINFO/COM S 230: Intermediate Web Design and ProgrammingMidterm infoTime: 7:30-9PM, Tuesday 3/11 Place: Olin 155 Format: On paper Closed book, closed notes However
Cornell - ILROB - 4710
GROUND RULES FOR COLLABORATIVE LAW PROCESS 1. 2. 3. 4. Attack the problems and concerns at hand, not each other. Avoid positions; rather, express yourself in terms of needs and interests and the outcomes you would like to achieve. Work for what you b
Cornell - ILROB - 4710
COLLABORATIVE LAW PARTICIPATION AGREEMENTI. PURPOSE_ and his/her attorney, _, and_ and his/her attorney, _, have chosen to use the principles of Collaborative Law to settle the issues arising from the dissolution of their marriage or domestic part
Cornell - ILROB - 4710
Cornell - ILROB - 4710
Warning Concerning Copyright Restrictions The copyright law of the United States (Title 17, United States Code) governs the making of photocopies or other reproductions of copyrighted material. Under certain conditions specified in the law, libraries
Cornell - ILROB - 4710
Cornell - ILROB - 4710
Warning Concerning Copyright Restrictions The copyright law of the United States (Title 17, United States Code) governs the making of photocopies or other reproductions of copyrighted material. Under certain conditions specified in the law, libraries
Cornell - ILROB - 4710
ILROB 471 Organizations and NegotiationProfessor Michele WilliamsAgenda Turn in Post-Negotiation Paper (upload a copy onto Blackboard!) In the News Integrative Bargaining (reviewed) Exercise Video Case and Debrief Wrap-up 2008 Michele Willi
Cornell - ILROB - 4710
ILROB 471 Organizations and NegotiationProfessor Michele WilliamsAgenda Getting to Yes Conflict Exercise El-Tek Discussion and Wrap-up 2007 Michele Williams. All Rights Reserved.Pilots Thwart Merger Plans 2007 Michele Williams. All Right
Cornell - ILROB - 4710
ILROB 471 Organizations and NegotiationProfessor Michele WilliamsAgenda Emotion, Power and Negotiation Style (The Coleman account ) Reflective Paper Assignment Amanda Dispute Discussion and Wrap-up Gender (next week) 2007 Michele Williams.
Cornell - ILROB - 4710
ILROB 471 Organizations and NegotiationProfessor WilliamsAgenda Distributive Tactics Negotiation Exercise (Used Car) Fishbowl Negotiation Break Auction Netscape Case Discussion Wrap-upFocusStrategy Distributive (fixed-pie) Integrative (
Cornell - ILROB - 4710
ILROB 471 Organizations and NegotiationProfessor Michele WilliamsAnnouncement: Sign out an IClickerAgenda In the News Negotiation Paradigms Psychological Biases Personal Experience Coffee Contract Double Negotiation Discussion Video and W
Cornell - ILROB - 4710
ILROB 471 Organizations and NegotiationProfessor WilliamsAgenda Ethics In the News Negotiation Preparation Break Negotiation Discussion and Wrap-up Post Negotiation Analytic PaperA Question of Ethics You see a sign on a vacation home,
Cornell - ILROB - 4710
ILROB 471 Organizations and NegotiationProfessor WilliamsProfessor Michele WilliamsTeaching Assistant:Chia-Ming Chan, cc489@cornell.eduAgenda Introduction and Overview Syllabus Break Negotiation Exercise Discussion Wrap-upWe negotiate
Cornell - ILROB - 4710
ILROB 471 Organizations and NegotiationProfessor Michele Williams 2008 Michele Williams. All Rights Reserved.Agenda Gender Dispute Resolution Frameworks Emotion Management Tool Kit Telepro Negotiation Discussion and Wrap-up Mediation in Ac
Cornell - ILROB - 4710
Berkeley - MATH - 16A
016A S2 Homework 1 SolutionJae-young Park September 2, 2007 0.1 *10 Use intervals to describe the real numbers satisfying the inequality x -1 and x &lt; 8. Solution You may change the expression little bit: -1 x &lt; 8, which is equivalent. Using inte
E. Michigan - PHYS - 221
E. Michigan - CHEM - 371
CHEM 371 Fall 2007 Professor Wilmes Exam 4 50 minutesName_ EMU ID#_ By signing below, I state that I agree to and will follow all aspects of the Student Conduct Code with regard to academic honesty: Signature__Instructions: This is a closed book
E. Michigan - CHEM - 372
E. Michigan - CHEM - 372
E. Michigan - CHEM - 372
E. Michigan - CHEM - 372
Penn State - ENGL - 015
LJ Palombo 10/15/07 Ms. Spanier To Party or Not to Party To live a healthy life, you must find a balance your free time. You should use some of your time for work and some for play. My preferred form of play would be to party. By party, I mean to go
Penn State - KINES - 061
LJ Palombo Target Heart Rate Training Zone : 121 181 bpmWorkout 1 20 minutes of cardio work (aerobics) Lower Body: (1 set, 10-12 reps) Leg Press - machine Leg Extension - machine Leg Curl - machine Lunge - dumbbell Upper Body: (1 sets, 8-10 reps)
Michigan - ENG - 125
Curtice 1 (I am sorry that I sent you the incorrect version, I saved these paper versions as Escuerdo4 and Escudero4 on my laptop and I think that this was an accident.) Mark Curtice English 125 section 56 Instructor Escudero This is a much better pa