0% found this document useful (0 votes)
5 views

Web Technology 2

The document provides an overview of various programming concepts and techniques, primarily focusing on PHP and JavaScript. It covers topics such as database connections using mysqli_connect(), event handling in JavaScript, and the differences between client-side and server-side scripting. Additionally, it discusses data types in JavaScript, the use of jQuery, and the advantages of PHP in web development.

Uploaded by

gautamsujit151
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Web Technology 2

The document provides an overview of various programming concepts and techniques, primarily focusing on PHP and JavaScript. It covers topics such as database connections using mysqli_connect(), event handling in JavaScript, and the differences between client-side and server-side scripting. Additionally, it discusses data types in JavaScript, the use of jQuery, and the advantages of PHP in web development.

Uploaded by

gautamsujit151
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1. What is purpose of the mysqli_connect() function in PHP?

Describe its usage and


parameters.
The mysqli_connect() function in PHP is used to establish a connection to a MySQL database. It is part of the
MySQL Improved Extension (MySQLi), which provides an interface for accessing MySQL databases with improved
security and functionality compared to the older mysql_connect() function.

Syntax:

mysqli_connect(host, username, password, database, port, socket);

Parameters:

1. host (Required) – The hostname or IP address of the MySQL server (e.g., "localhost" or
"127.0.0.1").
2. username (Required) – The MySQL database username.
3. password (Required) – The password for the specified username.
4. database (Optional) – The name of the database to connect to.
5. port (Optional) – The port number for the MySQL server (default is 3306).
6. socket (Optional) – The socket or named pipe used for the connection.

Example :

<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "my_database";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

echo "Connected successfully";

?>

2. How do you connect MySQL database with PHP? Explain with an example.
<?php

// Step 1: Database Credentials

$server = "localhost"; // MySQL server (usually 'localhost')


$user = "root"; // MySQL username

$pass = ""; // MySQL password (keep empty if no password)

$dbname = "my_database"; // Database name

// Step 2: Create Connection

$conn = mysqli_connect($server, $user, $pass, $dbname);

// Step 3: Check Connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

echo "Connected successfully";

// Step 4: Close Connection (optional, but recommended)

mysqli_close($conn);

?>

3. How do you add an event handler in JavaScript? Give an example.

There are three ways to Add an Event Handler

1. Using HTML Event Attribute (Inline)


2. Using JavaScript’s onclick Property
3. Using addEventListener() (Recommended)

Example 1: Using Inline HTML Event

<button onclick="alert('Button Clicked!')">Click Me</button>

Example 2 : Using JavaScript onclick Property

<button id="myButton">Click Me</button>

<script>

// Get the button element

let btn = document.getElementById("myButton");

// Add an event handler

btn.onclick = function() {
alert("Button Clicked!");

};

</script>

Example 3: Using addEventListener() (Best Practice)

<button id="myButton">Click Me</button>

<script>

// Get the button element

let btn = document.getElementById("myButton");

// Add event handler using addEventListener

btn.addEventListener("click", function() {

alert("Button Clicked!");

});

</script>

4. Explain the database connection PHP function for MySQL.

In PHP, connecting to a MySQL database is essential for building dynamic web applications. The
mysqli_connect() function is commonly used to establish this connection. To make the connection reusable,
a function can be created that takes care of the database connection process. For example, the
connectDatabase() function defines the database credentials such as the server name, username, password,
and database name. It then uses mysqli_connect() to establish the connection and returns the connection
object if successful. If the connection fails, it displays an error message using mysqli_connect_error(). This
function can be included in multiple files to avoid repeating the connection code, making the application
more organized and maintainable. After using the connection, it is a good practice to close it using
mysqli_close($conn) to free up resources. By using a function for database connection, PHP applications
become more scalable and easier to manage.

Note: Example copy from the first question

5. Explain the database connection method in PHP


<?php

// Database credentials

$servername = "localhost";

$username = "root";
$password = "";

$database = "my_database";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

echo "Connected successfully";

// Close connection

mysqli_close($conn);

?>

6. How do you fetch data from database in PHP and display it in form? Describe.

Fetching data from a MySQL database and displaying it in an HTML form allows users to view and edit
existing records. This is commonly used in update/edit forms where users can modify stored data.

Steps to Fetch and Display Data in a Form

1. Connect to the Database using mysqli_connect().


2. Fetch Data using a SQL SELECT query.
3. Display Data inside an HTML form.
4. Populate the form fields with fetched data.

<?php

// Step 1: Database Connection

$conn = mysqli_connect("localhost", "root", "", "my_database");

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

// Step 2: Fetch Data from Database (Assuming user ID is passed via URL)
$id = $_GET['id']; // Get ID from URL

$sql = "SELECT * FROM users WHERE id = $id";

$result = mysqli_query($conn, $sql);

// Step 3: Display Data in Form

if ($row = mysqli_fetch_assoc($result)) {

?>

<form method="post" action="update.php">

<input type="hidden" name="id" value="<?php echo $row['id']; ?>">

<label>Name:</label>

<input type="text" name="name" value="<?php echo $row['name']; ?>"><br>

<label>Email:</label>

<input type="email" name="email" value="<?php echo $row['email']; ?>"><br>

<label>Phone:</label>

<input type="text" name="phone" value="<?php echo $row['phone']; ?>"><br>

<input type="submit" name="update" value="Update">

</form>

<?php

} else {

echo "No record found!";

// Close connection

mysqli_close($conn);

?>

6. Write short notes on Internet technology.

Internet technology refers to the various tools, protocols, and systems that enable communication, data
exchange, and online services over the Internet. It plays a crucial role in modern life, supporting web
browsing, email, social media, e-commerce, cloud computing, and more.
Key Components of Internet Technology:

1. Web Technologies – Includes HTML, CSS, JavaScript, and frameworks like React and Angular for building
websites and web applications.
2. Networking Protocols – Protocols like TCP/IP, HTTP, HTTPS, FTP, and DNS enable data transmission and
communication.
3. Internet Services – Services such as email, VoIP (Skype, Zoom), cloud storage (Google Drive, Dropbox), and
streaming (Netflix, YouTube).
4. Wireless & Mobile Internet – Includes Wi-Fi, 4G, 5G, and satellite communication, allowing seamless
connectivity.
5. Cybersecurity – Technologies like firewalls, encryption, and VPNs help protect data from cyber threats.

Importance of Internet Technology:

 Enables instant communication (emails, messaging apps).


 Facilitates online transactions (e-commerce, digital banking).
 Supports remote work and education through cloud-based applications.
 Enhances entertainment and social interactions via social media and streaming platforms.

Internet technology continues to evolve, shaping the digital world with advancements like AI, IoT, and
blockchain.

7. Differentiate between server-side and client-side scripting.

Client-side scripting Server-side scripting


Source code is not visible to the user because its
output
Source code is visible to the user.
of server-sideside is an HTML page.

Its primary function is to manipulate and provide


Its main function is to provide the requested
access to the respective database as per the
output to the end user.
request.
In this any server-side technology can be used
It usually depends on the browser and its and it does not
version. depend on the client.

It runs on the user’s computer. It runs on the webserver.


There are many advantages linked with this like The primary advantage is its ability to highly
faster. customize, response
Response times, a more interactive application. requirements, access rights based on user.

It does not provide security for data. It provides more security for data.
It is a technique that uses scripts on the
It is a technique used in web development in
webserver to produce a response that is
which scripts run on the client’s browser.
customized for each client’s request.
HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.
No need of interaction with the server. It is all about interacting with the servers.
It reduces load on processing unit of the server. It surge the processing load on the server.
8. Explain different data types used in JavaScript.

JavaScript has two main categories of data types: Primitive and Non-Primitive.

1. Primitive Data Types

These store a single value and are immutable (cannot be changed).

 Number: Represents numeric values (integers and floats).


o Example: let age = 25;
 String: Represents text, enclosed in quotes.
o Example: let name = "Alice";
 Boolean: Represents true or false.
o Example: let isActive = true;
 Undefined: A variable that has been declared but not assigned a value.
o Example: let score; (score is undefined)
 Null: Represents an intentional absence of value.
o Example: let data = null;
 BigInt: For very large integers.
o Example: let bigNum = 12345678901234567890n;
 Symbol: Represents a unique identifier.
o Example: let uniqueID = Symbol('id');

2. Non-Primitive Data Types

These can store collections of values or more complex entities.

 Object: A collection of key-value pairs.


o Example: let person = { name: "Alice", age: 25 };
 Array: An ordered list of values.
o Example: let colors = ["Red", "Green", "Blue"];
 Function: A block of reusable code.
o Example: function greet() { return "Hello!"; }

8. What is JQuery? Write down its uses.

jQuery is a fast, lightweight, and feature-rich JavaScript library that simplifies HTML document traversal
and manipulation, event handling, animation, and AJAX interactions. It was designed to make it easier to
work with JavaScript, enabling developers to write less code while achieving more functionality.

Key Features of jQuery:

 Cross-browser compatibility: Works consistently across different web browsers.


 Simplified syntax: Provides a concise and easy-to-use syntax for common tasks.
 Extensibility: Supports plugins that can enhance its functionality.

Uses of jQuery:

1. DOM Manipulation:
o Easily select and modify HTML elements.
o Add, remove, or update content dynamically.
o Example: $('#element').hide (); hides an element.
2. Event Handling:
o Simplifies handling events like clicks, mouse movements, and keyboard actions.
o Example: $('#button').click (function () {alert ('Clicked!'); });
3. AJAX Requests:
o Facilitates asynchronous requests to fetch data without reloading the page.

4. Animations and Effects:

 Provides built-in methods for creating animations and effects like fading, sliding, and
showing/hiding elements.
 Example: $('#element').fadeIn();

5. Cross-browser Support:

 Handles inconsistencies between different web browsers, ensuring a smoother user experience.

6. Plugins:

 Supports a wide range of plugins to extend its functionality for tasks such as form validation, image
sliders, and more.

7. Simplified AJAX Forms:

 Makes it easier to submit forms and handle responses without a full page refresh.

8. What is PHP? Explain its uses and advantages.

PHP (Hypertext Preprocessor) is a widely-used, open-source server-side scripting language designed


primarily for web development. It can be embedded into HTML and is especially suited for creating
dynamic and interactive web applications. PHP scripts are executed on the server, generating HTML that is
sent to the client’s browser.

Uses of PHP:

1. Web Development:
o PHP is commonly used to build dynamic websites and web applications. It can handle forms,
sessions, and manage databases.
2. Database Interaction:
o PHP seamlessly integrates with databases like MySQL, PostgreSQL, and others, enabling developers
to create data-driven applications.
3. Content Management Systems (CMS):
o Popular CMS platforms like WordPress, Joomla, and Drupal are built using PHP, allowing users to
create and manage content easily.
4. E-commerce Solutions:
o PHP is used to develop e-commerce platforms, enabling businesses to sell products and services
online (e.g., Magento, WooCommerce).
5. Web APIs:
o PHP can be used to create RESTful APIs, allowing different applications to communicate and
exchange data over the web.
6. Session Management:
o PHP provides built-in support for managing user sessions and cookies, facilitating user
authentication and tracking.

Advantages of PHP:

1. Open Source:
o PHP is free to use and has a large community of developers contributing to its continuous
improvement and support.
2. Cross-Platform Compatibility:
o PHP runs on various operating systems (Windows, Linux, macOS) and can work with different web
servers (Apache, Nginx, IIS).
3. Ease of Learning:
o PHP has a simple and straightforward syntax, making it accessible for beginners and reducing the
learning curve.
4. Wide Community Support:
o A vast community of developers provides extensive documentation, tutorials, and forums, making it
easier to find help and resources.
5. Rich Set of Built-in Functions:
o PHP offers a wide range of built-in functions for various tasks, such as string manipulation, file
handling, and date/time processing.
6. Integration with Databases:
o PHP supports various database systems, making it easy to interact with databases and manage data
efficiently.
7. Scalability and Performance:
o PHP can handle a large number of concurrent users and is capable of scaling web applications to
meet growing demands.

9. Explain the different operators used in a PHP


The different types of operators used in PHP are as follows:

1. Arithmetic Operators

Arithmetic operators are used for performing basic mathematical operations.

 Addition (+): Adds two values.


o Example: $result = $a + $b; (If $a is 5 and $b is 3, $result will be 8.)
 Subtraction (-): Subtracts one value from another.
o Example: $result = $a - $b; (If $a is 5 and $b is 3, $result will be 2.)
 Multiplication (*): Multiplies two values.
o Example: $result = $a * $b; (If $a is 5 and $b is 3, $result will be 15.)
 Division (/): Divides one value by another.
o Example: $result = $a / $b; (If $a is 6 and $b is 3, $result will be 2.)
 Modulus (%): Returns the remainder of a division operation.
o Example: $result = $a % $b; (If $a is 5 and $b is 3, $result will be 2.)
 Exponentiation (**): Raises a number to the power of another.
o Example: $result = $a ** $b; (If $a is 2 and $b is 3, $result will be 8.)

2. Assignment Operators

Assignment operators are used to assign values to variables.

 Simple Assignment (=): Assigns the value of the right operand to the left operand.
o Example: $a = 5;
 Addition Assignment (+=): Adds the right operand to the left operand and assigns the result.
o Example: $a += 3; (If $a was 5, it becomes 8.)
 Subtraction Assignment (-=): Subtracts the right operand from the left operand and assigns the result.
o Example: $a -= 2; (If $a was 5, it becomes 3.)
 Multiplication Assignment (*=): Multiplies the left operand by the right operand and assigns the result.
o Example: $a *= 2; (If $a was 5, it becomes 10.)
 Division Assignment (/=): Divides the left operand by the right operand and assigns the result.
o Example: $a /= 5; (If $a was 10, it becomes 2.)
 Modulus Assignment (%=): Applies the modulus operator and assigns the result.
o Example: $a %= 3; (If $a was 5, it becomes 2.)

3. Comparison Operators

Comparison operators are used to compare two values and return a boolean result (true or false).

 Equal to (==): Checks if two values are equal.


o Example: $a == $b; (Returns true if $a is equal to $b.)
 Identical (===): Checks if two values are equal and of the same type.
o Example: 5 === '5'; (Returns false because one is a number and the other is a string.)
 Not equal (!=): Checks if two values are not equal.
o Example: $a != $b; (Returns true if $a is not equal to $b.)
 Not identical (!==): Checks if two values are not equal or not of the same type.
o Example: 5 !== '5'; (Returns true because they are not of the same type.)
 Greater than (>): Checks if the left operand is greater than the right.
o Example: $a > $b; (Returns true if $a is greater than $b.)
 Less than (<): Checks if the left operand is less than the right.
o Example: $a < $b; (Returns true if $a is less than $b.)
 Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right.
o Example: $a >= $b;
 Less than or equal to (<=): Checks if the left operand is less than or equal to the right.
o Example: $a <= $b;

4. Logical Operators

Logical operators are used to combine conditional statements.

 Logical AND (&&): Returns true if both conditions are true.


o Example: ($a > 5 && $b < 10);
 Logical OR (||): Returns true if at least one condition is true.
o Example: ($a > 5 || $b < 10);
 Logical NOT (!): Reverses the boolean value.
o Example: !($a > 5); (Returns true if $a is not greater than 5.)

5. Increment and Decrement Operators

These operators are used to increase or decrease the value of a variable by one.

 Increment (++): Increases the value of a variable by 1.


o Example: $a++; (If $a was 5, it becomes 6.)
 Decrement (--): Decreases the value of a variable by 1.
o Example: $a--; (If $a was 5, it becomes 4.)

6. String Operators

String operators are used to concatenate strings.


 Concatenation (.): Joins two strings together.
o Example: $fullName = $firstName . " " . $lastName;
 Concatenation Assignment (.=): Appends a string to the existing string variable.
o Example: $fullName .= " Smith"; (If $fullName was "John", it becomes "John Smith.")

7. Array Operators

Array operators are used to compare arrays.

 Union (+): Combines two arrays.


o Example: $array1 + $array2;
 Equality (==): Checks if two arrays have the same key-value pairs.
o Example: $array1 == $array2;
 Identity (===): Checks if two arrays are identical in key-value pairs and order.
o Example: $array1 === $array2;
 Inequality (!=): Checks if two arrays are not equal.
o Example: $array1 != $array2;
 Non-identity (!==): Checks if two arrays are not identical.
o Example: $array1 !== $array2;

8. Ternary Operator

The ternary operator is a shorthand for the if-else statement.

 Ternary (? :): Returns one of two values based on a condition.


o Example: $result = ($a > $b) ? $a : $b; (If $a is greater than $b, $result gets the value
of $a; otherwise, it gets $b.)

10. Develop a program in JavaScript to exchange/swap the values of any two variables

// Function to swap two variables using a temporary variable


function swapUsingTemp() {
let a = 5; // First variable
let b = 10; // Second variable

console.log("Before swapping:");
console.log("a =", a);
console.log("b =", b);

// Swap using a temporary variable


let temp = a;
a = b;
b = temp;
console.log("After swapping:");
console.log("a =", a);
console.log("b =", b);
}

// Call the function


swapUsingTemp();

Write a JavaScript function that checks if a number is even or odd and print the result.

// Function to check if a number is even or odd


function checkEvenOdd(number) {
if (typeof number !== 'number') {
console.log("Please enter a valid number.");
return;
}

if (number % 2 === 0) {
console.log(number + " is even.");
} else {
console.log(number + " is odd.");
}
}

// Example usage
checkEvenOdd(10); // Output: 10 is even.
checkEvenOdd(7); // Output: 7 is odd.
checkEvenOdd(0); // Output: 0 is even.
checkEvenOdd(-3); // Output: -3 is odd.
checkEvenOdd("5"); // Output: Please enter a valid number.
11. Write a program to find the largest number among three numbers in JavaScript.
// Function to find the largest number among three numbers
function findLargestNumber(num1, num2, num3) {
if (num1 >= num2 && num1 >= num3) {
return num1; // num1 is the largest
} else if (num2 >= num1 && num2 >= num3) {
return num2; // num2 is the largest
} else {
return num3; // num3 is the largest
}
}
// Example usage
const number1 = 25;
const number2 = 30;
const number3 = 20;

const largest = findLargestNumber(number1, number2, number3);

console.log ("The largest number among", number1, number2, "and", number3, "is:", largest);

12. What are the uses of Java Script in web page development?

JavaScript is a powerful programming language widely used in web development for a variety of purposes.
Here are some of its primary uses:

1. Client-Side Scripting: JavaScript is primarily used as a client-side scripting language. It runs in the
user's web browser, allowing for interactive and dynamic content without requiring a page reload.
2. Form Validation: JavaScript can validate user input in forms before submitting data to the server.
This ensures that users enter the correct data format, improving user experience and reducing server
load.
3. Dynamic Content Updates: JavaScript enables dynamic content changes on a webpage without
reloading the entire page. This is often achieved through AJAX (Asynchronous JavaScript and
XML), allowing for smooth user interactions.
4. Event Handling: JavaScript can respond to user actions such as clicks, mouse movements, and
keyboard inputs. This interactivity is crucial for creating engaging user interfaces and improving user
experience.
5. Animations and Effects: JavaScript can create animations, transitions, and other visual effects on
web pages. Libraries like jQuery and frameworks like GSAP enhance these capabilities.
6. Manipulating HTML and CSS: JavaScript can modify the DOM (Document Object Model),
allowing developers to change HTML elements and CSS styles dynamically. This enables real-time
updates and modifications to the webpage.
7. Creating Interactive Games: JavaScript is used in web-based games, allowing developers to create
interactive and engaging experiences directly in the browser.
8. Browser-Based Applications: With frameworks like React, Angular, and Vue.js, JavaScript can be
used to build complex single-page applications (SPAs) that offer a desktop-like experience in a web
browser.
9. Accessing APIs: JavaScript can make HTTP requests to external APIs, allowing web applications to
retrieve and display data from various sources, such as social media, weather services, and more.
10. Cross-Platform Development: JavaScript, along with frameworks like Node.js, enables server-side
development, allowing developers to use the same language for both front-end and back-end
development.

13. Write down the server-side script to create a database, connect with it, create a
table and insert data in it.
<?php
// Database configuration
$host = 'localhost'; // MySQL server host
$username = 'root'; // MySQL username
$password = ''; // MySQL password
$dbname = 'my_database'; // Name of the database

// Create connection
$conn = new mysqli($host, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to MySQL server.<br>";

// Create database
$sql = "CREATE DATABASE $dbname";
if ($conn->query($sql) === TRUE) {
echo "Database '$dbname' created successfully.<br>";
} else {
echo "Error creating database: " . $conn->error . "<br>";
}

// Select the database


$conn->select_db($dbname);

// Create table
$table_sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

if ($conn->query($table_sql) === TRUE) {


echo "Table 'users' created successfully.<br>";
} else {
echo "Error creating table: " . $conn->error . "<br>";
}

// Insert data into the table


$insert_sql = "INSERT INTO users (username, email) VALUES
('john_doe', '[email protected]'),
('jane_doe', '[email protected]')";

if ($conn->query($insert_sql) === TRUE) {


echo "Data inserted successfully into 'users' table.<br>";
} else {
echo "Error inserting data: " . $conn->error . "<br>";
}
// Close the connection
$conn->close();
?>

You might also like