logo

Unit 3: Web Technology II (12 Hours)

Computer Science - Class 12

MCQ questions

Unit 3: Web Technology II (12 Hours)

3.1 Introduction

Web technology encompasses various tools, languages, and frameworks used to create and manage web applications and services. It includes both client-side and server-side technologies that work together to provide a seamless user experience on the web.

3.2 Server-Side and Client-Side Scripting

  • Client-Side Scripting: Scripts are executed in the user's browser, allowing for dynamic content and user interaction without needing to communicate with the server for every action. Common client-side scripting languages include:

    • JavaScript: The most widely used language for client-side scripting, allowing developers to create interactive web pages.

  • Server-Side Scripting: Scripts are executed on the server, generating dynamic content based on user requests before sending it to the client. Common server-side scripting languages include:

    • PHP: A popular language for server-side web development, often used in conjunction with databases.

3.3 Introduction of Internet Technology

Internet technology refers to the systems and protocols that facilitate communication and data exchange over the internet. It includes technologies such as:

  • HTML: Hypertext Markup Language used for creating and structuring web content.

  • CSS: Cascading Style Sheets used for styling HTML content.

  • JavaScript: Used to add interactivity and dynamic elements to web pages.

3.4 Adding JavaScript to HTML Page

JavaScript can be added to an HTML page in two main ways:

  • Inline: Placing JavaScript code directly within an HTML tag using the onclick, onmouseover, or other event attributes.

  • Internal: Writing JavaScript code within <script> tags in the HTML document.

  • External: Linking to an external JavaScript file using the <script src="filename.js"></script> tag, allowing for better organization and reuse of code.

3.5 JavaScript Fundamentals

  • Variables: Used to store data values. JavaScript variables can be declared using var, let, or const.

  • Data Types: JavaScript supports several data types, including:

    • String: Represents text values.

    • Number: Represents numeric values.

    • Boolean: Represents true or false values.

    • Object: A collection of key-value pairs.

    • Array: An ordered collection of values.

3.6 Variables and Operators

  • Operators: JavaScript supports various operators, including:

    • Arithmetic Operators: +, -, *, /, % for mathematical operations.

    • Comparison Operators: ==, ===, !=, !==, <, >, <=, >= for comparing values.

    • Logical Operators: && (AND), || (OR), ! (NOT) for combining conditions.

3.7 Functions and Control Structures

  • Functions: Reusable blocks of code that perform a specific task. Functions can take parameters and return values.

  • Control Structures: Used to control the flow of execution in a program. Common control structures include:

    • If-else Statements: Allow for conditional execution based on Boolean expressions.

    • Switch-case Statements: A control structure that allows multiple possible execution paths.

    • Loops: Such as for, while, and do-while loops that execute a block of code multiple times.

3.8 Object-Based Programming with JavaScript and Event Handling

  • Object-Based Programming: JavaScript supports object-oriented programming concepts such as objects and methods, enabling developers to model real-world entities.

  • Event Handling: JavaScript can respond to user actions (events) like clicks, mouse movements, and key presses. Event listeners can be added to HTML elements to trigger functions when events occur.

3.9 Image, Event, and Form Objects

  • Image Objects: JavaScript can manipulate image elements in the DOM, allowing for dynamic image changes or effects.

  • Event Objects: JavaScript provides event objects that contain information about the event that occurred (e.g., mouse position, key pressed).

  • Form Objects: JavaScript can interact with form elements, enabling validation and submission handling.

3.10 Form Validation, JQuery

  • Form Validation: Ensuring that user input meets specified criteria before submitting a form. JavaScript can be used to validate form fields for required input, correct formats, etc.

  • jQuery: A fast, lightweight JavaScript library that simplifies HTML document manipulation, event handling, and animation. It provides an easy-to-use API for DOM traversal and manipulation.

3.11 Server-Side Scripting Using PHP

  • PHP: A server-side scripting language designed for web development. It can create dynamic web pages and interact with databases.

  • Integration: PHP code is executed on the server, and the resulting HTML is sent to the client's browser. PHP can process form data, manage sessions, and handle cookies.

3.12 Introduction to PHP: Hardware and Software Requirements

Hardware Requirements :

  • CPU: 1 GHz or faster (single-core or dual-core processor).

  • RAM: 2 GB minimum (4 GB recommended for better performance).

  • Storage: 20 GB of disk space (SSD recommended for faster file access).

  • Operating System: Any Linux distribution (Ubuntu, CentOS) or Windows.

  • Web Server: Apache or Nginx.

  • PHP Version: PHP 7.4 or higher (preferably the latest stable version).

3.13 Object-Oriented Programming with Server-Side Scripting

  • PHP supports object-oriented programming (OOP) principles, allowing developers to create classes and objects, encapsulate data, and inherit properties and methods from other classes.

    eg:

    <?php
    class Fruit {
      // Properties
      public $name;
      public $color;

      // Methods
      function set_name($name) {
        $this->name = $name;
      }
      function get_name() {
        return $this->name;
      }
    }

    $apple = new Fruit();
    $banana = new Fruit();
    $apple->set_name('Apple');
    $banana->set_name('Banana');

    echo $apple->get_name();
    echo "<br>";
    echo $banana->get_name();
    ?>

3.14 Basic PHP Syntax

  • PHP code is embedded within HTML using the <?php ?> tags. Basic syntax includes:

    • Variables: Declared with a $ sign (e.g., $variableName).

    • Comments: Single-line (//) and multi-line (/* */) comments are supported.

3.15 PHP Data Types

PHP supports several data types:

  • String: Text values enclosed in quotes.

  • Integer: Whole numbers.

  • Float: Decimal numbers.

  • Boolean: Represents true or false.

  • Array: A collection of values indexed by keys.

  • Object: Instances of classes.

3.16 Basic Programming in PHP

Basic programming concepts in PHP include:

  • Control Structures: Conditional statements and loops.

  • Functions: Reusable code blocks that can take parameters and return values.

3.17 Operators (Arithmetic, Logical, Comparison, Operator Precedence)

  • Arithmetic Operators: Perform mathematical operations (e.g., +, -, *, /).

  • Logical Operators: Combine Boolean expressions (e.g., &&, ||).

  • Comparison Operators: Compare values (e.g., ==, ===).

  • Operator Precedence: The order in which operators are evaluated in expressions.

3.18 Variables Manipulation

Variables in PHP can be manipulated using various operations, including assignment, concatenation (for strings), and arithmetic operations.

3.19 Database Connectivity

PHP can connect to databases (e.g., MySQL) using extensions such as mysqli or PDO. It allows executing SQL queries to perform CRUD (Create, Read, Update, Delete) operations.

You can create a MySQL database using PHP by executing an SQL CREATE DATABASE statement. This process can be automated in your PHP script, which will connect to the MySQL server and issue the CREATE DATABASE command.

Example: Creating a Database with PHP

Here’s a simple PHP script to create a new MySQL database:

php
<?php $servername = "localhost"; $username = "root"; // MySQL username $password = ""; // MySQL password // Create connection $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // SQL to create a new database $dbname = "your_new_database"; $sql = "CREATE DATABASE $dbname"; // Execute the query to create the database if (mysqli_query($conn, $sql)) { echo "Database '$dbname' created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } // Close the connection mysqli_close($conn); ?>

Explanation:

  1. Connection:

    • mysqli_connect($servername, $username, $password) is used to connect to the MySQL server (without specifying a database).
    • The connection is stored in the $conn variable.
  2. Create Database:

    • The SQL command CREATE DATABASE $dbname creates a new database.
    • Replace your_new_database with the desired name for your database.
  3. Execution:

    • mysqli_query($conn, $sql) executes the SQL command.
    • A success or error message is displayed based on whether the query executed correctly.
  4. Closing the Connection:

    • After executing the command, the connection to the MySQL server is closed using mysqli_close($conn).

3.20 Connecting Server-Side Script to Database

To connect a PHP script to a database:

  1. Establish a Connection: Use functions like mysqli_connect() or new PDO().

    eg:

    1. Using mysqli (MySQL)


    <?php // Database connection details $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } else { echo "Connected successfully"; } // Close the connection $conn->close(); ?>

    2. Using PDO (PHP Data Objects)


    <?php // Database connection details $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; try { // Create a new PDO connection $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // Set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } // Close the connection $conn = null; ?>

    Replace the placeholders:

  2. Execute SQL Queries: Use prepared statements to ensure security against SQL injection.

    Here's a simple example:

    <?php // Database connection details $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // SQL INSERT query $sql = "INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')"; // Execute the query if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // Close connection mysqli_close($conn); ?>


  3. Close the Connection: Close the database connection after operations.

    After executing your queries, you should close the connection like this:


    <?php // Your previous code... // Execute the query if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // Close the connection mysqli_close($conn); ?>

3.21 Making SQL Queries

SQL queries can be executed using PHP to interact with the database. Common operations include:

  • SELECT: Retrieving data.

    1. SELECT: Retrieving Data

    <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // SQL SELECT query $sql = "SELECT id, name, email FROM users"; $result = mysqli_query($conn, $sql); // Check if there are results and output data if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } } else { echo "0 results"; } // Close connection mysqli_close($conn); ?>

  • INSERT: Adding new records.

    <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // SQL INSERT query $sql = "INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // Close connection mysqli_close($conn); ?>
  • UPDATE: Modifying existing records.

    <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // SQL UPDATE query $sql = "UPDATE users SET email='[email protected]' WHERE name='John Doe'"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); } // Close connection mysqli_close($conn); ?>
  • DELETE: Removing records.


    <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // SQL DELETE query $sql = "DELETE FROM users WHERE name='John Doe'"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } // Close connection mysqli_close($conn); ?>

3.22 Fetching Data Sets

After executing a query, data can be fetched using functions like mysqli_fetch_assoc() or fetchAll() in PDO or other mysqli, allowing access to the returned records.

When fetching data sets from a MySQL database using PHP, you can utilize the mysqli_fetch_assoc() function with the mysqli extension to retrieve records as associative arrays. Here's how you can do it, along with some examples of fetching multiple records.

Fetching Data with mysqli_fetch_assoc()

Example: Fetching All Records

<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // SQL SELECT query $sql = "SELECT id, name, email FROM users"; $result = mysqli_query($conn, $sql); // Check if there are results and fetch data if (mysqli_num_rows($result) > 0) { // Fetch records one by one while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } } else { echo "0 results"; } // Close connection mysqli_close($conn); ?>

3.23 Getting Data About Data

This refers to metadata that provides information about the structure and properties of data stored in a database, such as data types, constraints, and relationships.

3.24 Creating SQL Database with Server-Side Scripting

Databases can be created using SQL commands like CREATE DATABASE, executed through PHP scripts to automate the process of database creation.

Creating a Database with PHP

Example: Creating a Database

php
<?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // SQL CREATE DATABASE command $sql = "CREATE DATABASE your_database_name"; // Execute the query if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } // Close connection mysqli_close($conn); ?>

3.25 Displaying Queries in Tables

Data fetched from a database can be displayed in HTML tables using PHP loops to iterate through the results and dynamically generate table rows.

Example: Displaying Data in an HTML Table

Step 1: Fetch Data from the Database

Here’s a complete example that fetches user data from a database and displays it in an HTML table.

<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // SQL SELECT query $sql = "SELECT id, name, email FROM users"; $result = mysqli_query($conn, $sql); // Check if there are results if (mysqli_num_rows($result) > 0) { // Start the HTML table echo "<table border='1'> <tr> <th>ID</th> <th>Name</th> <th>Email</th> </tr>"; // Loop through the results and create table rows while ($row = mysqli_fetch_assoc($result)) { echo "<tr> <td>" . $row["id"] . "</td> <td>" . $row["name"] . "</td> <td>" . $row["email"] . "</td> </tr>"; } // End the HTML table echo "</table>"; } else { echo "0 results"; } // Close connection mysqli_close($conn); ?>

Explanation:

  1. Database Connection: A connection to the MySQL database is established using mysqli_connect().
  2. SQL Query Execution: The SELECT query fetches records from the users table.
  3. Result Check: The script checks if there are results using mysqli_num_rows().
  4. HTML Table Structure:
    • An HTML table is started with <table> and a header row is defined with <tr> and <th>.
  5. Looping Through Results:
    • The while loop uses mysqli_fetch_assoc() to fetch each row as an associative array.
    • Inside the loop, <tr> tags create new table rows, and <td> tags populate the cells with data from the database.
  6. Closing the Table: The table is closed after all rows are output.
  7. Connection Closure: The database connection is closed with mysqli_close().

Example Output

This script will generate an HTML table that looks something like this:


+----+----------+------------------+ | ID | Name | Email | +----+----------+------------------+ | 1 | John Doe | john@example.com | | 2 | Jane Doe | jane@example.com | +----+----------+------------------+

Here's a simple PHP script using PDO (PHP Data Objects) to fetch data from a database and display it in an HTML table.


<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>contact.php</title> <!-- Add basic styling for the table, making the table, header, and data cells have a black border --> <style type="text/css"> table, th, td { border: 1px solid black; } </style> </head> <body> <p> <?php try { // Create a PDO (PHP Data Object) connection to the MySQL database $con = new PDO('mysql:host=localhost;dbname=dbName', 'user', 'pwd'); // Set the error mode to throw exceptions for easier debugging $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Define the SQL query to select all data from the 'contact' table $query = "SELECT * FROM contact"; // Start the HTML table and open the first row print "<table>\n"; // Execute the query and fetch the first row to get column names $result = $con->query($query); $row = $result->fetch(PDO::FETCH_ASSOC); // Create the table header row with column names print "<tr>\n"; foreach ($row as $field => $value) { print "<th>$field</th>\n"; // Add each column name as a table header cell } print "</tr>\n"; // End the header row // Execute the query again to get all rows from the table $data = $con->query($query); $data->setFetchMode(PDO::FETCH_ASSOC); // Fetch rows as associative arrays // Loop through each row of data foreach ($data as $row) { print "<tr>\n"; // Start a new table row foreach ($row as $name => $value) { print "<td>$value</td>\n"; // Add each value as a table data cell } print "</tr>\n"; // End the row } // Close the table after all data has been displayed print "</table>\n"; } catch (PDOException $e) { // Catch any database connection or query errors and display an error message echo 'ERROR: ' . $e->getMessage(); } ?> </p> </body> </html>