|
|
| Line 1: |
Line 1: |
| − | '''Path de los códigos:'''
| + | ~ Migrated |
| − | {{#vardefine:codespath|http://localhost/webdevelopment/}}
| |
| − | <syntaxhighlight lang="wiki">
| |
| − | Variable definida con:
| |
| − | {{#vardefine:codespath|http://localhost/webdevelopment/}}
| |
| − | | |
| − | Para usar la variable:
| |
| − | {{#var:codespath}}
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | <br/>
| |
| − | ==Web Applications==
| |
| − | A Web Applicaton is an application running on the Internet. Ex: Google, Facebook, Amazon, etc.
| |
| − | | |
| − | A WebApp is typically a 3-tier (or multi-tier) client-server database application run over the Internet .
| |
| − | | |
| − | Using simple '''HTML''' and '''CSS''' we can create static client Web Sites. Sin embargo, para crear páginas más avanzadas (WebApp) necesitamos otras tecnologías.
| |
| − | | |
| − | A WebApp generally comprises five components:
| |
| − | # '''Web Server (HTTP Server):'''
| |
| − | #* '''Apache HTTP Server''' (Compatible con PHP)
| |
| − | #* '''Apache Tomcat Server''' (Compatible con JSP (JavaServer Pages))
| |
| − | #* '''Microsoft Internet Information Server (IIS)''' (Compatible con ASP.Net)
| |
| − | #* Nginx
| |
| − | #* Google Web Server (GWS)
| |
| − | #:
| |
| − | # '''HTTP Client (or Web Browser):'''
| |
| − | #* Internet Explorer (MSIE), FireFox, Chrome, Safari.
| |
| − | #:
| |
| − | # '''Database (Un serveur de base de données):'''
| |
| − | #* '''MySQL''' (mysql-server):
| |
| − | #:* Open source, free
| |
| − | #:* OS: Windows, Mac OS, Linux OS
| |
| − | #:* Web Server: Apache Http, IIS amongst others
| |
| − | #:
| |
| − | #* '''Oracle:'''
| |
| − | #:* Commercial Licence required
| |
| − | #:* OS: Windows, Mac OS, Linux OS
| |
| − | #:* Web Server: Apache Http, IIS amongst others
| |
| − | #:
| |
| − | #* '''MSSQL (Microsoft SQL Server):'''
| |
| − | #:* Commercial Licence required
| |
| − | #:* OS: windows, (recently linux version)
| |
| − | #:* Web server: IIS
| |
| − | #:
| |
| − | #* '''Other open-sources:''' Apache Derby, mSQL, SQLite, PostgreSQL, OpenOffice's Base.
| |
| − | #* '''Other Commercials:''' IBM DB2, SAP SyBase, MS Access.
| |
| − | #:
| |
| − | # '''Client-Side Programs:'''
| |
| − | #* '''HTML'''
| |
| − | #* '''CSS'''
| |
| − | #* JavaScript, VBScript, Flash.
| |
| − | #:
| |
| − | # '''Server-Side Programs:'''
| |
| − | #* '''PHP:''' Platform independent (Windows, Linux, Mac OS)
| |
| − | #* '''Java Servlet/JSP:''' Platform independent (Windows, Linux, Mac OS)
| |
| − | #* '''ASP.NET''' (Windows only (as IIS proprietary to windows))
| |
| − | #* '''Othre thecnologies:''' Perl, Python, CGI.
| |
| − | | |
| − | | |
| − | <br/>
| |
| − | ===Wireframe===
| |
| − | Algunas aplicaciones para hacer wireframes y otros tipos de gráficos/charts:
| |
| − | * https://www.lucidchart.com: Esta me pareció excelente. La versión gratis no está mal. Permite realizar muchos tipos de gráficos.
| |
| − | * https://www.draw.io/: Esta es la que he usado para relizar diagramas en Bases de datos. Permite relizar muchos tipo de gráficos.
| |
| − | * https://wireframe.cc: Esta es sólo para wireframes. No tiene muchas funciones.
| |
| − | | |
| − | | |
| − | <br/>
| |
| − | | |
| − | ===Some fundamental concepts===
| |
| − | | |
| − | | |
| − | <br/>
| |
| − | ====URLs====
| |
| − | URL stands for Uniform Resource Locator. It is generally the address we use to locate files/resources on the web.
| |
| − | | |
| − | An example of a URL is: http://www.example.com/directory-name/file.php
| |
| − | * http - this is the protocol we are using
| |
| − | * www.example.com - This is the domain addresss (port 80 assumed) (we could also enter www.example.com:80)
| |
| − | * directory-name - Path to file (or resource)
| |
| − | * index.php this is the file we are requesting
| |
| − | | |
| − | | |
| − | <br/>
| |
| − | | |
| − | ==Document Object Model (DOM)==
| |
| − | The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
| |
| − | | |
| − | When a web page is shown in the browser, each of the different elements e.g. Input Field, Text Field, Radio Buttons etc are all considered "Elements". Each of these different elements are added to a Tree type structure called the Document Object Model (DOM).
| |
| − | | |
| − | Think about the web page being the root of the tree and each of the elements added to the tree are different branches coming off the tree. Each of the elements has different attributes such as the name, id, value.
| |
| − | | |
| − | Considere el siguiente código html:
| |
| − | <syntaxhighlight lang="html">
| |
| − | <html>
| |
| − | <head>
| |
| − | <title>My Title</title>
| |
| − | </head>
| |
| − | <body>
| |
| − | <h1>My Header</h1>
| |
| − | <a href='www.google.com'>my link</a>
| |
| − | <div>
| |
| − | <p>this is a paragraph</p>
| |
| − | </div>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | The DOM defines a structure like this:
| |
| − | [[File:dom1.png|650px|thumb|center|DOM structure]]
| |
| − | | |
| − | There is a parent/child relationship between elements:
| |
| − | * <nowiki><h1></nowiki> is said to be a child of the <nowiki><body></nowiki> element
| |
| − | * <nowiki><body></nowiki> is a parent of the <nowiki><h1></nowiki> element
| |
| − | | |
| − | ==HTML==
| |
| − | '''HyperText Markup Language (HTML)''' is the standard markup language for creating web pages and web applications. With Cascading Style Sheets (CSS), and JavaScript, it forms a triad of cornerstone technologies for the World Wide Web. Web browsers receive HTML documents from a webserver or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document. https://en.wikipedia.org/wiki/HTML
| |
| − | | |
| − | HTML can embed programs written in a scripting language such as JavaScript which affect the behavior and content of web pages. Inclusion of CSS defines the look and layout of content. The World Wide Web Consortium (W3C), maintainer of both the HTML and the CSS standards, has encouraged the use of CSS over explicit presentational HTML since 1997. https://en.wikipedia.org/wiki/HTML
| |
| − | | |
| − | ===Validations===
| |
| − | * We want to get the right data, in the right format — our applications won't work properly if our user's data is stored in any old format they like, or if they don't enter the correct information in the correct places, or omit it altogether.
| |
| − | * We want to protect our users — if they entered really easy passwords, or no password at all, then malicious users could easily get into their accounts and steal their data.
| |
| − | * We want to protect ourselves — there are many ways that malicious users can misuse unprotected forms to damage the application they are part of
| |
| − | | |
| − | Validation comes in three forms:
| |
| − | * '''HTML5''' - put directly in the form - '''client side'''
| |
| − | * '''JavaScript''' - This is done on the - '''client side'''
| |
| − | * '''PHP''' - This validation is done on the '''server side'''
| |
| − | | |
| − | Client-side validation occurs in the browser, before the data has been submitted to the server. Client Side Validation is more user-friendly and efficient than server-side validation(validation performed by PHP on the client site) as it gives an instant response (it can enhance the user experience by informing the user as to formatting errors and what is expected).
| |
| − | | |
| − | However, client site validation is very easy to hack, as it resides on the client side. People can easily manipulate the JavaScript. Why? Because code can be copied and changed. For example, remove all javascript validation but keeping the form. Then inputting malicious data to the form.
| |
| − | | |
| − | Client side validation is more about creating a better user experience by informing the user as to errors and how to correct them before moving to the server for processing.
| |
| − | | |
| − | Server-side validation is validation that occurs on the server, after the data has been submitted e.g. by a form 'post'. Server-side code is used to validate the data before it is put into the database.
| |
| − | | |
| − | Server-side validation is not as user-friendly as client-side validation, as it requires a round trip to the server, but it is essential — it is your application's last line of defense against bad (meaning incorrect, or even malicious) data.
| |
| − | | |
| − | In other words if we’ve set up our web server security properly it’s difficult for anyone to '''Get At''' the php code and manipulate the server side validation.
| |
| − | | |
| − | ===HTML5 Form validations===
| |
| − | Built in form validation is done with HTML5 form validation features. This way of validations has better performance that JavaScript validations, but it is not as customizable. JavaScript is completely customizable.
| |
| − | | |
| − | /var/www/html/webdevelopment/lecture9-CSValidation/CSValidationForm.php
| |
| − | <syntaxhighlight lang="php">
| |
| − | <!DOCTYPE>
| |
| − | <html>
| |
| − | <head>
| |
| − | </head>
| |
| − | <body>
| |
| − | <form action='cvform.php' method='post'>
| |
| − | <!-- The «required» attribute essentially checks if the field is not blank -->
| |
| − | <!-- We can add minlength/maxlength attributes (min/max number of characters) to a «text» input field -->
| |
| − | Username <input type='text' name='username' required minlength='3' maxlength='40'/><br>
| |
| − | <!-- We can add min/max attributes (minimum/maximum value) to a «number» input field -->
| |
| − | Age <input type='number' name='age' required min='18' max='35'/><br>
| |
| − | Telephone <input type='text' name='tel' required/><br>
| |
| − | <!-- We can add an input types such as «email» -->
| |
| − | Email <input type='email' name='email' required><br>
| |
| − | Date <input type='date' name='date' required><br>
| |
| − | <input type='submit'/>
| |
| − | </form>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | ===Why is client side validation only not sufficient?===
| |
| − | Let's look at our web page and do a view source. Para ver el código fuente de una página web basta con solocar la orden '''view-source:''' antes de la dirección de la página:
| |
| − | | |
| − | <syntaxhighlight lang="php">
| |
| − | view-source:http://localhost/webdevelopment/lecture9-CSValidation/cvform.php
| |
| − | | |
| − | view-source:https://www.facebook.com/
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | '''Remember what we are seeing in our browser is the 'executed' code from our php file.''' In our case when we request the php file from the web server we are seeing a combination of the:
| |
| − | * html text, and
| |
| − | * text output from the 'executed' php code.
| |
| − | This is why we don't see any php code when we do a '''view-source''' in the browser.
| |
| − | | |
| − | But we can see the HTML and JavaScript code. So, we can take a copy of this web page and remove all the validation and then submit the original web page form without any validation:
| |
| − | | |
| − | [[File:Breaking_client_side_validation.png|650px|thumb|center|Breaking client side validation]]
| |
| − | | |
| − | ==CSS==
| |
| − | ===Colores===
| |
| − | '''Meilleurs Générateurs de Palette de Couleur:'''
| |
| − | | |
| − | http://htmlcolorcodes.com/fr/ressources/meilleurs-generateurs-de-palette-de-couleur/
| |
| − | | |
| − | : https://color.adobe.com/create/color-wheel/?base=2&rule=Analogous&selected=0&name=My%20Color%20Theme&mode=rgb&rgbvalues=0.8483762931332555,1,0.3951068113728652,0.87,0.5611135766500768,0.04350000000000004,1,0,0,0.338027436008127,0.04550000000000004,0.91,0.6646886641632195,0.9457528844018331,1&swatchOrder=0,1,2,3,4
| |
| − | | |
| − | | |
| − | ==Authorization and Authentication==
| |
| − | Say you are going to a football match... '''Authentication''' could be thought of as the process of presenting your ticket to the security staff. if you have a valid ticket you are let into the stadium. '''Authorization''' could the be thought of as which regions of the stadium am I allowed into w.g. terrace, stand etc.
| |
| − | | |
| − | ===Authentication===
| |
| − | * '''What tools do we have to authenticate users:'''
| |
| − | ** Database, we store user details in a database so we can verify them as valid users later at login
| |
| − | | |
| − | * '''Process:'''
| |
| − | ** Allow users to register with our site and store their details
| |
| − | ** When users logs in they are verified against registration details
| |
| − | ** '''Security:''' How can we make this process more secure:
| |
| − | *** '''Encrypt any passwords''' (in php) before storing to database.
| |
| − | *** Ensure passwords are not too simple ('''using validation''')
| |
| − | *** We can add a '''Captcha''' to a registration file to eliminate the use of robots registering on your form
| |
| − | | |
| − | ===Authorization===
| |
| − | How do we make sure an Authenticated user has access to certain areas of the application:
| |
| − | * We can use '''Sessions: ''' Once a user has logged in and has been authenticated we can use sessions to keep track of data between pages.
| |
| − | ** Sessions mean we can pass data around an application without having to go back to the database constantly.
| |
| − | ** Without sessions it would be difficult to maintain state i.e. who is logged in, what their user_type is, user name etc.
| |
| − | | |
| − | ====Example====
| |
| − | * We're going to write a simple application that allows a user to login in to a form.
| |
| − | * The method the form uses is a POST.
| |
| − | * Once we have submitted the form we will captute the form data in some session variables using the global array variable '''$_SESSION'''
| |
| − | * We will then redirect to a confirm page. Which will display the session data.
| |
| − | * We will add a href link to allow the user to '''logout''' of the sesssion and redirect to the login page.
| |
| − | | |
| − | /var/www/html/webdevelopment/lecture11/login.php
| |
| − | <syntaxhighlight lang="php">
| |
| − | <?php
| |
| − | | |
| − | session_start();
| |
| − | | |
| − | if($_POST){
| |
| − | $_SESSION['username'] = $_POST['username'];
| |
| − | $_SESSION['email'] = $_POST['email'];
| |
| − | header('Location: confirm.php');
| |
| − | }
| |
| − | | |
| − | | |
| − | ?>
| |
| − | | |
| − | <!DOCTYPE html>
| |
| − | | |
| − | <html>
| |
| − | | |
| − | <body>
| |
| − | <form action="login.php" method="POST">
| |
| − | Username: <input type='text' name='username'></input>
| |
| − | Email: <input type='text' name='email' required></input>
| |
| − | <input type='submit'></input>
| |
| − | </form>
| |
| − | </body>
| |
| − | </html>
| |
| − | | |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | /var/www/html/webdevelopment/lecture11/confirm.php
| |
| − | <syntaxhighlight lang="php">
| |
| − | <?php
| |
| − | | |
| − | session_start();
| |
| − | | |
| − | if(isset($_SESSION['username'])){
| |
| − | echo '<br/>Username: '.$_SESSION['username'];
| |
| − | echo '<br/>Email: '.$_SESSION['email'].'<br/>';
| |
| − | }else{
| |
| − | header('Location: login.php');
| |
| − | exit();
| |
| − | }
| |
| − | | |
| − | ?>
| |
| − | | |
| − | <!DOCTYPE html>
| |
| − | <html>
| |
| − | <body>
| |
| − | <a href='logout.php'>Logout</a>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | With '''logout.php''' we want to '''destroy the Session''' we have created and return to the login page, removing all the session variables. This is very importan to prevent an unauthorized user to access pages that were authorized based on the session variables.
| |
| − | | |
| − | /var/www/html/webdevelopment/lecture11/logout.php
| |
| − | <syntaxhighlight lang="php">
| |
| − | <?php
| |
| − | | |
| − | session_start();
| |
| − | session_unset();
| |
| − | session_destroy();
| |
| − | header('Location: login.php');
| |
| − | | |
| − | ?>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | logout.php
| |
| − | To prove that the session has been destroyed, once logged out try and bringup the confirm.php file in the browser. You should immediately be redirected back to the login page as the $_SESSION[‘username’] should no longer be set.
| |
| − | | |
| − | ==Transfer data from one php file to another==
| |
| − | * Using sessions
| |
| − | * Form POST and GET via the $_POST and $_GET global variables
| |
| − | * Passing parameters in a href link <nowiki>(<a href="xyz.php?id=1">link</a>)</nowiki> then use $_GET to retreive parameter id
| |
| − | * Cookies, similar to sessions but less secure.
| |
| − | | |
| − | ==Ejemplo 1: Forms - POST and GET requests - $_SERVER - Sessions==
| |
| − | <span style="background:#00FF00"> 10 CSS HTML Form Designs (Exelente página)</span> https://www.sanwebe.com/2014/08/css-html-forms-designs
| |
| − | | |
| − | En este ejemplo vamos a abordar:
| |
| − | * '''Forms'''
| |
| − | * '''POST and GET requests'''
| |
| − | * '''The PHP global variable $_SERVER'''
| |
| − | * '''Sessions'''
| |
| − | * ''' The PHP «header» function
| |
| − | | |
| − | To create a simple html page:
| |
| − | <syntaxhighlight lang="html">
| |
| − | <!DOCTYPE html>
| |
| − | <html>
| |
| − | <head>
| |
| − | </head>
| |
| − | <body>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | Save as '''1form1.php''' in:
| |
| − | * '''The htdocs''' folder (if using XAMPP)
| |
| − | * '''/var/www/html/''' (if using LAMP on Ubuntu)
| |
| − | | |
| − | En nuestro caso:
| |
| − | * '''/var/www/html/webdevelopment/ejemplo1/1form1.php'''
| |
| − | * '''{{#var:codespath}}ejemplo1/1form1.php'''
| |
| − | | |
| − | | |
| − | '''Forms:'''
| |
| − | | |
| − | Forms allow the user of a website to enter in some information to your website.
| |
| − | | |
| − | All websites use forms in some way, or use elements from forms for different purposes: Registration form, airline booking etc.
| |
| − | | |
| − | In this example, we are going to create an application that posts some '''«form» data''' to a separate ''php'' file on submission.
| |
| − | | |
| − | Add the form to your web page, between the '''<body>''' and '''</body>''' tags:
| |
| − | | |
| − | <syntaxhighlight lang="html">
| |
| − | <!DOCTYPE html>
| |
| − | <html>
| |
| − | <head>
| |
| − | </head>
| |
| − | <body>
| |
| − | <form>
| |
| − | <!-- Form code -->
| |
| − | </form>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | {{#var:codespath}}ejemplo1/1form1.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <!DOCTYPE html>
| |
| − | | |
| − | <html>
| |
| − | | |
| − | <head>
| |
| − | <link rel="stylesheet" href="style.css">
| |
| − | </head>
| |
| − | | |
| − | <body>
| |
| − | <!-- Lo siguiente es equivalente a escribir el texto directamente, a continuaci'on lo colocamos
| |
| − | en un PHP code a manera de ilustraci'on -->
| |
| − | <?php echo 'Our first Form example'; ?>
| |
| − | <h2>Form Enter</h2>
| |
| − | <!-- Ejemplo 1 en el archivo 1form_posted.php (Request via POst) - Descomente la siguiente l'inea: -->
| |
| − | <form class='form-style-1' action="1form_posted.php" method="POST">
| |
| − | <!-- Ejemplo 2 en el archivo 1form_posted.php (Request via GET) - Descomente la siguiente l'inea:
| |
| − | Note que a trav'es de una request via GET, las variables se despliegan en la barra de
| |
| − | direcci'on del navegador web. -->
| |
| − | <!-- <form class='form-style-1' action="1form_posted.php" method="GET"> -->
| |
| − | | |
| − | <label>First Name</label>
| |
| − | <input type='text' name='firstname' required></input>
| |
| − | | |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | Password
| |
| − | <input type='password' name='password'/>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <!-- Notice that in this case (type='radio') both of the names are set to the same name, this is
| |
| − | because we want to treat both of these options as part of the same group. En otras palabras, la
| |
| − | variable asociada a este elemento ser'a gener y valor de dicha variable puede ser 'Male' or 'Female' -->
| |
| − | <input type='radio' name='gender' value='Male'>Male</input>
| |
| − | <input type='radio' name='gender' value='Female'>Female</input>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <!-- Note que en el caso de un checkbox el name debe ser definido como un Array[] debido a que en el
| |
| − | checkbox se puede seleccionar m'as de un valor. So, si el usuario selecciona 'Car' y 'Bike', el valor
| |
| − | de la variable ser'a vehicle['Car','Bike'] -->
| |
| − | <input type='checkbox' name='vehicle[]' value='Car'>I have a Car</input>
| |
| − | <input type='checkbox' name='vehicle[]' value='Bike'>I have a Bike</input>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <select name='cartype'>
| |
| − | <option value='Mini'>Mini</option>
| |
| − | <option value='Volvo'>Volvo</option>
| |
| − | <option value='BMW'>BMW</option>
| |
| − | <option value='Saab'>Saab</option>
| |
| − | <option value='Ford'>Ford</option>
| |
| − | </select>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <textarea name="sometext" rows='4' cols='40'>Web develpment</textarea>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <input class='button' type='submit'></input>
| |
| − | </form>
| |
| − | <!-- Ejemplo 3 en el archivo 1form_posted.php (Request via GET fuera del la </form>)
| |
| − | Descomente la siguiente l'inea:
| |
| − | Note como puede ser transmitida una variable, en este ejemplo id=25 -->
| |
| − | <a href="1form_posted.php?id=25" method="GET">Get Request</a>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | Create a new php program in the same folder as called '''1form_posted.php'''
| |
| − | | |
| − | {{#var:codespath}}ejemplo1/1form_posted.php
| |
| − | <syntaxhighlight lang="php">
| |
| − | <?php
| |
| − | | |
| − | | |
| − | // print_r($_SERVER);
| |
| − | | |
| − | | |
| − | // // Ejemplo 1 - Request via POST - Hemos tambi'en colocado un if para eque el
| |
| − | // // programa compruebe que la request viene via POST
| |
| − | if ($_SERVER['REQUEST_METHOD'] == 'POST'){
| |
| − | // Todos los valores ingresados en la form se almacenan en la variable $_POST
| |
| − | print_r($_POST);
| |
| − | | |
| − | // "<br/>" introduce un salto de l'inea
| |
| − | echo "<br/>"."First Name: ".$_POST['firstname'];
| |
| − | echo "<br/>"."Gender: ".$_POST['gender'];
| |
| − | echo "<br/>"."Car: ".$_POST['cartype'];
| |
| − | echo "<br/>"."Text: ".$_POST['sometext'];
| |
| − | | |
| − | // Como $vehicle es un Array[] (ver explicaci'on en 1form1.php) debemos realizar un
| |
| − | // loop para imprimir los valores almacenados en la variable $vehible:
| |
| − | $vehicles = $_POST['vehicle'];
| |
| − | foreach ($vehicles as $value)
| |
| − | echo "<br/>Vehicle: ".$value;
| |
| − | | |
| − | echo "<br/>"."Password: ".$_POST['password'];
| |
| − | echo "<br/>";
| |
| − | echo "<br/>";
| |
| − | }
| |
| − | else{
| |
| − | echo "<br/>"."Bad Request , must come via POST";
| |
| − | }
| |
| − | | |
| − | | |
| − | // // Ejemplo 2 - Request via GET - Descomente la l'inea «method="GET"» en el archivo 1form1.php para este ejemplo.
| |
| − | // // Note que a trav'es de una request via GET, las variables se despliegan en la barra de direcci'on del navegador web.
| |
| − | // echo "<br/>"."First Name: ".$_GET['firstname'];
| |
| − | // echo "<br/>"."Gender: ".$_GET['gender'];
| |
| − | // echo "<br/>"."Car: ".$_GET['cartype'];
| |
| − | // echo "<br/>"."Text: ".$_GET['sometext'];
| |
| − | | |
| − | // $vehicles = $_GET['vehicle'];
| |
| − | // foreach ($vehicles as $value)
| |
| − |
| |
| − | // echo "<br/>Vehicle: ".$value;
| |
| − | // echo "<br/>"."Password: ".$_GET['password'];
| |
| − | | |
| − | | |
| − | // // Ejemplo 3 - Request via GET fuera del la </form>
| |
| − | // // Note como puede ser transmitida una variable, en este ejemplo id=25
| |
| − | // if ($_SERVER['REQUEST_METHOD'] == 'GET') {
| |
| − | // echo "<br/>".$_GET['id'];
| |
| − | // echo "<br/>"; // line break
| |
| − | // }
| |
| − | | |
| − | ?>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | '''Cuando ingresamos la «form» debemos definir tres parámetros:'''
| |
| − | <syntaxhighlight lang="html">
| |
| − | <form class='form-style-1' action="1form_posted.php" method="POST">
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | # class='form-style-1'
| |
| − | # action="1form_posted.php" - Este parámetro define el archivo «.php» que procesará la información ingresada en la «form». Puede ser el mismo archivo en donde se encuentra la «form» u otro archivo.
| |
| − | # '''The Http Request Methods:''' Http has a number of methods for sending a http request. We will look specifically a the '''GET''' and '''POST''' methods.
| |
| − | #* method="GET"
| |
| − | #* method="POST"
| |
| − | | |
| − | '''GET or POST request:'''
| |
| − | | |
| − | En {{#var:codespath}}ejemplo1/1form1.php la información ingresada en la «form» será enviada y procesada en el archivo {{#var:codespath}}ejemplo1/1form_posted.php
| |
| − | | |
| − | En {{#var:codespath}}ejemplo1/1form_posted.php hemos abordado varios ejemplos para entender los métodos ('''GET''' or '''POST''').
| |
| − | | |
| − | Cabe destacar que si usamos '''«method="GET"»''', cuando hacemos «submit», se mostrarán en la «Address bar del Web browser» todos los valores ingresados en la «form» (incluyendo el password). Para evitar esto, debemos cambiar a '''«method="POST"»'''.
| |
| − | | |
| − | :: '''HTTP GET Request:'''
| |
| − | :: Here are few things to note while using GET method :
| |
| − | ::* The principal problem with HTML GET method is that the values sent to the server are visible over the browser address bar, therefore sending sensitive data such as passwords, secret keys using GET method is not advisable.
| |
| − | ::* Amount of data can be sent using this method is limited to the length of characters allowed in URL by different browsers.
| |
| − | ::* GET parameters remain in browser history because they are part of the URL
| |
| − | ::* GET requests can be bookmarked.
| |
| − | ::* GET requests should never be used when dealing with sensitive data
| |
| − | ::* GET requests have length restrictions
| |
| − | ::* GET requests should be used only to retrieve data
| |
| − | | |
| − | :: Good technique and standards requirements say that you never use GET for an operation that has "side effects," or that actually does something. For example, we’re just looking at data, so no side effects affect the operation. But, ultimately, we're going to add the data to the database, which is, by definition, a side effect.
| |
| − | | |
| − | :: So the preferred way of sending data to server has been the POST method.
| |
| − | | |
| − | ::: '''URLs With Parameters:'''
| |
| − | :::* Parameters can be passed with a URL request and then accessed in to calling program or service. Parameters are key/value pairs.
| |
| − | :::* Parameter list begins with '''?''' and are separated by '''&'''
| |
| − | :::* http://localhost/webdevelopment/ejemplo1/1form_posted.php?firstname=Adelo&password=0930923403&gender=Male&vehicle%5B%5D=Car&vehicle%5B%5D=Bike&cartype=BMW&sometext=Web+develpment
| |
| − | | |
| − | :: '''HTML POST request:'''
| |
| − | :: POST method works similar way as GET, but it is safer than GET because the values are not visible on the address bar and will not be stored in browser history.
| |
| − | | |
| − | :: Benefits of using POST method:
| |
| − | ::* POST requests are never cached
| |
| − | ::* POST requests do not remain in the browser history
| |
| − | ::* POST requests cannot be bookmarked
| |
| − | ::* POST requests have no restrictions on data length
| |
| − | ::* POST variable are not included in url address
| |
| − | | |
| − | | |
| − | : '''PHP $_GET & $_POST variables:'''
| |
| − | : PHP $_GET & $_POST are part of PHP global variables, and can be called anywhere in PHP scripts, both $_GET & $_POST captures data sent with HTML post and get methods.
| |
| − | | |
| − | : Cuando enviamos la request, los valores ingresados en la «form» serán almacenados en la variable '''$_GET''' o '''$_POST'''. Luego podremos recuperar los valores como se hizo en 1form_posted.php:
| |
| − | | |
| − | | |
| − | '''Each form has a number of different forms elements (tags) that can be added:'''
| |
| − | * '''Input field:''' <input>
| |
| − | ** '''Text input:''' <input type='text'
| |
| − | ** '''password input:''' <input type='password'
| |
| − | ** '''Radio Button:''' <input type='radio'
| |
| − | ** '''Checkbox:''' <input type='checkbox'
| |
| − | * '''Select Menu'''
| |
| − | * '''Text Area'''
| |
| − | * '''Submit Button'''
| |
| − | | |
| − | En cada elemento (tag) podemos definir ciertas opciones. Por ejemplo:
| |
| − | * '''name='nombre''''
| |
| − | * '''value='valor''''
| |
| − | *'''required'''
| |
| − | | |
| − | <span style="background:#00FF00"> Para una lista completa de los elementos '''(tags)''' que pueden ser definidos en una «form» y de todos los elementos que pueden ser definidos en un archivo '''HTML''' acuda a:</span> https://www.w3schools.com/tags/
| |
| − | | |
| − | Note que la importanciá de definir correctamente las opciones (campos) de cada elemento radica en el hecho de que cada elemento en la '''«form»''' estará asociado con una variable que será probablemente utilizada en el código '''«php»'''. De ahí la importancia de asociar un '''«name»''' y, en muchos casos, un '''«value»''' al elemento (variable).
| |
| − | | |
| − | | |
| − | '''The PHP global variable $_SERVER:'''
| |
| − | | |
| − | '''$_SERVER''' is an associative array which contains a bunch of information about the http request that has been made.
| |
| − | | |
| − | En el Ejemplo 1 de {{#var:codespath}}ejemplo1/1form_posted.php we have put some checking (if) to ensure it cannot be run outside of a '''«POST form action»'''. To do so, we use a PHP global variable '''$_SERVER'''
| |
| − | | |
| − | We are in particular interested in the value of the element '''«REQUEST_METHOD»''' which tells us if the form action was a '''GET''' or '''POST''' (or something else).
| |
| − | | |
| − | To see all elements of the '''$_SERVER''' variable we can use the '''print_r()''' function which allows us to view the contents of an array.
| |
| − | | |
| − | En el ejemplo mostrado en {{#var:codespath}}ejemplo1/1form_posted.php: If the value of '''$_SERVER['REQUEST_METHOD'] != "POST"''', then we flag an error and not continue executing.
| |
| − | | |
| − | | |
| − | '''Request en el mismo archivo:'''
| |
| − | | |
| − | Ahora, podría ser conveniente colocar el código que se encuentra en {{#var:codespath}}ejemplo1/1form_posted.php en el mismo archivo en donde se encuentra la «form». Lo anterior se muestra en el siguiente ejemplo:
| |
| − | | |
| − | {{#var:codespath}}ejemplo1/2form2.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php
| |
| − | | |
| − | // Es este ejemplo hemos colocado a «1form1.php» y «1form_posted.php» en un mismo archivo.
| |
| − | // Note que en la l'inea <form class='form-style-1' action="2form2.php" method="POST"> se
| |
| − | // llama este mismo archivo «2form2.php»
| |
| − | // Debemos tambien notar que en este caso es apropiado que la request venga via POST
| |
| − | // porque la GET ser'a ejecutada autom'aticamente cuando abrimos el archivo en el
| |
| − | // navegador web, y queremos que la request sea ejecutada cuando el usuario lo
| |
| − | // indique (en este caso cuando se haga cick en el bot'on «Sumit»)
| |
| − | | |
| − | | |
| − | // print_r($_SERVER);
| |
| − | | |
| − | | |
| − | // // Ejemplo 1 - Request via POST - Hemos tambi'en colocado un if para eque el
| |
| − | // // programa compruebe que la request viene via POST
| |
| − | if ($_SERVER['REQUEST_METHOD'] == 'POST'){
| |
| − | // Todos los valores ingresados en la form se almacenan en la variable $_POST
| |
| − | print_r($_POST);
| |
| − | | |
| − | // "<br/>" introduce un salto de l'inea
| |
| − | echo "<br/>"."First Name: ".$_POST['firstname'];
| |
| − | echo "<br/>"."Gender: ".$_POST['gender'];
| |
| − | echo "<br/>"."Car: ".$_POST['cartype'];
| |
| − | echo "<br/>"."Text: ".$_POST['sometext'];
| |
| − | | |
| − | // Como $vehicle es un Array[] (ver explicaci'on en 1form1.php) debemos realizar un
| |
| − | // loop para imprimir los valores almacenados en la variable $vehible:
| |
| − | $vehicles = $_POST['vehicle'];
| |
| − | foreach ($vehicles as $value)
| |
| − | echo "<br/>Vehicle: ".$value;
| |
| − | | |
| − | echo "<br/>"."Password: ".$_POST['password'];
| |
| − | echo "<br/>";
| |
| − | echo "<br/>";
| |
| − | }
| |
| − | // else{
| |
| − | // echo "<br/>"."Bad Request , must come via POST";
| |
| − | // }
| |
| − | | |
| − | | |
| − | // // Ejemplo 2 - Request via GET - Descomente la l'inea «method="GET"» en el archivo 1form1.php para este ejemplo.
| |
| − | // // Note que a trav'es de una request via GET, las variables se despliegan en la barra de direcci'on del navegador web.
| |
| − | // echo "<br/>"."First Name: ".$_GET['firstname'];
| |
| − | // echo "<br/>"."Gender: ".$_GET['gender'];
| |
| − | // echo "<br/>"."Car: ".$_GET['cartype'];
| |
| − | // echo "<br/>"."Text: ".$_GET['sometext'];
| |
| − | | |
| − | // $vehicles = $_GET['vehicle'];
| |
| − | // foreach ($vehicles as $value)
| |
| − |
| |
| − | // echo "<br/>Vehicle: ".$value;
| |
| − | // echo "<br/>"."Password: ".$_GET['password'];
| |
| − | | |
| − | | |
| − | // // Ejemplo 3 - Request via GET fuera del la </form>
| |
| − | // // Note como puede ser transmitida una variable, en este ejemplo id=25
| |
| − | // if ($_SERVER['REQUEST_METHOD'] == 'GET') {
| |
| − | // echo "<br/>".$_GET['id'];
| |
| − | // echo "<br/>"; // line break
| |
| − | // }
| |
| − | | |
| − | ?>
| |
| − | | |
| − | | |
| − | <!DOCTYPE html>
| |
| − | | |
| − | <html>
| |
| − | | |
| − | <head>
| |
| − | <link rel="stylesheet" href="style.css">
| |
| − | </head>
| |
| − | | |
| − | <body>
| |
| − | <!-- Lo siguiente es equivalente a escribir el texto directamente, a continuaci'on lo colocamos
| |
| − | en un PHP code a manera de ilustraci'on -->
| |
| − | <?php echo 'Our first Form example'; ?>
| |
| − | <h2>Form Enter</h2>
| |
| − | <!-- Ejemplo 1 en el archivo 1form_posted.php (Request via POst) - Descomente la siguiente l'inea: -->
| |
| − | <form class='form-style-1' action="2form2.php" method="POST">
| |
| − | <!-- Ejemplo 2 en el archivo 1form_posted.php (Request via GET) - Descomente la siguiente l'inea:
| |
| − | Note que a trav'es de una request via GET, las variables se despliegan en la
| |
| − | barra de direcci'on del navegador web. -->
| |
| − | <!-- <form class='form-style-1' action="2form2.php" method="GET"> -->
| |
| − | | |
| − | <label>First Name</label>
| |
| − | <input type='text' name='firstname' required></input>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | Password
| |
| − | <input type='password' name='password'/>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <!-- Notice that in this case (type='radio') both of the names are set to the same name, this is
| |
| − | because we want to treat both of these options as part of the same group. En otras palabras, la
| |
| − | variable asociada a este elemento ser'a gener y valor de dicha variable puede ser 'Male' or 'Female'-->
| |
| − | <input type='radio' name='gender' value='Male'>Male</input>
| |
| − | <input type='radio' name='gender' value='Female'>Female</input>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <!-- Note que en el caso de un checkbox el name debe ser definido como un Array[] debido a que en el
| |
| − | checkbox se puede seleccionar m'as de un valor. So, si el usuario selecciona 'Car' y 'Bike', el valor
| |
| − | de la variable ser'a vehicle['Car','Bike'] -->
| |
| − | <input type='checkbox' name='vehicle[]' value='Car'>I have a Car</input>
| |
| − | <input type='checkbox' name='vehicle[]' value='Bike'>I have a Bike</input>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <select name='cartype'>
| |
| − | <option value='Mini'>Mini</option>
| |
| − | <option value='Volvo'>Volvo</option>
| |
| − | <option value='BMW'>BMW</option>
| |
| − | <option value='Saab'>Saab</option>
| |
| − | <option value='Ford'>Ford</option>
| |
| − | </select>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <textarea name="sometext" rows='4' cols='40'>Web develpment</textarea>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <input type='submit'></input>
| |
| − | </form>
| |
| − | <!-- Ejemplo 3 en el archivo 1form_posted.php (Request via GET fuera del la </form>)
| |
| − | Descomente la siguiente l'inea:
| |
| − | Note como puede ser transmitida una variable, en este ejemplo id=25 -->
| |
| − | <a href="1form_posted.php?id=25" method="GET">Get Request</a>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | '''Sessions:'''
| |
| − | | |
| − | A session is a collection of data ''«stored on the server»'' and associated with a given user.
| |
| − | | |
| − | '''Sessions''' are different to '''Cookies'''. The main difference between a '''session''' and a '''cookie''' is that '''session''' data is stored on the server, whereas a '''cookies''' is a collection of data ''«stored by the browser»'' and sent to the server with every request.
| |
| − | | |
| − | '''Sessions''' are more secure than '''cookies''' as it is stored in server. Cookie can be turn off from browser and/or deleted by the client.
| |
| − | | |
| − | We can use a session to retain information from a previous page. Sessions are useful when, for example, a user has logged into an application. We can keep a record of their login details from file to file using a session.
| |
| − | | |
| − | '''How do we use sessions - $_SESSION:''' The PHP global variable '''$_SESSION''' is basically a variable that we can store values which can be later accessed from another PHP script.
| |
| − | | |
| − | '''$_SESSION''' creates a unique '''id''' for each user. PHP session can exactly identify each user and serve them stored data.
| |
| − | | |
| − | | |
| − | '''Starting PHP Session:''' To start a PHP session, we use '''session_start()''' function. It must be on the top of HTML or any text.
| |
| − | | |
| − | Para pasar los valores almacenados en '''$_SESSION''' a otro archivo, we can use the php '''header''' function:
| |
| − | <syntaxhighlight lang="php">
| |
| − | header('Location: file.php');
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | The '''header'' function hace que se ejecute (que se abra por lo tanto) el archivo indicado.
| |
| − | | |
| − | Para entender mejor la utilidad y el funcionamiento de '''Sessions''' observe el siguiente ejemplo:
| |
| − | | |
| − | {{#var:codespath}}ejemplo1/3session1.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php
| |
| − | | |
| − | session_start();
| |
| − | | |
| − | | |
| − | // if ($_SERVER['REQUEST_METHOD'] == 'POST') {
| |
| − | // $_SESSION["name"] = "Adeloaleman";
| |
| − | // $_SESSION['gender'] = "Male";
| |
| − | // header('Location: 3session_confirm.php');
| |
| − | // }
| |
| − | | |
| − | | |
| − | // // Aqu'i estamos utilizando «sessions» para almacenar los valores introducidos en la «form»:
| |
| − | // // Estos parametros ser'an luego trans
| |
| − | if ($_SERVER['REQUEST_METHOD'] == 'POST') {
| |
| − | $_SESSION['name'] = $_POST['firstname'];
| |
| − | $_SESSION['gender'] = $_POST['gender'];
| |
| − | header('Location: 3session_confirm.php');
| |
| − | }
| |
| − | | |
| − | ?>
| |
| − | | |
| − | | |
| − | <!DOCTYPE html>
| |
| − | | |
| − | <html>
| |
| − | | |
| − | <head>
| |
| − | <link rel="stylesheet" href="style.css">
| |
| − | </head>
| |
| − | | |
| − | <body>
| |
| − | <?php echo 'Our first Form example'; ?>
| |
| − | <h2>Form Enter</h2>
| |
| − | <form class='form-style-1' action="3session1.php" method="POST">
| |
| − | | |
| − | <label>First Name</label>
| |
| − | <input type='text' name='firstname' required></input>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | Password
| |
| − | <input type='password' name='password'/>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <input type='radio' name='gender' value='Male'>Male</input>
| |
| − | <input type='radio' name='gender' value='Female'>Female</input>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <input type='checkbox' name='vehicle[]' value='Car'>I have a Car</input>
| |
| − | <input type='checkbox' name='vehicle[]' value='Bike'>I have a Bike</input>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <select name='cartype'>
| |
| − | <option value='Mini'>Mini</option>
| |
| − | <option value='Volvo'>Volvo</option>
| |
| − | <option value='BMW'>BMW</option>
| |
| − | <option value='Saab'>Saab</option>
| |
| − | <option value='Ford'>Ford</option>
| |
| − | </select>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <textarea name="sometext" rows='4' cols='40'>Web develpment</textarea>
| |
| − | | |
| − | <br/><br/>
| |
| − | | |
| − | <input type='submit'></input>
| |
| − | </form>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | El siguiente archivo '''(3session_confirm.php)''' se ejecuta desde {{#var:codespath}}ejemplo1/3session1.php. Utiliza los valores que, en '''3session1.php''', fueron almacenados la variable '''$_SESSION'''.
| |
| − | {{#var:codespath}}ejemplo1/3session_confirm.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php session_start(); ?>
| |
| − | | |
| − | <!DOCTYPE html>
| |
| − | <html>
| |
| − | <body>
| |
| − | | |
| − | <?php
| |
| − | // Get session variables
| |
| − | print_r($_SESSION);
| |
| − | echo "<br/>".$_SESSION["name"];
| |
| − | echo "<br/>".$_SESSION["gender"];
| |
| − | ?>
| |
| − | | |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | En {{#var:codespath}}ejemplo1/3session1.php:
| |
| − | # Hemos usado '''sessions''' para almacenar los valores ingresados en la '''form''' en la variable '''$_SESSION'''.
| |
| − | # Luego la función '''header('Location: 3session_confirm.php')''' hace que el archivo '''3session_confirm.php''' se ejecute.
| |
| − | # '''3session_confirm.php''' utiliza los valores que, en '''3session1.php''', fueron almacenados la variable '''$_SESSION'''.
| |
| − | | |
| − | ===Style===
| |
| − | En los ejemplos anteriores, note que el archivo '''«style.css»''' ha sido integrado a nuestro archivo html de la siguiente forma:
| |
| − | <syntaxhighlight lang="html">
| |
| − | <head>
| |
| − | <link rel="stylesheet" href="style.css">
| |
| − | </head>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | Ahora, en caso de que queramos escribirlo en el mismo file html:
| |
| − | <syntaxhighlight lang="html">
| |
| − | <head>
| |
| − | <style type="text/css">
| |
| − | ... Aqu'i escribir'iamos el style
| |
| − | ...
| |
| − | ...
| |
| − | </style>
| |
| − | </head>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | De los ejemplos anteriores, note también que hemos agregado un class attribute to the form and input submit button:
| |
| − | <syntaxhighlight lang="html">
| |
| − | <form class='form-style-1' action="1form_posted.php" method="POST">
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | <syntaxhighlight lang="html">
| |
| − | <input class='button' type='submit'></input>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | ... estos atributos («form-style-1» «button») se encuentran, por supuesto, definidos en el archivo style.css.
| |
| − | | |
| − | El siguiente es el archivo '''style.css''' que hemos usado en este ejemplo:
| |
| − | {{#var:codespath}}/ejemplo1/style.css
| |
| − | <syntaxhighlight lang="css">
| |
| − | .form-style-1 {
| |
| − | margin:10px auto;
| |
| − | max-width: 400px;
| |
| − | padding: 20px 12px 10px 20px;
| |
| − | font: 20px "Lucida Sans Unicode", "Lucida Grande", sans-serif;
| |
| − | }
| |
| − | .form-style-1 li {
| |
| − | padding: 0;
| |
| − | display: block;
| |
| − | list-style: none;
| |
| − | margin: 10px 0 0 0;
| |
| − | }
| |
| − | .form-style-1 label{
| |
| − | margin:0 0 3px 0;
| |
| − | padding:0px;
| |
| − | display:block;
| |
| − | font-weight: bold;
| |
| − | }
| |
| − | .form-style-1 input[type=text],
| |
| − | .form-style-1 input[type=date],
| |
| − | .form-style-1 input[type=datetime],
| |
| − | .form-style-1 input[type=number],
| |
| − | .form-style-1 input[type=search],
| |
| − | .form-style-1 input[type=time],
| |
| − | .form-style-1 input[type=url],
| |
| − | .form-style-1 input[type=email],
| |
| − | textarea,
| |
| − | select{
| |
| − | box-sizing: border-box;
| |
| − | -webkit-box-sizing: border-box;
| |
| − | -moz-box-sizing: border-box;
| |
| − | border:1px solid #BEBEBE;
| |
| − | padding: 7px;
| |
| − | margin:0px;
| |
| − | -webkit-transition: all 0.30s ease-in-out;
| |
| − | -moz-transition: all 0.30s ease-in-out;
| |
| − | -ms-transition: all 0.30s ease-in-out;
| |
| − | -o-transition: all 0.30s ease-in-out;
| |
| − | outline: none;
| |
| − | }
| |
| − | .form-style-1 input[type=text]:focus,
| |
| − | .form-style-1 input[type=date]:focus,
| |
| − | .form-style-1 input[type=datetime]:focus,
| |
| − | .form-style-1 input[type=number]:focus,
| |
| − | .form-style-1 input[type=search]:focus,
| |
| − | .form-style-1 input[type=time]:focus,
| |
| − | .form-style-1 input[type=url]:focus,
| |
| − | .form-style-1 input[type=email]:focus,
| |
| − | .form-style-1 textarea:focus,
| |
| − | .form-style-1 select:focus{
| |
| − | -moz-box-shadow: 0 0 8px #88D5E9;
| |
| − | -webkit-box-shadow: 0 0 8px #88D5E9;
| |
| − | box-shadow: 0 0 8px #88D5E9;
| |
| − | border: 1px solid #88D5E9;
| |
| − | }
| |
| − | .form-style-1 .field-divided{
| |
| − | width: 49%;
| |
| − | }
| |
| − | | |
| − | .form-style-1 .field-long{
| |
| − | width: 100%;
| |
| − | }
| |
| − | .form-style-1 .field-select{
| |
| − | width: 100%;
| |
| − | }
| |
| − | .form-style-1 .field-textarea{
| |
| − | height: 100px;
| |
| − | }
| |
| − | .form-style-1 input[type=submit], .form-style-1 input[type=button]{
| |
| − | background: #4B99AD;
| |
| − | padding: 8px 15px 8px 15px;
| |
| − | border: none;
| |
| − | color: #fff;
| |
| − | }
| |
| − | .form-style-1 input[type=submit]:hover, .form-style-1 input[type=button]:hover{
| |
| − | background: #4691A4;
| |
| − | box-shadow:none;
| |
| − | -moz-box-shadow:none;
| |
| − | -webkit-box-shadow:none;
| |
| − | }
| |
| − | .form-style-1 .required{
| |
| − | color:red;
| |
| − | }
| |
| − | .button {
| |
| − | display: inline-block;
| |
| − | background: #4B99AD;
| |
| − | padding: 8px 15px 8px 15px;
| |
| − | border: none;
| |
| − | color: #fff;
| |
| − | border-radius: 2px;
| |
| − | padding: 0.48rem 0.8rem !important;
| |
| − | line-height: 1.4 !important;
| |
| − | position: relative;
| |
| − | text-transform: uppercase;
| |
| − | }
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | ==Ejemplo 2 - Databases in PHP==
| |
| − | Primero tenemos que crear la base de datos y la tabla que usaremos:
| |
| − | | |
| − | <syntaxhighlight lang="sql">
| |
| − | CREATE DATABASE wdtest;
| |
| − | | |
| − | USE wdtest;
| |
| − | | |
| − | CREATE TABLE users(
| |
| − | id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
| |
| − | username VARCHAR(50) NOT NULL,
| |
| − | email VARCHAR(50) NOT NULL,
| |
| − | password VARCHAR(50) NOT NULL,
| |
| − | date TIMESTAMP NOT NULL,
| |
| − | PRIMARY KEY(id)
| |
| − | );
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | En {{#var:codespath}}ejemplo2/1register.php se realiza una conexión con la base de datos. En dicho código '''This is the line that makes the DB connection:'''
| |
| − | <syntaxhighlight lang="php">
| |
| − | $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | De esta forma estamos creando an instance of the '''PDO''' class, which stands for '''Prepared Data Object''' or '''PHP Data Objects'''.
| |
| − | | |
| − | '''Once we have the PDO instance''' we have available a whole bunch of functions (or methods) to help us interact with the mysql database:
| |
| − | * '''prepare()''' prepare our sql statement
| |
| − | * '''bindParam()''' bind input variables to sql statement
| |
| − | * '''execute()''' execute the sql statement
| |
| − | * '''fetch()''' fetch single row from result of execute
| |
| − | * '''query()''' run a direct sql statement in no params
| |
| − | * '''rowCount()''' number of rows returned from execute
| |
| − | * '''fetchAll()''' returns all rows in a query
| |
| − | * '''fetchColumn()''' return single column from query
| |
| − | | |
| − | '''The real PDO benefits are:'''
| |
| − | * security (usable prepared statements)
| |
| − | * usability (many helper functions to automate routine operations)
| |
| − | * reusability (unified API to access multitude of databases, from SQLite to Oracle)
| |
| − | | |
| − | The PDO extension defines a lightweight, consistent interface for accessing databases in PHP. It means that, regardless of which database you're using, use the same functions to issue queries and fetch data. There is no need to rewrite your queries again when you change your database.
| |
| − | | |
| − | '''Here is a list of database supported by PDO:'''
| |
| − | * MySQL
| |
| − | * Micro Soft SQL Server
| |
| − | * PostgreSQL
| |
| − | * Oracle
| |
| − | * Sqlite
| |
| − | * IBM DB2
| |
| − | * Firebird
| |
| − | * INFORMIX etc.
| |
| − | | |
| − | '''Security:'''
| |
| − | | |
| − | One of the big issues with allowing people to insert or select records from forms directly to the database is '''SQL injection'''.
| |
| − | | |
| − | '''SQL injection''' is when someone adds some SQL into a form field, e.g. the username field with malicious intent to break a database.
| |
| − | | |
| − | SQL injection is a code injection technique, used to attack data-driven applications, in which nefarious SQL statements are inserted into an entry field for execution.
| |
| − | | |
| − | For example, when the insert statement goes to add the username and password into the database, a person may inject some SQL themselves such as:
| |
| − | DROP TABLE users;
| |
| − | Via an input element on the form
| |
| − | | |
| − | Si, por ejemplo, en el campo $name se añade este sentencia:
| |
| − | $name = "Bobby';DROP TABLE users; ";
| |
| − | | |
| − | Y la query es: (Previous versions of php mysql libraries would allow you to set up a query like this)
| |
| − | $query = "SELECT * FROM users WHERE name='$name'";
| |
| − | | |
| − | Se ejecutará la siguiente orden:
| |
| − | SELECT * FROM users WHERE name='Bobby';DROP TABLE users;
| |
| − | | |
| − | | |
| − | '''Placeholders:'''
| |
| − | | |
| − | El el siguiente ejemplo, los '''«?»''' son llamados '''Positional Placeholders'''
| |
| − | <syntaxhighlight lang="php">
| |
| − | | |
| − | # MySQL with PDO_MYSQL
| |
| − | $DBH = new PDO("mysql:host=$host;dbname=$dbname;port=$port", $user, $pass);
| |
| − | | |
| − | $sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?);"; // Positional Placeholders
| |
| − | | |
| − | $sth = $DBH->prepare($sql);
| |
| − | | |
| − | $sth->bindParam(1, $username);
| |
| − | $sth->bindParam(2, $password);
| |
| − | $sth->bindParam(3, $email);
| |
| − | | |
| − | $sth->execute();
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | '''Named Placeholder:'''
| |
| − | <syntaxhighlight lang="php">
| |
| − | $DBH = new PDO("mysql:host=$host;dbname=$dbname;port=$port", $user, $pass);
| |
| − | $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
| |
| − | | |
| − | $q = $DBH->prepare("select * from users where username = :username and password = :password LIMIT 1"); //Named placeholders
| |
| − | | |
| − | $q->bindValue(':username', $username);
| |
| − | $q->bindValue(':password', $password);
| |
| − | $q->execute();
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | '''PDO::bindParam()''' binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.
| |
| − | | |
| − | If we use PDOs to do our insert statements, and our select statements with '''named placeholders''', or '''positional(?) placeholders''' we can help '''prevent SQL Injection'''.
| |
| − | | |
| − | Notice that '''bindParam only binds data to placeholders leaving unchanged the query'''. So there is no way to change the original SQL query, because it has already sent to the server by means of the '''prepare''' method and because you are sending '''SQL queries and input data separately''' so user entered data can't interfere with queries.
| |
| − | | |
| − | This allows SQL to insert the values into the expression, without modifying the expression itself.
| |
| − | | |
| − | So, if the user inserts something lile this:
| |
| − | <syntaxhighlight lang="php">
| |
| − | $name = "Bobby';DROP TABLE users; ";
| |
| − | </syntaxhighlight>
| |
| − | It simply becomes a search string rather than becoming part of the query. We would be searching for a name of "Bobby';DROP TABLE users; ". Which would be meaningless but harmless.
| |
| − | | |
| − | | |
| − | <syntaxhighlight lang="html">
| |
| − | <?php
| |
| − | | |
| − | session_start();
| |
| − | | |
| − | $username = "";
| |
| − | $email = "";
| |
| − | $password = "";
| |
| − | | |
| − | $usernameErr = "";
| |
| − | $emailErr = "";
| |
| − | $passwordErr = "";
| |
| − | | |
| − | | |
| − | if($_POST){
| |
| − | // Recuperaci'on de los valores introducidos en la Form:
| |
| − | $username = $_POST['username'];
| |
| − | $email = $_POST['email'];
| |
| − | $password = $_POST['password'];
| |
| − | | |
| − | // Server Side Validation: Aqu'i nos aseguramos de que los valores introducidos en la Form sean v'alidos:
| |
| − | if (empty($username) || strlen($username) < 4 ){
| |
| − | $usernameErr = 'Username is required, at least 4 chars';
| |
| − | }
| |
| − | | |
| − | if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
| |
| − | $emailErr = 'Sorry! you did not enter a correct email. ';
| |
| − | }
| |
| − | | |
| − | if (strlen($password) < 8) {
| |
| − | $passwordErr = 'This password is too short!';
| |
| − | }
| |
| − | | |
| − | | |
| − | // Si las validaciones realizadas en el paso anterior:
| |
| − | if (empty($usernameErr) && empty($emailErr) && empty($passwordErr)){
| |
| − | // if (empty($usernameErr) and empty($emailErr) and empty($passwordErr)) {
| |
| − | | |
| − | // Conecci'on con la base de datos:
| |
| − | try {
| |
| − | $host = '127.0.0.1';
| |
| − | $port = 3306;
| |
| − | $dbname = 'wdtest';
| |
| − | $user = 'root';
| |
| − | $pass = 'a1640774200';
| |
| − | | |
| − | # MySQL with PDO_MYSQL
| |
| − | $DBH = new PDO("mysql:host=$host;dbname=$dbname;port=$port", $user, $pass);
| |
| − | | |
| − | $sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?);";
| |
| − | | |
| − | $sth = $DBH->prepare($sql);
| |
| − |
| |
| − | $sth->bindParam(1, $username);
| |
| − | $sth->bindParam(2, $password);
| |
| − | $sth->bindParam(3, $email);
| |
| − |
| |
| − | $sth->execute();
| |
| − | | |
| − | // Si hubo errores en la request queremos un mensaje de error que nos ayude a
| |
| − | // localizar el problema:
| |
| − | // We have been having problems with inserts not working and not getting any
| |
| − | // useful errors. To remedy this we can add the following after the ->execute() of
| |
| − | // our SQL statement:
| |
| − | $arr = $sth->errorInfo();
| |
| − | if (isset($arr[2])) {// if we have an error...
| |
| − | echo "<br/> Database Error Code: ".$arr[0];
| |
| − | echo "<br/> Driver Error Code: ".$arr[1];
| |
| − | echo "<br/> Database Error Message: ".$arr[2];
| |
| − | exit();
| |
| − | }
| |
| − | | |
| − | $_SESSION["username"] = $username;
| |
| − | $_SESSION["email"] = $email;
| |
| − | header('Location: 3confirm.php');
| |
| − | | |
| − | exit();
| |
| − |
| |
| − | echo 'You are now registered!';
| |
| − | }
| |
| − | catch(PDOException $e) {echo 'Error' . $e;}
| |
| − | // catch(PDOException $e) {echo $e->getMessage();}
| |
| − | }
| |
| − | }
| |
| − | | |
| − | ?>
| |
| − | <!DOCTYPE>
| |
| − | <html>
| |
| − | <head>
| |
| − | <link rel="stylesheet" href="style.css">
| |
| − | <style>
| |
| − | .error {display: block;color: #FF0000; }
| |
| − | </style>
| |
| − | </head>
| |
| − | <body>
| |
| − | <h2> Registration Form</h2>
| |
| − | <form class='form-style' action="1register.php" method="post">
| |
| − | Username <input type="text" name="username" value="<?php echo $username; ?>"/>
| |
| − | <span class = "error"><?php echo $usernameErr;?></span>
| |
| − | email <input type="text" name="email" value="<?php echo $email; ?>"/>
| |
| − | <span class = "error"><?php echo $emailErr;?></span>
| |
| − | Password <input type="password" name="password" value="<?php echo $password; ?>"/>
| |
| − | <span class = "error"><?php echo $passwordErr;?></span>
| |
| − | <input type="submit" class='button' name='submit' value= 'Register'/>
| |
| − | </form>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | {{#var:codespath}}ejemplo2/2login.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php
| |
| − | | |
| − | session_start();
| |
| − | | |
| − | $username = "";
| |
| − | $password = "";
| |
| − | | |
| − | $usernameErr = "";
| |
| − | $passwordErr = "";
| |
| − | | |
| − | | |
| − | if($_POST){
| |
| − | $username = $_POST['username'];
| |
| − | $password = $_POST['password'];
| |
| − | | |
| − | if(empty($username) || strlen($username) < 4){
| |
| − | $usernameErr = 'Username is required, at least 4 chars';
| |
| − | }
| |
| − | | |
| − | if(strlen($password) < 8){
| |
| − | $passwordErr = 'password 8 or more chars';
| |
| − | }
| |
| − |
| |
| − | if(empty($usernameErr) && empty($passwordErr)){
| |
| − |
| |
| − | try {
| |
| − | $host = '127.0.0.1';
| |
| − | $dbname = 'wdtest';
| |
| − | $user = 'root';
| |
| − | $pass = 'a1640774200';
| |
| − | $port=3306;
| |
| − | | |
| − | # MySQL with PDO_MYSQL
| |
| − | $DBH = new PDO("mysql:host=$host;dbname=$dbname;port=$port", $user, $pass);
| |
| − | $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
| |
| − | | |
| − | $q = $DBH->prepare("select * from users where username = :username and password = :password LIMIT 1");
| |
| − | | |
| − | $q->bindValue(':username', $username);
| |
| − | $q->bindValue(':password', $password);
| |
| − | $q->execute();
| |
| − | | |
| − | // Mensaje de error si hubo problemas con la request
| |
| − | $arr = $q->errorInfo();
| |
| − | if (isset($arr[2])) {// if we have an error...
| |
| − | echo "<br/> Database Error Code: ".$arr[0];
| |
| − | echo "<br/> Driver Error Code: ".$arr[1];
| |
| − | echo "<br/> Database Error Message: ".$arr[2];
| |
| − | exit();
| |
| − | }
| |
| − |
| |
| − | $row = $q->fetch(PDO::FETCH_ASSOC);
| |
| − | // returns table row(s) as an associative array of values column names to data values:
| |
| − | // Array ( [id] => 2
| |
| − | // [username] => kike
| |
| − | // [email] => kike@gmail.com
| |
| − | // [password] => kikedominguez
| |
| − | // [date] => 2017-10-27 18:07:15 )
| |
| − | | |
| − | $message = '';
| |
| − | if (!empty($row)){ //is the array empty
| |
| − | $username = $row['username'];
| |
| − | $email = $row['email'];
| |
| − | | |
| − | $_SESSION["username"] = $username;
| |
| − | $_SESSION["email"] = $email;
| |
| − | header('Location: 3confirm.php');
| |
| − | | |
| − | exit();
| |
| − | }
| |
| − | else {
| |
| − | $message= 'Sorry your log in details are not correct';
| |
| − | }
| |
| − | }catch(PDOException $e) {echo $e->getMessage();}
| |
| − | }
| |
| − | }
| |
| − | ?>
| |
| − | | |
| − | <!DOCTYPE>
| |
| − | <html>
| |
| − | <head>
| |
| − | <link rel="stylesheet" href="style.css">
| |
| − | <style>
| |
| − | .error {display: block;color: #FF0000;}
| |
| − | </style>
| |
| − | </head>
| |
| − | <body>
| |
| − | <h2>Login</h2><br></br>
| |
| − | <form class='form-style' action="2login.php" method="post">
| |
| − | Username <input type="text" name="username" value="<?php echo $username; ?>"/>
| |
| − | <span class="error"><?php echo $usernameErr;?></span>
| |
| − | Password <input type="password" name="password" value="<?php echo $password; ?>"/>
| |
| − | <span class="error"><?php echo $passwordErr;?></span>
| |
| − | <input type="submit" name="submit" value="Login" class='button'/>
| |
| − | <?php
| |
| − | if(!empty($message)){
| |
| − | echo '<br>';
| |
| − | echo $message;
| |
| − | }
| |
| − | ?>
| |
| − | </form>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | {{#var:codespath}}ejemplo2/3confirm.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php
| |
| − | session_start();
| |
| − | ?>
| |
| − | | |
| − | <!DOCTYPE html>
| |
| − | <html>
| |
| − | <body>
| |
| − | <?php
| |
| − | // Get session variables
| |
| − | if (isset($_SESSION["username"])){
| |
| − | echo "<br/>Logged in as: ".$_SESSION["username"];
| |
| − | echo "<br/>email: ".$_SESSION["email"];
| |
| − | }
| |
| − | ?>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | ===Style===
| |
| − | El siguiente es el archivo style.css que hemos usado en este ejemplo:
| |
| − | | |
| − | {{#var:codespath}}ejemplo2/style.css
| |
| − | <syntaxhighlight lang="css">
| |
| − | .button {
| |
| − | display: inline-block;
| |
| − | background: #4B99AD;
| |
| − | padding: 8px 15px 8px 15px;
| |
| − | border: none;
| |
| − | color: #fff;
| |
| − | border-radius: 2px;
| |
| − | padding: 0.48rem 0.8rem !important;
| |
| − | line-height: 1.4 !important;
| |
| − | position: relative;
| |
| − | text-transform: uppercase;
| |
| − | }
| |
| − | | |
| − | label,input {
| |
| − | display:block;
| |
| − | margin-bottom: 5px;
| |
| − |
| |
| − | }
| |
| − | | |
| − | .form-style input[type=text], .form-style input[type=password] {
| |
| − | height: 28px;
| |
| − | border-radius: 4px;
| |
| − | border:1px solid #BEBEBE;
| |
| − | }
| |
| − | | |
| − | .form-style, h2 {
| |
| − | margin:10px auto;
| |
| − | max-width: 50%;
| |
| − | padding: 20px 12px 10px 20px;
| |
| − | }
| |
| − | | |
| − | .form-style input[type=submit]:hover{
| |
| − | background: #4691A4;
| |
| − | box-shadow:none;
| |
| − | -moz-box-shadow:none;
| |
| − | -webkit-box-shadow:none;
| |
| − | }
| |
| − | | |
| − | .form-style {
| |
| − | font: 14px "Lucida Sans Unicode", "Lucida Grande", sans-serif;
| |
| − | }
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | ==Ejemplo 3 - Dynamic Content==
| |
| − | Esta sección está basada en: [[Media:7-ejemplo3-Dynamic_web_pages.pdf]]
| |
| − | | |
| − | '''Dynamic vs Static Web Pages:'''
| |
| − | * Consider if you were to generate a full page for every single Amazon product, they would be next to impossible to manually manage
| |
| − | * Pages would get corrupt, lost, mistagged, damaged, etc
| |
| − | * Given that all of them look the same, and the data/content is different, we can look at the notion of a template
| |
| − | * If we use a template, we just fill in the blanks, and alter some portions depending on what we need.
| |
| − | | |
| − | * We need separate files for each bit of code that will be common to all files/pages
| |
| − | | |
| − | | |
| − | [[File:Page_layout.png |600px | thumb | center | Page layout.]]
| |
| − | | |
| − | | |
| − | ===Index===
| |
| − | '''«index.php»''' es al archivo que será llamado por defecto por el web browser.
| |
| − | | |
| − | Por tanto, al colocar en el web browser la dirección:
| |
| − | {{#var:codespath}}ejemplo3
| |
| − | | |
| − | ... se abrirá el archivo:
| |
| − | | |
| − | {{#var:codespath}}ejemplo3/index.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php
| |
| − | include('header.php');
| |
| − | ?>
| |
| − | <h1>Welcome To our Products App</h1>
| |
| − | <p>All sorts of normal content go in here</p>
| |
| − | <?php
| |
| − | include('footer.php'); // include the footer page
| |
| − | ?>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | ===Header===
| |
| − | {{#var:codespath}}ejemplo3/header.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <!DOCTYPE html>
| |
| − | <html>
| |
| − | <head>
| |
| − | </head>
| |
| − | <body>
| |
| − | <link rel="stylesheet" href="menu.css">
| |
| − | <link rel="stylesheet" href="style.css">
| |
| − | <ul>
| |
| − | <li><a href="index.php">Home</a></li>
| |
| − | <li><a href="createProduct.php">New</a></li>
| |
| − | <li><a href="products.php">List</a></li>
| |
| − | <li><a href="#about">About</a></li>
| |
| − | </ul>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | {{#var:codespath}}ejemplo3/menu.css
| |
| − | <syntaxhighlight lang="css">
| |
| − | ul {
| |
| − | list-style-type: none;
| |
| − | margin: 0;
| |
| − | padding: 0;
| |
| − | overflow: hidden;
| |
| − | background-color: #333;}
| |
| − | li {
| |
| − | float: left;}
| |
| − | li a {
| |
| − | display: inline-block;
| |
| − | color: white;
| |
| − | text-align: center;
| |
| − | padding: 14px 16px;
| |
| − | text-decoration: none;}
| |
| − | li a:hover {
| |
| − | background-color: #111;}
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | ===Footer===
| |
| − | {{#var:codespath}}ejemplo3/footer.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <div id='footer' >
| |
| − | <br/><br/>© CCT
| |
| − | College 2017
| |
| − | </div>
| |
| − | </body>
| |
| − | </html>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | ===Second page===
| |
| − | {{#var:codespath}}ejemplo3/secondpage.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php
| |
| − | include('header.php'); // include the header page
| |
| − | ?>
| |
| − | | |
| − | <h1>Second Page</h1>
| |
| − | <p>All sorts of normal content go in here</p>
| |
| − | | |
| − | <?php
| |
| − | include('footer.php'); // include the footer page
| |
| − | ?>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | ===Generate pages based on database entries===
| |
| − | | |
| − | <syntaxhighlight lang="mysql">
| |
| − | CREATE TABLE products(
| |
| − | id INT NOT NULL AUTO_INCREMENT,
| |
| − | product_name VARCHAR(50) NOT NULL,
| |
| − | product_description VARCHAR(100),
| |
| − | cost DECIMAL(8,2),
| |
| − | PRIMARY KEY(id)
| |
| − | );
| |
| − | | |
| − | insert into products values(1, 'phone', 'Some amazing phone An', 235.43);
| |
| − | insert into products values(2, 'tablet', 'even better tablet Snazzy', 452.00);
| |
| − | insert into products values(3, 'laptop', 'laptop', 1234.54);
| |
| − | insert into products values(4, 'desktop', 'Big fancy gaming machine', 2345.43);
| |
| − | insert into products values(5, 'monitor', '32 inch flat screen', 345.32);
| |
| − | insert into products values(6, 'mouse', 'standard mouse', 9.99);
| |
| − | insert into products values(7, 'keyboard', 'wireless keyboard', 20.99);
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | A continuación se muestra el código que hará la conexión con la base de datos
| |
| − | | |
| − | {{#var:codespath}}ejemplo3/db.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php
| |
| − | try{
| |
| − | $host = '127.0.0.1';
| |
| − | $dbname = 'wdtest';
| |
| − | $user = 'root';
| |
| − | $pass = '********';
| |
| − | $port=3306;
| |
| − | $DBH = new
| |
| − | PDO("mysql:host=$host;dbname=$dbname;port=$port",$user,$pass);
| |
| − | }
| |
| − | catch (PDOException $e) {echo $e->getMessage();}
| |
| − | ?>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | {{#var:codespath}}ejemplo3/errordb.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php
| |
| − | // We have been having problems with inserts not working and not getting any
| |
| − | // useful errors. To remedy this we can add the following after the ->execute() of
| |
| − | // our SQL statement:
| |
| − | $arr = $stmt->errorInfo();
| |
| − | if (isset($arr[2])) {// if we have an error...
| |
| − | echo "<br/> Database Error Code: ".$arr[0];
| |
| − | echo "<br/> Driver Error Code: ".$arr[1];
| |
| − | echo "<br/> Database Error Message: ".$arr[2];
| |
| − | exit();
| |
| − | }
| |
| − | ?>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | {{#var:codespath}}ejemplo3/products.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php include('header.php'); ?>
| |
| − | <h2>Product list</h2>
| |
| − | <?php
| |
| − | // create the connection
| |
| − | include('db.php');
| |
| − | // select the correct table
| |
| − | $stmt = $DBH->prepare("SELECT * FROM products");
| |
| − | $stmt->execute();
| |
| − | include('errordb.php');
| |
| − | // get the rows and put it in a variable
| |
| − | $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
| |
| − | echo "<table>";
| |
| − | echo "<tr><th>Id</th><th>Name</th><th>Description</th></tr>";
| |
| − | foreach($rows as $row){
| |
| − | echo "<tr>";
| |
| − | echo "<td>";
| |
| − | echo $row['id'];
| |
| − | echo "</td>";
| |
| − | echo "<td>";
| |
| − | echo $row['product_name'];
| |
| − | echo "</td>";
| |
| − | echo "<td>";
| |
| − | echo $row['product_description'];
| |
| − | echo "</td>";
| |
| − | echo "<td>";
| |
| − | echo "<a href=viewProduct.php?id=".$row['id'].">View</a>";
| |
| − | echo "</td>";
| |
| − | echo "</tr>";
| |
| − | }
| |
| − | echo "</table>";
| |
| − | ?>
| |
| − | <?php include 'footer.php'; ?>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | El siguiente código '''«.css»''' define el estilo de la tabla que es desplegada en '''«products.hph»'''. Este código, sin embargo, es llamado en '''«header.php»'''
| |
| − | | |
| − | {{#var:codespath}}ejemplo3/style.css
| |
| − | <syntaxhighlight lang="css">
| |
| − | table {
| |
| − | border: 1px solid black;
| |
| − | }
| |
| − | th, td {
| |
| − | padding: 15px;
| |
| − | text-align: left;
| |
| − | }
| |
| − | th{
| |
| − | background-color: mediumseagreen;
| |
| − | color: white}
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | {{#var:codespath}}ejemplo3/viewProduct.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php include('header.php'); ?>
| |
| − | <h2>Product</h2>
| |
| − | <?php
| |
| − | $pid = $_GET['id'];
| |
| − | include('db.php');
| |
| − | $stmt = $DBH->prepare("SELECT * FROM products WHERE id= :pid");
| |
| − | $stmt->bindValue(':pid', $pid);
| |
| − | $stmt->execute();
| |
| − | include('errordb.php');
| |
| − | $row = $stmt->fetch(PDO::FETCH_ASSOC);
| |
| − | echo $row['id'].", ".$row['product_name'].", ".$row['product_description'];
| |
| − | echo ", ".$row['cost']."<br/>";
| |
| − | ?>
| |
| − | <?php include 'footer.php'; ?>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | {{#var:codespath}}ejemplo3/deleteProduct.php
| |
| − | <syntaxhighlight lang="html">
| |
| − | <?php include('header.php'); ?>
| |
| − | <?php
| |
| − | include('db.php');
| |
| − | if ($_GET){
| |
| − | $pid = $_GET['id']; // from link in products.php
| |
| − | $stmt = $DBH->prepare("SELECT * FROM products WHERE id= :pid");
| |
| − | $stmt->bindValue(':pid', $pid);
| |
| − | $stmt->execute();
| |
| − | include('errordb.php');
| |
| − | $row = $stmt->fetch(PDO::FETCH_ASSOC);
| |
| − | $product = $row['product_name'];
| |
| − | $product_desc = $row['product_description'];
| |
| − | $cost = $row['cost'];
| |
| − | }
| |
| − | if ($_POST) {
| |
| − | $pid = $_POST['pid']; // from hidden input field
| |
| − | $stmt = $DBH->prepare("DELETE FROM products WHERE id= :pid");
| |
| − | $stmt->bindValue(':pid', $pid);
| |
| − | $stmt->execute();
| |
| − | include('errordb.php');
| |
| − | header("Location: products.php");
| |
| − | }
| |
| − | ?>
| |
| − | <h2>Delete Product</h2><br></br>
| |
| − | <form class='form-style' action="deleteProduct.php" method="post">
| |
| − | Product: <input type="text" name="product" value="<?php echo $product; ?>"
| |
| − | readonly/>
| |
| − | Description: <input type="text" name="description" value="<?php echo
| |
| − | $product_desc; ?>" readonly/>
| |
| − | Cost: <input type="text" name="cost" value="<?php echo $cost; ?>" readonly/>
| |
| − | <input type="hidden" name="pid" value="<?php echo $pid; ?>" />
| |
| − | <input type="submit" name="submit" value="Delete" class='button'/>
| |
| − | </form>
| |
| − | <?php include 'footer.php'; ?>
| |
| − | </syntaxhighlight>
| |
| − | | |
| − | | |
| − | <br/>
| |
| − | ==[[JavaScript]]==
| |
| − | | |
| − | | |
| − | <br />
| |