Document Details

HandierJadeite2200

Uploaded by HandierJadeite2200

T. Zalizam T. Muda

Tags

programming languages computer programming network programming web development

Summary

This document provides an introduction to network and web application programming. It covers different types of programming languages, including machine, assembly, algorithmic, business-oriented, education-oriented, object-oriented, declarative, and scripting languages. The document also explains the history of the internet and the World Wide Web (WWW).

Full Transcript

+ Introduction to Network and Web Application T. Zalizam T. Muda © 2023 + Identify the types of programming languages Explain the history of the Internet and WWW Recognise WWW Consortium Elaborate on...

+ Introduction to Network and Web Application T. Zalizam T. Muda © 2023 + Identify the types of programming languages Explain the history of the Internet and WWW Recognise WWW Consortium Elaborate on the network architecture Introduction to Network & Web Application T. Zalizam T. Muda © 2023 + Introduction Computer Programming Language Any of various languages for expressing a set of detailed instructions for a digital cptr. Such instructions can be executed directly when they are in the cptr manufacturer-specific numerical form known as machine language, after a simple substitution process when expressed in a corresponding assembly language, or after translation from some “high- level” language. Although there are many cptr lang., relatively few are widely used. T. Zalizam T. Muda © 2023 + Language Types Machine Document Formatting Assembly World Wide Web display Algorithmic Business-oriented Education-oriented Object-oriented Declarative Scripting T. Zalizam T. Muda © 2023 + Machine Language A machine lang. consists of the numeric codes for the operations that a particular cptr can execute directly. The codes are strings of 0s and 1s, or binary digits(“bits”), which are frequently converted both from and to hexadecimal(base 16) for human viewing and modification. Machine lang. instructions typically use some bits to represent operations, such as addition, and some to represent operands, or perhaps the location of the next instructions. Machine lang. is difficult to read and write, since it does not resemble conventional mathematical notation or human language, and its codes vary from cptr to cptr. T. Zalizam T. Muda © 2023 + Machine Language Advantages of ML The fast and efficient use of the computer can be done by using machine language. It requires no translator to translate the code. It is directly understood by the computer. T. Zalizam T. Muda © 2023 + Machine Language Disadvantages of ML All operation codes have to be remembered. All memory addresses have to be remembered. Finding errors in a program written in machine language is hard. T. Zalizam T. Muda © 2023 + Machine Language Q T. Zalizam T. Muda © 2023 + Assembly Language Assembly language is one level above machine language. Sometimes called assembly or ASM, an assembly language is a low-level programming language. It uses short mnemonic codes for instructions and allows the programmer to introduce names for blocks of memory that hold data. One might thus write “add pay, total” instead of “0110101100101000” for an instruction that adds two numbers. Assembly lang. is designed to be easily translated into machine language. Programs written in assembly languages are compiled by an assembler. Every assembler has its own assembly language, which is designed for one specific computer architecture. Although blocks of data may be referred to by name instead of by their machine addresses, assembly lang. does not provide more sophisticated means of organizing complex information. T. Zalizam T. Muda © 2023 + Assembly Language(cont.) Like machine lang., assembly lang. requires detailed knowledge of internal computer architecture. It is useful when such details are important, as in programming a computer to interact with input/output devices (printers, scanners, storage devices, and so forth) T. Zalizam T. Muda © 2023 + Assembly Language(cont.) eg https://www.digitalelectronicsdeeds.com/demos/demopage_micro.html T. Zalizam T. Muda © 2023 + Machine & Assembly Languages Example T. Zalizam T. Muda © 2023 + More… Machine language machine dependent, understood +1300042774 by computers, defined by the +1400593419 hardware design of that computer +1200274027 Assembly language After found that machine languages are LOAD BASEPAY too slow and tedious. English-like ADD OVERPAY abbreviations to overcome the problem STORE GROSSPAY with “strings of numbers”. Need assembler (translator) to change to machine language T. Zalizam T. Muda © 2023 + Algorithmic Languages Algorithmic languages are designed to express mathematical or symbolic computations. They can express algebraic operations in notation similar to mathematics and allow the use of subprograms that package commonly used operations for reuse. They were the first high-level languages. Example for algorithmic lang. are: FORTRAN ALGOL LISP C T. Zalizam T. Muda © 2023 + The first important algorithmic language was FORTRAN (formula translation), designed in 1957 by an IBM team led by John Backus. It was intended for scientific computations with real numbers and collections of them organized as one- or multidimensional arrays. Its control structures included conditional IF statements, repetitive loops (so-called DO loops), and a GOTO statement that allowed non-sequential execution of program code. FORTRAN made it convenient to have subprograms for common mathematical operations, and built libraries of them. FORTRAN was also designed to translate into efficient machine language. It was immediately successful and continues to evolve. T. Zalizam T. Muda © 2023 + ALGOL (algorithmic language) was designed by a committee of American and European computer scientists during 1958- 60 for publishing algorithms, as well as for doing computations. ALGOL had recursive subprograms – procedures that could invoke themselves to solve a problem by reducing it to a smaller problem of the same kind. ALGOL introduced block structure, in which program is composed of blocks that might contain both data and instructions and have the same structure as an entire program. Block structure became a powerful tool for building large programs out of small components. T. Zalizam T. Muda © 2023 + LISP (list processing) was developed about 1960 by John McCarthy at the Massachusetts Institute of Technology (MIT) and was founded on the mathematical theory of recursive functions. A LISP program is a function applied to data, rather than being a sequence of procedural steps as in FORTRAN and ALGOL. LISP uses a very simple notation in which operation are given in a parenthesized list. For example, (+ a (* b c)) stands for a + b * c. LISP became a common language for artificial intelligence (AI) programming T. Zalizam T. Muda © 2023 + The C programming language was developed in 1972 by Dennis Ritchie and Brian Kernighan at the AT&T Corporation for programming computer operating systems. Its capacity to structure data and programs through the composition of smaller units is comparable to that of ALGOL. It uses a compact notation and provides the programmer with the ability to operate with the addresses of data as well as with their values. This ability is important in systems programming, and C shares with assembly language the power to exploit all the features of a computer’s internal architecture. C, along with its descendant C++, remains one of the most common languages. T. Zalizam T. Muda © 2023 + COBOL COBOL (Common Business Oriented Language) has been heavily used by businesses since its inception 1959. A committee of computer manufactures and users and U.S. government organizations established CODASYL (Committee on Data Systems and Languages) to develop and oversee the language standard in order to ensure its portability across diverse systems. COBOL uses an English-like notation-novel when introduced. Business computations organize and manipulate large quantities of data, and COBOL introduced the record data structure for such tasks. T. Zalizam T. Muda © 2023 + SQL SQL (structured query language) is a language for specifying the organization of databases (collections of records). Databases organized with SQL are called relational because SQL provides the ability to query a database for information that falls in a given relation. For example, a query might be “find all records with both last name Smith and city New York”. Commercial database programs commonly use a SQL-like language for their queries. T. Zalizam T. Muda © 2023 + BASIC BASIC (Beginner’s All-purpose Symbolic Instruction Code) was designed at Dartmouth College in the mid-1960s by John Kemeny and Thomas Kurtz. It was intended to be easy to learn by novices, particularly non-computer science majors, and to run well on a time- sharing computer with many users. It had simple data structures and notation. Its small size and simplicity also made BASIC a popular language for early personal computers. T. Zalizam T. Muda © 2023 + PASCAL PASCAL is an imperative and procedural programming language, which Niklaus Wirth designed in 1968-69 and published in 1970, as a small, efficient language intended to encourage good programming practices using structured programming and data structuring. It is named in honor of the French mathematician, philosopher and physicist Blaise Pascal. Pascal was developed on the pattern of the ALGOL language. Pascal, like many programming languages of today, allows most kinds of definitions and declarations inside subroutines. T. Zalizam T. Muda © 2023 + LOGO HYPERTALK More details: https://www.britannica.com/technology/computer- programming-language T. Zalizam T. Muda © 2023 + Types of Programming Languages High-level language Assembly language – increasing comp. use rapidly. HLL – single statement for multi purposes. Need compilers to translate to machine languages. Almost similar to everyday English, mathematical notations Scripting language Scripts were created to shorten the traditional edit-compile-link-run process. Scripting languages can also be compiled, but because interpreters are simpler to write than compilers, they are interpreted more often than they are compiled T. Zalizam T. Muda © 2023 + Types of Programming Languages T. Zalizam T. Muda © 2023 Translator Programs (Assembler vs Compiler vs Interpreter) Assembler Compilers Interpreter Use in assembly Use in High level Use in High level languages. language. language. Convert assembly To speed up Execute high level language program to programming language directly machine language. process compared to without compiling assembly lang. into machine language. Convert high level language to machine Program is language. recompiled as new features are added Faster than & errors are Interpreter corrected T. Zalizam T. Muda © 2023 + Different Programming Languages T. Zalizam T. Muda © 2023 + Properties of Web Languages Compiled languages: Java, C, and C++. These languages are "typed" languages in that every identifier is assigned a fixed data type. The compiler scans the entire program and then writes machine language (or in the case of Java, writes to a virtual machine) to implement the operations. The key feature is that this code is generated before the program sees any data and will fail if the data is not of the expected type. What is Compiled Language? A compiled language is a programming language that is converted into machine code so that the processor can execute it. The compiled languages are usually compiled, not interpreted. For better understanding you can go through the types of compiled language – CLEO, COBOL, C, C++, C#, etc. T. Zalizam T. Muda © 2023 + Properties of Web Languages Interpreted languages: An interpreted language is a language in which the implementations execute instructions directly without earlier compiling a program into machine language. JavaScript, JScript, VBscript, Perl, PHP, Rexx, Python…… These languages are (at least in principle) executed line by line as the data flow in. the Difference between Compiled and Interpreted Language Both compiled and interpreted are programming languages. When it comes to compiled languages, they are usually compiled, not interpreted. While on the other hand, an interpreted language is commonly interpreted. T. Zalizam T. Muda © 2023 + Compiled vs Interpreted languages Compiled Languages Interpreted Languages much faster in execution (except often easier to write as you Java which is about 10 times slower don't have to pre-specify than C because it has the data types in advance and intermediate step of virtual machine- you can fling any data at it to-real machine translation) with. provide very powerful syntax slower and don't provide the checking capabilities which let you powerful syntax checking detect many errors at compile time capabilities of compiler which can be much, much easier to languages debug than runtime errors best for large programs which better suited to small process lots of data, and especially programs created by one for programs designed by teams of person where runtime errors people. are easier to find. T. Zalizam T. Muda © 2023 + Compiled vs Interpreted languages . https://byjus.com/gate/difference-between-compiled-and-interpreted-language/ T. Zalizam T. Muda © 2023 + Properties of Web Languages Object Oriented Languages Object-oriented programming (OOP) is a computer programming model that organises software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behaviour. OOP focuses on the objects that developers want to manipulate rather than the logic required to manipulate them. This approach to programming is well-suited for programs that are large, complex and actively updated or maintained. This includes programs for manufacturing and design, as well as mobile applications; for example, OOP can be used for manufacturing system simulation software. https://www.techtarget.com/searchapparchitecture/definition/object-oriented-programming-OOP T. Zalizam T. Muda © 2023 + OOP The structure, or building blocks, of object-oriented programming include the following: Classes are user-defined data types that act as the blueprint for individual objects, attributes and methods. Objects are instances of a class created with specifically defined data. Objects can correspond to real-world objects or an abstract entity. When class is defined initially, the description is the only object that is defined. Methods are functions that are defined inside a class that describe the behaviors of an object. Each method contained in class definitions starts with a reference to an instance object. Additionally, the subroutines contained in an object are called instance methods. Programmers use methods for reusability or keeping functionality encapsulated inside one object at a time. Attributes are defined in the class template and represent the state of an object. Objects will have data stored in the attributes field. Class attributes belong to the class itself. T. Zalizam T. Muda © 2023 + This image shows an example of the structure and naming in OOP. T. Zalizam T. Muda © 2023 +Object-oriented programming is based on the following principles: Encapsulation Abstraction Polymorphism Inheritance T. Zalizam T. Muda © 2023 Object-oriented programming +What are examples of object-oriented programming languages? While Simula is credited as being the first object-oriented programming language, many other programming languages are used with OOP today. But some programming languages pair with OOP better than others. For example, popular pure OOP languages include: Ruby Scala JADE Emerald Programming languages designed primarily for OOP include: Java Python C++ Other programming languages that pair with OOP include: Visual Basic.NET PHP JavaScript + Properties of Web Languages Object Oriented Languages(cont.) JavaScript, JScript, VBscript, Java, and C++ Instead of concentrating on the "processes" that are to be performed, you concentrate on the "classes" and "classes-of-objects" that make up the entities that are manipulated by your program. Procedure oriented programmers may have a difficult time making the transition to OOP, especially as OOP usually takes more time in the design phase, and the solutions are often more general then they need be. But the code is usually much more reusable, robust, and easier to modify and extend. T. Zalizam T. Muda © 2023 + What are the benefits of OOP? Benefits of OOP include: Modularity. Encapsulation enables objects to be self-contained, making troubleshooting and collaborative development easier. Reusability. Code can be reused through inheritance, meaning a team does not have to write the same code multiple times. Productivity. Programmers can construct new programs quicker through the use of multiple libraries and reusable code. Easily upgradable and scalable. Programmers can implement system functionalities independently. Interface descriptions. Descriptions of external systems are simple, due to message passing techniques that are used for objects communication. Security. Using encapsulation and abstraction, complex code is hidden, software maintenance is easier and internet protocols are protected. Flexibility. Polymorphism enables a single function to adapt to the class it is placed in. Different objects can also pass through the same interface. T. Zalizam T. Muda © 2023 + Criticism of OOP The object-oriented programming model has been criticized by developers for multiple reasons. The largest concern is that OOP overemphasizes the data component of software development and does not focus enough on computation or algorithms. Additionally, OOP code may be more complicated to write and take longer to compile. T. Zalizam T. Muda © 2023 + Web languages examples Client-side JavaScript JScript VBScript Tcl Cascading Style Sheets (Designing) HTML(Structure) DHTML AJAX jQuery TypeScript ActionScript React Angular Vue Swift SASS(Syntactically Awesome Style Sheet) Elm … T. Zalizam T. Muda © 2023 + Web languages examples Server-side Active Server Pages (ASP) Java Server Pages (JSP) ColdFusion IPTSCRAE Lasso MIVA Script PHP ASP.NET SMX XSLT Ruby Python Java Node.js PERL C# ... T. Zalizam T. Muda © 2023 + Programming T. Zalizam T. Muda © 2023 + Languages T. Zalizam T. Muda © 2023 + Future of Internet Computing Mobile GSM,2.5G,EDGE,3G, H+,4G, LTE, 5G, 6G WiMax Wireless Mesh Networks Wireless Sensor Networks Interactive/Multimedia 3D Virtual reality Haptic (sense of touch) Smell? Cyber-Physical Systems Telepresence Tele-Medicine/Tele-Surgery Unmanned transportation Robotics Assisted Living Grid computing Internet of Things More? T. Zalizam T. Muda © 2023 + Future of Internet Computing Mobile GSM,2.5G,EDGE,3G, H+,4G, LTE, 5G, 6G WiMax Wireless Mesh Networks Wireless Sensor Networks Interactive/Multimedia 3D Virtual reality Haptic (sense of touch) Smell? Cyber-Physical Systems Telepresence Tele-Medicine/Tele-Surgery Unmanned transportation Robotics Assisted Living Grid computing Internet of Things More? T. Zalizam T. Muda © 2023 + Introduction to the Internet TCP/IP is the communication protocol for the Internet. TCP/IP defines the rule computers must follow to communicate with each other over the internet. Your Browser and Server use TCP/IP Browsers and servers use TCP/IP to connect to the Internet. A browser uses TCP/IP to access a server. A server uses TCP/IP to send HTML back to a browser. Your E-Mail uses TCP/IP Your e-mail program uses TCP/IP to connect to the Internet for sending and receiving e-mails. Your Internet Address is TCP/IP Your Internet address "58.26.136.5" is a part of the standard TCP/IP protocol (and so is your domain name). T. Zalizam T. Muda © 2023 + Internet Protocol The Internet Protocol (IP) is a protocol used for communicating data across a packet-switched internetwork using the Internet Protocol Suite, also referred to as TCP/IP. IP is the primary protocol in the Internet Layer of the Internet Protocol Suite and has the task of delivering distinguished protocol datagrams (packets) from the source host to the destination host solely based on their addresses. IP address Same as a person name. Assigned as numeric address. IPv4 – 32-bit number Example: 131.123.35.92 128-bit address in IPv6. T. Zalizam T. Muda © 2023 + Internet Protocol IP : T. Zalizam T. Muda © 2023 + Internet Protocol IP : T. Zalizam T. Muda © 2023 + Internet Protocol The Internet Protocol (IP) T. Zalizam T. Muda © 2023 + Domain Names Textual names for machines on the Internet. Name of host machine called domain. They may be two, three or more domain names. The last domain name identifies the type of organisation. Example: www.uum.edu.my | www.nyu.edu | www.msn.com.sg www.yahoo.com | www.lancs.ac.uk | www.hu.ac.th www.jpa.gov.my | www.yahoo.co.uk | www.ugm.ac.id T. Zalizam T. Muda © 2023 + Domain Names T. Zalizam T. Muda © 2023 Domain Names Conversion from IP address (number) to domain name (textual) is done by name server. This implement Domain Name Server (DNS). Domain Name Internet Client System IP IP Name Internet Web Server Server T. Zalizam T. Muda © 2023 + World Wide Web Created by group led by Tim Berners Lee at CERN (Conseil European pour la Recherce Nucleaire) To allow scientists around the world to use the Internet to exchange documents and search and retrieve documents from database. Form of documents– hypertext. Which is text with embedded links to text in other documents. WWW simply known “The Web”. “the Web” – vast collection of documents some of which are connected by links. This documents accessed by Web Browsers and are provided Web Servers. T. Zalizam T. Muda © 2023 + Internet vs Web Bear in mind, a collection of computers and other devices connected by equipment that allows them to communicate with each other. collection of software and protocols that has been installed on most, if not all, of the computers on the Internet. Therefore; Internet and Web is not the same thing!!! WEB >are the pages you see when you're at a device and you're online. T. Zalizam T. Muda © 2023 + Terminologies Client Server Web Browser Web Server URL HTTP T. Zalizam T. Muda © 2023 + Client & Server Client: initiates communication Server: send information's back to client. Browser Program running at client. Allow users to browse the resources available at servers. Text browser (no graphic) – 1993 Mosaic: The first browser with GUI. Common protocols is HTTP (Hypertext Transfer Protocol) HTTP provide standard form of communications between browsers and Web servers. Example: ???? T. Zalizam T. Muda © 2023 + Web Servers Programs that provide documents to requesting browsers. Most common Web servers: Apache and IIS. 2 separate directories: Document root: stores web page. Server root: stores the server and support software. Web server can interact with database system through CGI (Common Gateway Interface) and server-side script. Other protocols supported by Web servers FTP, Gopher, News and mail T. Zalizam T. Muda © 2023 Web Server & Web Browser In Action 1. Type the URL in Web Browser 5. Close the connection www.uum.edu.my 4. Send the information's 2. Sending URL (documents or program) to initiate a connection. Internet Browser Server 2. Sending URL (documents or program) to initiate a connection 4. Send the information's 3. Accept incoming connection through specific port. T. Zalizam T. Muda © 2023 + URL – Uniform Resource Locators To identify documents (resources) on the Internet. URL format Scheme: object address Scheme is a communication protocols. http, ftp, gopher, telnet, file, mailto and news. Default web server port number is 80. URL paths: http://www.uum.edu.my http://www.google.com http://www.nytimes.com T. Zalizam T. Muda © 2023 + Uniform Resource Locater (URL) Domain Name http://www.uum.edu.my Location Indicates the protocol the browser will use to Function retrieve the page Host Computer T. Zalizam T. Muda © 2023 + HTTP (Hypertext Transfer Protocol) As communication transactions Formally defined as RFC 2616 Consists 2 phases: Request Response Each HTTP communication (request & response between browser and web server consist 2 parts: Header: information about the communication Body: the data of the communication T. Zalizam T. Muda © 2023 + Markup languages Markup languages, such as HTML, DHTML, HTML4.0, HTML5 XML, XSL, and CSS (Cascading Style Sheets) have a major effect on the role of web languages As these markup languages develop they give more and more power to the client side web languages, such as JavaScript. T. Zalizam T. Muda © 2023 + Markup languages characterization Hypertext Markup Language (HTML) Specifies How a document shall be presented How documents cross-reference each other (hyperlinks) Why HTML succeeds? Open and free standard Simple tag markups for hyperlinks. Simple, standard, and platform independent ASCII characters. Only needs open, free, and simple text editors for editing and publishing. Platform independent for publishing and presentation. Simple and easy to learn. T. Zalizam T. Muda © 2023 + Markup languages characterization HTML 5.0: https://en.wikipedia.org/wiki/HTML5 T. Zalizam T. Muda © 2023 + Markup languages characterization CSS: Cascading Style Sheets make possible the "D" in "Dynamic" HTML Style sheets let user define a set of characteristics for a group of HTML elements, such as color, font, position, and visibility. T. Zalizam T. Muda © 2023 + Markup languages characterisation eXtensible Markup Language (XML): the newest markup language. Unlike HTML which is concerned with appearances only, XML is concerned almost wholly with content as opposed to form. Thus the tags identify information that is relevant to a particular discipline Tagging information this way has many advantages: client side languages will have much more information that they can manipulate in meaningful ways The combination of this tagging information and a client language should greatly enhance interaction, reduce the load on the Internet (since most interactions take place on the client) and make information much more retrievable XML is available in most browsers. T. Zalizam T. Muda © 2023 + Markup languages characterisation Extensible Stylesheet Language (XSL) XSL is mostly concerned with the appearance of XML documents. By separating the content and the appearance, XSL makes it easy to render the XML document in many different formats, such as text, images, speech, or control over equipment. T. Zalizam T. Muda © 2023 + Markup languages characterisation XHTML XHTML is essentially HTML 4 which conforms to the very strict syntax required by XML. For example, all beginning tags must have ending tags, so that must be balanced by an tag, and all tags must be lower case. Following such rules greatly increasing the portability of HTML code. T. Zalizam T. Muda © 2023 + World Wide Web Consortium (W3C) Founded: October 1994 – Tim Berners-Lee Organisation called W3C Goal: to make the Web universally accessible- regardless of disability, language or culture Standardisation organisation for Web tech. Recommendations – doc. That specifies tech’s role, syntax, rules etc. E.g: XHTML, CSS, HTML, XML T. Zalizam T. Muda © 2023 + Network Architecture Network architecture is the design of a communication network. It is a framework for the specification of a network's physical components and their functional organization and configuration, its operational principles and procedures, as well as data formats used. In telecommunication, the specification of a network architecture may also include a detailed description of products and services delivered via a communications network, as well as detailed rate and billing structures under which services are compensated. T. Zalizam T. Muda © 2023 + OSI Network Model Open Systems Interconnection Model PDNTSPA http://en.wikipedia.org/wiki/Network_architecture T. Zalizam T. Muda © 2023 + Summary Programming language: Machine, assembly & high-level The Internet began in 1960s as the Arpanet. The Web began in 1980s as CERN Two kind of addresses: IP address & DNS Browser: to browse resources at server Web Server: provide resources to browser URL: identify resources on the Internet HTTP: communication protocol Network Architecture T. Zalizam T. Muda © 2023 + T. Zalizam T. Muda © 2023 Objectives, at the end of this lecture, students will be able to: – Define HTML and explain the use of HTML tags, table, form and frame – Create the simple HTML document – Create HTML document with table HTML the main language of the WWW Web server is used to communicate the page structure to the browser Web Browser is used to render pages HTML defines only the structure of a page Cascading Style Sheet for the page styles An HTML file is a text file containing small markup tags. The markup tags tell the Web Browser how to display the page An HTML file must have an htm or html file extension An HTML file can be created using a simple text editor such as notepad in Windows HTML documents are text files made up of HTML elements. HTML elements are defined using HTML tags. HTML tags are used to mark-up HTML elements HTML tags are surrounded by the two characters < and > which are called angle brackets HTML tags normally come in pairs like and where the first is the start tag, the second tag is the end tag The text between the start and end tags is the element content HTML tags are not case sensitive, means the same as , but in HTML5, all tags must be in lower case Tag Description Defines an HTML document Defines the document's body to Defines header 1 to header 6 Defines a paragraph Inserts a single line break Defines a horizontal rule Defines a comment HTML element is the root element of the document = contains all other elements HTML elements begin with and ends with : Untitled Page HTML documents have TWO parts: – Head : contains document title. – Body: contains the information. Head Element your title Body Element your information An element in HTML represent a structure. Consists of a start tag, content and end tag Example: – = this is a sample start tag – = this is a sample start tag with an attribute. – = this is a sample end tag – Welcome = this is div element – = this is empty element. It uses a self-closing element Title of page This is my first homepage. This text is bold Largest Heading h2 size h3 size h4 size h5 size Smallest Heading This is a paragraph (line break) (horizontal rule) This text is preformatted Please take note… Contoh kenderaan : basikal, kereta dan motor Contoh kenderaan : basikal, kereta dan motor Contoh kenderaan : basikal, kereta dan motor Logical Styles This text is emphasized This text is strong This is some computer code HTML Text Elements Physical Styles This text is bold This text is italic HTML Image HTML Links, Anchors, and Image Elements This is a Link Send e-mail A named anchor: Useful Tips Section Jump to the Useful Tips Section HTML Links, Anchors, and Image Elements The target Attribute The target attribute defines where the linked document will be opened. – The code below will open the document in a new browser window: Visit W3Schools! – The code below will open the document in the current active window Visit W3Schools! HTML Unordered List First item Next item HTML Ordered List First item Next item HTML Definition list First term Definition Next term Definition Table Table – Organize data into rows and columns – All tags and text that apply to the table go inside … tags – TABLE element Attributes – BORDER lets you set the width of the table’s border in pixels – ALIGN: left, right or center – WIDTH: pixels (absolute) or a percentage Table TABLE element – …… Table row element used for formatting the cells of individual rows – …… column contents table.html Firstname Lastname Age Natasha Amin 20 Anne Jackson 44 Ravi Chandran 24 Sliced image in a borderless table Aligning with table  It’s easy to align web elements in a table.  Use table only for simple web layout.  However, making page layout with table is inappropriate  Tables are Inflexible  Nested Tables Load More Slowly  Tables Hurt Search Engine Optimization  Tables do not Always Print Well  Use CSS instead! Entities (Special Characters) &lt; is the same as < &gt; is the same as > &#169; is the same as © Other Elements Text quoted from some source. Address 1 Address 2 City Resources Forms : URL : http://www.cwru.edu/help/interHTML/ch8.html HTML http://www.w3schools.com/html/default.asp C Client Side Script : HTML Form Objectives, at the end of this lecture, students will be able to: Create HTML document form Form Collect information from people viewing your site FORM element HTTP METHOD attribute indicates the way the Web server will organize and send the output METHOD = “post” submits data to be processed to a specified resource METHOD = “get” requests data from a specified resource ACTION attribute Path to a script (CGI / ASP/PHP/PY scripts) This script will process the data GET vs. POST GET POST Restrictions on Yes, when sending data, the No restrictions data length GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters) Restrictions on Only ASCII characters allowed No restrictions. Binary data data type is also allowed Security GET is less secure compared to POST is a little safer than POST because data sent is part GET because the of the URL parameters are not stored Never use GET when sending in browser history or in web passwords or other sensitive server logs information! Visibility Data is visible to everyone in the Data is not displayed in the URL URL INPUT ELEMENTS Text Box Password Box Radio Buttons Check boxes Text Box A box in which anything can be typed ( e.g: letters, numbers) via the keyboard. Default size : 20 characters Markup: Linux UNIX SELECT Create a pop-up list from which any one option may be selected. Advantage: little screen space for list options. Markup: How are you reaching this page? U Mobile UNIFI Maxis CelcomDigi WIFI Multiple selections Select more than one : use attribute MULTIPLE Display many options : use attribute SIZE Markup: How are you reaching this page? U Mobile UNIFI Maxis CelcomDigi WIFI Text Area To create a box where the user may type large amounts of text Markup: Hidden INPUT Allows an input which is hidden from the user Programmers used this input for special programming purposes. Markup: SUBMIT & RESET TYPE = “submit” inserts a button that submits data to the server VALUE attribute changes the text displayed on the button (default is “Submit”) TYPE = “reset” inserts a button that clears all entries the user entered into the form VALUE attribute changes the text displayed on the button (default is “Reset”) SUBMIT & RESET Markup:... http://www.w3schools.com/css/css_intro.asp CSS Syntax  The Selector selects elements on the HTML page  The associated Style Block applies its Style Values to the selected Element’s Properties CSS Syntax  The Selector selects elements on the HTML page  The associated Style Block applies its Style Values to the selected Element’s Properties. . How to Insert CSS into HTML  There are three ways of inserting a style sheet: 1. External style sheet 2. Internal style sheet 3. Inline style How to Insert CSS into HTML 1. External Style Sheet An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the tag. The tag goes inside the head section: >> is called primary prompt STIV3013 WWW Programming | by T Zalizam © 2024  Try these exercises by typing each command at Interactive the primary prompt and hitting enter: 1. 1 + 2 Interpreter 2. 4*5 (Exercises) 3. 14/5 4. 14//5 5. 14%5 6. x = “Hello” 7. y = “There” 8. print(x+y) 9. print(x,y) 10. print(x,y, sep=‘-’) 11. csv = “one, two, three” 12. lst = csv.split(‘ , ’) 13. lst STIV3013 WWW Programming | by T Zalizam © 2024 Interactive Interpreter (Exercises) https://www.pythonanywhere.com/ STIV3013 WWW Programming | by T Zalizam © 2024 PYTHON BASICS PART 2 WWW Programming | © T Zalizam T Muda TOC  STRINGS  FORMATTING STRINGS  LISTS, DICTIONARIES AND TUPLES  THE IF STATEMENT AND CODE BRANCHING  LOOPS AND ITERATORS  CATCHING ERRORS  CLASSES AND FUNCTIONS WWW Programming | © T Zalizam T Muda STRINGS A string is a sequence of one or more characters – “a” is a string, ”Hello There” is a string, if you were silly enough to load it all into a single variable. This whole slides could be a string. String characters don’t have to be printable – a string can contain any Unicode character. Strings are immutable. An immutable object cannot be changed after it’s created. We will talk more about immutable and mutable objects when we cover lists, tuples and dictionaries. To create a string, you enclose the string in single or double quotes: x = ‘Hello’ y = “There" WWW Programming | © T Zalizam T Muda STRINGS-1 Unlike some other programming languages, Python treats single quotes and double quotes the same. The only time it matters if you use single or double quotes is if there are quotes in the string: a = ‘This doesn’t work’. #BAD, will break on #quote in “doesn’t” b = “Wasn’t that easy” #GOOD c = ‘ “Air quotes” are silly’ # Also GOOD If there are multiple quotes in the string, you must escape the quotes with a backslash (\): d = “ Aren’t quotes \”fun\”?” WWW Programming | © T Zalizam T Muda STRINGS-2 Strings are a special class built into Python, with many class methods available for working with them. Here are a few examples using the Python interactive interpreter: >>> “hello”.capitalize() # Manipulate a string directly ‘Hello’ # Capitalize string >>> “hello”.upper() # Uppercase string ‘HELLO’ >>> greet = “Hello There” # Work with string variable >>> greet # String indexing ‘H’ # First character >>> greet ‘T’ # Seventh character WWW Programming | © T Zalizam T Muda STRINGS-3 >>> greet[:4] # String slicing ‘Hell’ # First four characters >>> greet[len(greet)-4:] ‘here’ # Last four characters >>> greet[::-1] # Reverse a string ‘erehT olleH’ >>> padded = “ My name is Zam ” >>> padded.lstrip() ‘My name is Zam ‘ # Removing whitespace >>> padded.rstrip() ‘ My name is Zam’ WWW Programming | © T Zalizam T Muda STRINGS-4 >>> greet.replace(‘e’, ’_’) # Replacing characters ‘H_llo Th_r_’ # in a string >>> greet.split() # Splitting strings [‘Hello’, ‘There’] # Default split is space >>> greet.split(‘e’) # But can split on # anything [‘H’, ‘llo Th’, ‘r’, ‘ ‘] >>> WWW Programming | © T Zalizam T Muda FORMATTING STRINGS Another useful thing you can do with string is to use string interpolation to substitute values into a formatted string. This is better explained with an example. Try this at the Python prompt: >>> “There are %s apples left” % ‘four’ String interpolation is performed with the modulo (%) operator and takes the form: format % values So, when you enter the above code, Pyhton replaces the strong placeholder (%s) with a string “four”. When you hit Enter, Python prints out: ‘There are four apples left’ This works on multiple substitution, however, multiple substitutions, the values must be passed in as a tuple(more on tuples soon): >>> “There are %s apples and %s oranges left” % (‘four’, ‘two’) ‘There are four apples and two oranges left’ WWW Programming | © T Zalizam T Muda FORMATTING STRINGS-1 String formatting will substitute numbers as well. For example, %i will insert an integer: >>> “There are %i apples and %i oranges left” % (2, 7) ‘There are 2 apples and 7 oranges left’ >>> Other format strings include: %x – A signed hexadecimal(uppercase) %f – A floating-point decimal %c – A single character WWW Programming | © T Zalizam T Muda LISTS, TUPLES AND DICTIONARIES  used to store collections of objects  differentiated from each other by the delimiters they use: [ ] – A list – e.g : [‘one’, ‘two’, ‘three’, ‘four’]  Lists you should be familiar with, as we all use lists daily.  Lists are designed to contain largely homogeneous data, much like in real life where you would have a shopping list or a to-do list.  By convention, Python list items should all be the same type (although Python doesn’t enforce this rule) { } – A dictionary – e.g : (1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’)  A dictionary is also straight fwd – think of a regular dictionary where you have the word followed by the definition of the word.  In Python, the word is called a key and the definition a value. WWW Programming | © T Zalizam T Muda LISTS, TUPLES AND DICTIONARIES-1  cont. ( ) – A tuple – e.g : (‘one’, 2, [three]) Unlike lists, tuples are used to store heterogeneous data – (“one”, 2, [three]) is perfectly acceptable as a tuple, where it would be frowned upon as a list. A single element tuple (singleton) is also written differently to a single element list: lst = [‘one’] # 1 element list tpl = (‘one’,) # 1 element tuple with trailing comma # to differentiate between # a plain string (‘one’) or a # functions parameter some_func(‘one’) WWW Programming | © T Zalizam T Muda  cont. LISTS, TUPLES AND DICTIONARIES-2 ( ) – A tuple – e.g : (‘one’, 2, [three]) Unlike lists, tuples are used to store heterogeneous data – (“one”, 2, [three]) is perfectly acceptable as a tuple, where it would be frowned upon as a list. A single element tuple (singleton) is also written differently to a single element list: lst = [‘one’] # 1 element list tpl = (‘one’,) # 1 element tuple with trailing comma # to differentiate between # a plain string (‘one’) or a # functions parameter some_func(‘one’) Tuples, like strings, are immutable; they can’t be changed once created. Lists and dictionaries, however, are mutable and can be changed. WWW Programming | © T Zalizam T Muda LISTS, TUPLES AND DICTIONARIES-3  Examples: >>> lst = [‘one’] # Set up a list, tuple and dictionary >>> tpl = (‘one’,) >>> dict= {0: ‘one’} >>> lst ‘one’ >>> tpl ‘one’ >>> dict ‘one’ WWW Programming | © T Zalizam T Muda  cont. LISTS, TUPLES AND DICTIONARIES-4 >>> lst = ‘two’ # List is mutable (can be changed) >>> lst [‘two’] >>> dict = ‘two’ # So is the dictionary >>> dict {0: ‘two’} >>> tpl = ‘two’ # Tuple is immutable. Can’t be changed! Traceback……….. error >>> str = ‘one’ # String is also immutable >>> str = ‘x’ Traceback…….. error WWW Programming | © T Zalizam T Muda THE IF STATEMENT AND CODE BRANCHING  Python, like most programming languages, has an if statement to provide branching in code. The syntax of Python’s if statement is: if [expression is True] : # execute this code when True else: # execute this code when False  The else branch is optional: if [expression is True]: # only executes when True # resume code execution WWW Programming | © T Zalizam T Muda THE IF STATEMENT AND CODE BRANCHING-1  The expression can be anything that executes to True or False.  A few examples: 1. if num >= 10: 2. if str == “Hello”: 3. if this != that: 4. if SomeVar: …….. and so on. *Note example 4 above – in Python, anything that does not equate to zero, Null, or empty object is True. WWW Programming | © T Zalizam T Muda THE IF STATEMENT AND CODE BRANCHING-2  For example: >>> s = 0 >>> if s: … print(‘True’) … # Python returns nothing – statement is false >>> s = 1 >>> if s: … print(‘True’) … True WWW Programming | © T Zalizam T Muda THE IF STATEMENT AND CODE BRANCHING-3  For example: cont. >>> s = ‘ ‘ >>> if s: … print(‘True’) … # Nothing again – statement is false >>> s = ‘Hello’ >>> if s: … print(‘True’) … True WWW Programming | © T Zalizam T Muda THE IF STATEMENT AND CODE BRANCHING-4  Python includes a comprehensive range of Boolean operators you can use with your expression: < >= == != is ~ Is a particular object is not ~ Isn’t a particular object WWW Programming | © T Zalizam T Muda THE IF STATEMENT AND CODE BRANCHING-5  Python also supports Boolean operations for negating and chaining expressions:  or ~ Either expression can be True  and ~ Both expression must be True  not ~ Negate the proceeding expression Python also supports multiple branching using elif (short for “else if”) statement: if [exp1 is True]: # execute if exp1 is True elif [exp2 is True]: # execute if exp2 is true # and so on …. WWW Programming | © T Zalizam T Muda LOOPS AND ITERATORS  Loops and iterators do the same basic thing – repeat a section of code until some condition is met.  With a loop, the repetition can be any arbitrary code sequence, whereas an iterator steps through an iterable object.  An iterable object is an object that can be indexed (stepped through) sequentially. The most common iterable types in Python are the sequence types – strings, lists, tuples and ranges. WWW Programming | © T Zalizam T Muda THE WHILE LOOPS  To create a program loop in Python, you use the while statement.  For example, here is an elementary loop: a=1 while a < 5: print(a) a += 1 Output 1 2 3 4 WWW Programming | © T Zalizam T Muda THE WHILE LOOPS-1  Python’s while loops are handy for much more than simple task like printing out a variable.  For example, the factorial (!) of any number is the multiplication of the number with all the preceding integers (so 4! Is equal to 1*2*3*4). Here’s how to calculate the factorial of 9 with while loop: fact, mul = 1, 2 # Multiple assignment while mul < 10: fact, mul = fact * mul, mul + 1 print(fact) WWW Programming | © T Zalizam T Muda BREAKING OUT OF LOOPS  The break and continue statements allow you to exit a loop before the loop condition is met. Consider the following code: a, b = 1, 1 # Multiple assignment while a < 5: print(“a =“, a) a += 1 while b < 5: print(“b =“, b) if b == 2: b=1 break b += 1 WWW Programming | © T Zalizam T Muda BREAKING OUT OF LOOPS-1  The continue statement, won’t execute any of the code after the continue, instead it jumps to the next iteration of the loop. Consider the following code: a=0 while a < 5: a += 1 if a == 3: print (‘My favorite number is ‘, a) continue print(‘a =‘, a)  The break and continue statements can also be used inside a for loop. WWW Programming | © T Zalizam T Muda ITERATING WITH A FOR LOOP  The for loop is designed to step through an iterable item.  It takes the basic form: for [item] in [iterable]:  As mentioned earlier in the chapter, the most common iterables are strings, lists, tuples and ranges. Here are some example: word = ‘Hello’ for char in word: # Step through each character in the word print(char) WWW Programming | © T Zalizam T Muda ITERATING WITH A FOR LOOP-1  cont. lst = [‘1’, ‘2’, ‘3’] # Step through each item in the list for item in lst: print(item) cont. tup = (1,’two’, 3) # Step through each item in the tuple for item in tup: print(item) WWW Programming | © T Zalizam T Muda ITERATING WITH A FOR LOOP-2  cont. for i in range(5): # The range function provides you print(i) # with a sequence of integers WWW Programming | © T Zalizam T Muda CATCHING ERRORS  Examples: ans = 3 ans = ans/5 print(‘Answer divided by 5 is ‘, ans) Output Answer divided by 5 is 0.6 _______________________________ answer = ‘3’ ans = 5/answer Output …..error msg WWW Programming | © T Zalizam T Muda CATCHING ERRORS-1 >>> answer = ‘3’ >>> try: ans = answer/5 print(‘Answer divided by 5 is ‘, ans) except: print(‘something went wrong’) … Something went wrong WWW Programming | © T Zalizam T Muda CATCHING ERRORS-3 >>> answer = ‘3’ >>> try: ans = answer/5 print(‘Answer divided by 5 is ‘, ans) except: print(‘Type Error. Answer must be an integer.’) … Type Error. Answer must be an integer. WWW Programming | © T Zalizam T Muda CLASSES AND FUNCTIONS  The primary purpose of classes and functions is to group pieces of related code.  The major difference between the two is a function does something whereas a class is something.  For example, if Person was a class, walk() and eat() would be functions.  Both classes and functions can contain other functions.  If a function is inside another function. It’s called a sub-function.  If a function is included inside a class, it’s called a method.  Subclasses also exist, but they are created by a process called inheritance. WWW Programming | © T Zalizam T Muda CLASSES AND FUNCTIONS-1  To define a function in Python, you use the def statement: def function_name([parameter list]): # rest of function To define a class in Python, you use the class statement: class Someclass([argument list]): # Class constructor _ _init_ _() : # Constructor code # Class methods def … WWW Programming | © T Zalizam T Muda CLASSES AND FUNCTIONS-2  You create subclasses that contain all the attributes and methods of another class using inheritance.  Inheritance is an important concept in object-oriented programming.  Inheritance helps prevent repetition in code, and it allows programmers to build complex programs from simpler building blocks.  To create a class that inherits from another class, you refer to the parent when defining the class: class ChildClass(ParentClass): WWW Programming | © T Zalizam T Muda Q&A WWW Programming | © T Zalizam T Muda STIV3013 WWW PROGRAMMING (The Web) Server Side Script Database + MySQL STIV3013 WWW Programming | T Zalizam © 2021 Database & Structured Query Language (SQL) Objectives – To define database, DBMS, table, field and record – To give basic knowledge relational database model – To understand the MySQL database server STIV3013 WWW Programming | T Zalizam © 2021 Introduction Database – Integrated collection of data Database management system (DBMS) – Provides mechanisms for storing and organizing data – Allows users to access and store data without addressing internal representation of databases Relational databases – Consist of data corresponding to one another – Most popular database systems in use – Uses Structured Query Language (SQL) to create queries – Examples: Oracle, MS SQL Server, MySQL, Informix STIV3013 WWW Programming | T Zalizam © 2021 Introduction-1 In a database system, the data that describe a specific entity (such as a member of a society, a stock item, etc.) are stored in a record. Records are stored in a table or file. A table is usually visualised as a rectangular display of data values as rows (records) and columns (fields). A record consists of one or more fields. Each field represents an attribute of the entity represented by the record. STIV3013 WWW Programming | T Zalizam © 2021 Relational Database Overview STIV3013 WWW Programming | T Zalizam © 2021 Relational Database Overview-1 Microsoft Access diagram (Fig.1) – Illustrates relationships between tables in database – Lines represent table relationships – One-to-many relationship Example: line between Publishers and Titles tables Single publisher can have many books in Titles table Fig. 1 Table relationships in Books.mdb. STIV3013 WWW Programming | T Zalizam © 2021 Relational Database Overview-2 STIV3013 WWW Programming | T Zalizam © 2021 Relational Database Overview-3 Rule of Entity Integrity – Every record must have value in primary key field – Primary key values must be unique Foreign key field (or constraints) – References primary key field in another table – Specified when creating tables – Maintains Rule of Referential Integrity Every foreign key field value must appear in another table’s primary key field Example: PublisherID field in Titles table – Enables information from multiple tables to be joined for analysis STIV3013 WWW Programming | T Zalizam © 2021 Introduction to Structured Query Language (SQL) SQL is a standard computer language for accessing and manipulating databases. What is SQL? – SQL stands for Structured Query Language – SQL allows you to access a database – SQL is an ANSI standard computer language – SQL can execute queries against a database – SQL can retrieve data from a database – SQL can insert new records in a database – SQL can delete records from a database – SQL can update records in a database – SQL is easy to learn STIV3013 WWW Programming | T Zalizam © 2021 SQL Data Manipulation Language (DML) SQL (Structured Query Language) is a syntax for executing queries. But the SQL language also includes a syntax to update, insert, and delete records. These query and update commands together form the Data Manipulation Language (DML), part of SQL: – SELECT - extracts data from a database table – UPDATE - updates data in a database table – DELETE - deletes data from a database table – INSERT INTO - inserts new data into a database table STIV3013 WWW Programming | T Zalizam © 2021 SQL Data Definition Language (DDL) The Data Definition Language (DDL) part of SQL, permits database tables to be created or deleted. We can also define indexes (keys), specify links between tables, and impose constraints between database tables. The most important DDL statements in SQL are: – CREATE TABLE - creates a new database table – ALTER TABLE - alters (changes) a database table – DROP TABLE - deletes a database table – CREATE INDEX - creates an index (search key) – DROP INDEX - deletes an index STIV3013 WWW Programming | T Zalizam © 2021 Data Manipulation Language (DML) Overview SQL using Books.mdb database Following table lists some SQL keywords SQL keyw ord Desc rip tion SELECT Select (retrieve) fields from one or more tables. FROM Tables from which to get fields. Required in every SELECT. WHERE Criteria for selection that determine the rows to be retrieved. GROUP BY Criteria for grouping records. ORDER BY Criteria for ordering (sorting) records. INSERT INTO Insert values into one or more tables. Some databases do not require the SQL keyword INTO. UPDATE Update existing data in one or more tables. DELETE FROM Delete data from a specified table. Fig. 22.12 Some SQL q uery keyword s. STIV3013 WWW Programming | T Zalizam © 2021 Basic SELECT Query Extracts information from one or more tables Simplest form – SELECT * FROM TableName Asterisk (*) notifies query to select all rows and columns from table TableName specifies a table in database – Example: SELECT * FROM Authors Selecting specific fields – Replace asterisk (*) with field names – Example: SELECT AuthorID, LastName FROM Authors STIV3013 WWW Programming | T Zalizam © 2021 Basic SELECT Query SELECT AuthorID, LastName FROM Authors AuthorID LastName 1 Deitel 2 Deitel 3 Nieto 4 Steinbuhler Fig. 22.13 AuthorID and LastName from the Authors table. STIV3013 WWW Programming | T Zalizam © 2021 The SELECT DISTINCT Statement The DISTINCT keyword is used to return only distinct (different) values. The SELECT statement returns information from table columns. But what if we only want to select distinct elements? With SQL, all we need to do is to add a DISTINCT keyword to the SELECT statement: Syntax – SELECT DISTINCT column_name(s) FROM table_name STIV3013 WWW Programming | T Zalizam © 2021 The SELECT DISTINCT Statement Orders table: Company OrderNumber Sega 3412 W3Schools 2312 Trio 4678 W3Schools 6798 SELECT DISTINCT Company FROM Orders Company Sega W3Schools Trio – "W3Schools" is listed only once in the result-set STIV3013 WWW Programming | T Zalizam © 2021 WHERE Clause Optional clause in SELECT query Selects records satisfying selection criteria Basic form – SELECT fieldName1, fieldName2 FROM TableName WHERE criteria – Example: SELECT * FROM Authors WHERE YearBorn > 1960 Result set contains two authors born after 1960 AuthorID FirstName LastName YearBorn 2 Paul Deitel 1968 3 Tem Nieto 1969 Fig. 22.14 Authors from the Authors table born after 1960. STIV3013 WWW Programming | T Zalizam © 2021 WHERE Clause-1 Can contain operators – , =, =, and LIKE LIKE operator – Performs pattern matching with wildcard characters asterisk (*) and question mark (?) – Pattern matching allows SQL to search for particular string or string of characters – Asterisk (*) indicates string can have zero or more characters at it’s position STIV3013 WWW Programming | T Zalizam © 2021 WHERE Clause-2 Example: SELECT AuthorID, FirstName, LastName, YearBorn FROM Authors WHERE LastName LIKE ‘D*’ Result set contains two records AuthorID FirstName LastName YearBorn 1 Harvey Deitel 1946 2 Paul Deitel 1968 Fig. 22.15 Authors from the Authors table whose last names start with D. STIV3013 WWW Programming | T Zalizam © 2021 WHERE Clause-3 LIKE operator, cont. – Question mark (?) indicates single character can occupy it’s position Example: SELECT AuthorID, FirstName, LastName, YearBorn FROM Authors WHERE LastName LIKE ‘?i*’ – Result set contains one author AuthorID FirstName LastName YearBorn 3 Tem Nieto 1969 Fig. 22.16 Authors from the Authors table whose last names contain i as the second letter. STIV3013 WWW Programming | T Zalizam © 2021 WHERE Clause-4 Specifying range of characters – Use [startValue-endValue] startValue is first character in range endValue is last character in range STIV3013 WWW Programming | T Zalizam © 2021 ORDER BY Clause ISBN Title EditionNumber Year Pub lisher ID Published 0-13-089572-5 C How to Program 3 2001 1 0-13-089571-7 C++ How to Program 3 2001 1 0-13-528910-6 C++ How to Program 2 1997 1 0-13-028419-X e-Business and e-Commerce How to 1 2001 1 Program 0-13-016143-8 Internet and World Wide Web How to 1 1999 1 Program 0-13-012507-5 Java How to Program 3 1999 1 0-13-028418-1 Perl How to Program 1 2001 1 0-13-456955-5 Visual Basic 6 How to Program 1 1998 1 0-13-028417-3 XML How to Program 1 2001 1 Fig. 22.22 Portion of the b ooks from the Titles ta b le whose titles end with How to Program, sorted in a sc end ing ord er b y Title. STIV3013 WWW Programming | T Zalizam © 2021 Inserting a Record Use INSERT INTO operation Basic Form – INSERT INTO TableName (fieldName1, fieldName2) VALUES (value1, value2) TableName specifies table that receives new records Comma-separated list of field names specify the fields of TableName – Specifies columns that receive new records VALUES specifies data to be inserted into table – Example: INSERT INTO Authors (FirstName, LastName, YearBorn) VALUES (‘Sue’, ‘Smith’, 1960) Inserts three values into three columns of Authors table STIV3013 WWW Programming | T Zalizam © 2021 Inserting a Record-1 AuthorID FirstName LastName YearBorn 1 Harvey Deitel 1946 2 Paul Deitel 1968 3 Tem Nieto 1969 4 Kate Steinbuhler 5 Sue Smith 1960 Fig. 22.24 Authors table after an INSERT INTO operation to add a rec ord. STIV3013 WWW Programming | T Zalizam © 2021 Updating a Record Modifies data in tables (updates records) Basic form: – UPDATE TableName SET fieldName = value1 WHERE criteria SET assigns values to certain fields – Example: UPDATE Authors SET YearBorn = ‘1969’ WHERE LastName = ‘Deitel’ AND FirstName = ‘Paul’ AND states all components of selection criteria must be satisfied Can replace WHERE clause with WHERE AuthorID = 2 STIV3013 WWW Programming | T Zalizam © 2021 Updating a Record-1 AuthorID FirstName LastName YearBorn 1 Harvey Deitel 1946 2 Paul Deitel 1969 3 Tem Nieto 1969 4 Kate Steinbuhler 5 Sue Smith 1960 Fig. 22.25 Authors table after an UPDATE operation to modify a rec ord. STIV3013 WWW Programming | T Zalizam © 2021 DELETE FROM Statement Removes data from tables Basic form – DELETE FROM TableName WHERE criteria – Example: DELETE FROM Authors WHERE LastName = ‘Smith’ AND FirstName = ‘Sue’ Can replace WHERE clause with WHERE AuthorID = 5 AuthorID FirstName LastName Yea rBorn 1 Harvey Deitel 1946 2 Paul Deitel 1969 3 Tem Nieto 1969 4 Kate Steinbuhler Fig. 22.26 Ta b le Authors a fter a DELETE op era tion to remove a rec ord. STIV3013 WWW Programming | T Zalizam © 2021 MySQL Pronounced “My Ess Que Ell” Robust and scalable RDBMS Multi-user, multithreaded server – Performs multiple commands concurrently Uses SQL to interact with data Supports various programming languages – C, C++, Java, Python, Perl, PHP, etc Supports various operating systems – Windows, MacOS, Linux and Unix Access multiple databases with single query STIV3013 WWW Programming | T Zalizam © 2021 Introduction to Database Interface (DBI) Databases part of distributed applications – Divides work across multiple computers Retrieves result set and displays results Driver – Helps programs access databases – Each can have different syntax – Each database requires its own driver Interface – Provides uniform access to all database systems Database interface – Programmatic library for accessing relational database STIV3013 WWW Programming | T Zalizam © 2021 Example: Python + HTML STIV3013 WWW Programming | T Zalizam © 2021 Example: Python + HTML-1 STIV3013 WWW Programming | T Zalizam © 2021 STIV3013 WWW Programming | T Zalizam © 2021 STIV3013 WWW Programming | T Zalizam © 2021 OUTLINES Input Form HTML Insert Data View Data Delete Data Update Data STIV3013 WWW Programming | T Zalizam © 2021 Search Data Input Form HTML : Examples STIV3013 WWW Programming | T Zalizam © 2021 WWW Root Folder : htdocs C:\xampp\htdocs STIV3013 WWW Programming | T Zalizam © 2021 WWW Root Folder : htdocs STIV3013 WWW Programming | T Zalizam © 2021 WWW Root Folder : htdocs C:\python38\Scripts>python –m pip install mysql-connector-python WWW Root Folder : htdocs STIV3013 WWW Programming | T Zalizam © 2021 STIV3013 WWW Programming | T Zalizam © 2021 WWW Root Folder : htdocs STIV3013 WWW Programming | T Zalizam © 2021 STIV3013 WWW Programming | T Zalizam © 2021 STIV3013 WWW Programming | T Zalizam © 2021 Don’t forget to add “.py” inside xampp server file configuration STIV3013 WWW Programming | T Zalizam © 2021 modify file on Apache (httpd.conf) STIV3013 WWW Programming | T Zalizam © 2021 find the word “addhandler” STIV3013 WWW Programming | T Zalizam © 2021 add the python-type file “ py” and save Restart Xampp STIV3013 WWW Programming | T Zalizam © 2021 12 WEB APPLICATION DEVELOPMENT Server Side Script (Python): Database Integration WWW Programming | T Zalizam © 2025 Web Application Development – Database Integration  At the end of this lecture, student will be able to:  explain the advantages of using database to store web data;  prepare a MySQL database for using with Python;  establish a connection with MySQL server;  use SQL commands to MySQL;  use simple database query such as insert, select, update, delete data using Python;  prepare formatted data display in web browser. WWW Programming | T Zalizam © 2025 Advantages of using database to store web data  Faster access:  database system can generally search through large amounts of data much faster than using data files.  Better concurrent access:  web applications that use databases can often handle more concurrent users than applications that use files from data storage. WWW Programming | T Zalizam © 2025 Advantages of using database to store web data-1  Easier changes to data and scripts:  Python scripts that use a database access the data through a specially defined database query language, so changes in data elements have less of an effect on the Python scripts that access the data.  Increased security:  database systems often use a separate user ID and password mechanism so that only scripts with proper user ID and password can access the data. WWW Programming | T Zalizam © 2025 Python  Python has the built-in capability of working with a variety of database systems. The database that is most and popular with Python programmers is MySQL. MySQL  The two big reasons are Python+ MySQL is free; and the standard installation server has built-in functions that interface with MySQL under Xampp Server. WWW Programming | T Zalizam © 2025 Advantages and benefits of MySQL Connector Python  MySQL Connector Python is written in pure Python, and it is self-sufficient to execute database queries through Python.  It is an official Oracle- supported driver to work with MySQL and Python.  It is Python 3 compatible, actively maintained. WWW Programming | T Zalizam © 2025 How to  Let’s see how to connect the MySQL database in Python connect using the ‘MySQL Connector Python’ module. MySQL  Arguments required to connect database  You need to know the following in Python detail of the MySQL server to perform the connection from Python. WWW Programming | T Zalizam © 2025 Arguments required to connect  127.0.0.1 WWW Programming | T Zalizam © 2025 How to Connect to MySQL Database in Python  WWW Programming | T Zalizam © 2025 How to Connect to MySQL Database in Py 2 3  4 5 6 7 p_view.py WWW Programming | T Zalizam © 2025 How to Connect to MySQL Database in Python  use cursor.close() and connection.close () , WWW Programming | T Zalizam © 2025 How to Connect to MySQL Database in Python  WWW Programming | T Zalizam © 2025  WWW Programming | T Zalizam © 2025  WWW Programming | T Zalizam © 2025 Accessing MySQL via Python To access MySQL from a Python script, follow the same four step process: – Step 1: Make a connection to the MySQL database server this requires that you specify the location of the database, plus a user name and password. – Step 2: Select the database within MySQL that you want to work with.  Example, select the “books.db” database – Step 3: Issue an SQL statement / create the query this could be any valid SQL statement e.g. SELECT, INSERT INTO, UPDATE, DELETE – Step 4: If you are issuing a SELECT statement, iterate through the result set and extract each record.  Example, extract specific fields in each record, and display as HTML. At each step, check for specific error conditions. If an error occurs, fail gracefully and inform the user of the problem. WWW Programming | T Zalizam © 2025 Step 1: Connect to MySQL To connect to MySQL, use the mysql.connector.connect function. mysql.connector.connect(address,database, user,password) address – IP address or host name of the computer where the MySQL server is actually running. for user_name/password, you can use "guest" or "root"/ "guest" or "" Example: conn = mysql.connector.connect(host='localhost', database='books.db', user='root', password='') WWW Programming | T Zalizam © 2025 Connection Errors The mysql.connect function is not guaranteed to work. o the database server might be down o the database server might be on a different machine o the network connection is down. o the mysql.connect function will return false, if the connection attempt fails. It is important to test for these types of errors so that we can report meaningful error messages to your users. To determine exactly what went wrong, we can use the mysql.error function. WWW Programming | T Zalizam © 2025 Step 2: Select a Database To select a specific database, use the cursor.execute("select database();") function. Example: if connection.is_connected(): db_Info = connection.get_server_info() print("Connected to MySQL Server version ", db_Info, "") cursor = connection.cursor() cursor.execute("select database();") WWW Programming | T Zalizam © 2025 Testing: Connect to MySQL & Select Database if connection.is_connected(): db_Info = connection.get_server_info() print("Connected to MySQL Server version ", db_Info, "") cursor = connection.cursor() cursor.execute("select database();") record = cursor.fetchone() print("You're connected to database: ", record,"") except Error as e: print("Error while connecting to MySQL", e) WWW Programming | T Zalizam © 2025 Step 3: Issue an SQL Statement To issue an SQL statement (e.g. SELECT, INSERT INTO, DELETE, UPDATE), use the mysql.query function. Example: cursor.execute('SELECT * FROM Authors’) WWW Programming | T Zalizam © 2025 Step 4:Iterate through the SQL Result Set If you have issued a SELECT statement, iterate through all the records in your result set. To do so, use the cursor.fetchall() function along with a loop. Example: data = cursor.fetchall() print(" AuthorID | FirstName | LastName | Year ") a=1 for row in data: print (a,"&emsp;" , row,"&emsp;" , row, "&emsp;" ,row,"&emsp;&emsp;" , row,"") a += 1 WWW Programming | T Zalizam © 2025 WWW Programming | T Zalizam © 2025 & WWW Programming | T Zalizam © 2025 13 Web Application Development Redirecting Page STIV3013 WWW Programming | T Zalizam © 2021 Redirecting Page Page redirection is a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. STIV3013 WWW Programming | T Zalizam © 2021 Example… list of tables STIV3013 WWW Programming | T Zalizam © 2021 Example of login STIV3013 WWW Programming | T Zalizam © 2021 Creating login STIV3013 WWW Programming | T Zalizam © 2021 Creating login STIV3013 WWW Programming | T Zalizam © 2021 Sample Output login STIV3013 WWW Programming | T Zalizam © 2021 1.Create db | 2.Table | 3. Insert a record STIV3013 WWW Programming | T Zalizam © 2021 4.Create Login Page html STIV3013 WWW Programming | T Zalizam © 2021 4.Create Login Process Python STIV3013 WWW Programming | T Zalizam © 2021 4.Create Login Process Python(cont.) STIV3013 WWW Programming | T Zalizam © 2021 Question? Redirecting Page STIV3013 WWW Programming | T Zalizam © 2021 Add on: + Time Duration + Manage Session You have been online for 2 hours 35 secs

Use Quizgecko on...
Browser
Browser