0% found this document useful (0 votes)
6 views12 pages

PHP - Iv Unit

The document provides an overview of PHP and MySQL, focusing on HTML forms, methods for handling form data, and database management concepts. It explains the roles of HTML forms in data collection and user interaction, differentiates between GET and POST methods, and discusses MySQL data types and commands. Additionally, it covers security considerations for handling form data in PHP and illustrates the usage of various PHP functions for database operations.

Uploaded by

sharankumar26341
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views12 pages

PHP - Iv Unit

The document provides an overview of PHP and MySQL, focusing on HTML forms, methods for handling form data, and database management concepts. It explains the roles of HTML forms in data collection and user interaction, differentiates between GET and POST methods, and discusses MySQL data types and commands. Additionally, it covers security considerations for handling form data in PHP and illustrates the usage of various PHP functions for database operations.

Uploaded by

sharankumar26341
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

PHP & MySQL – IV UNIT

2 marks:
1. What is the role of HTML form in web development.
Data Collection: HTML forms allow websites to collect various types of user input, such as text,
numbers, dates, selections, and file uploads.
User Interaction: They enable users to submit information to a web server, initiating actions such as
submitting a search query, registering for an account, or completing an online purchase.
2. What is use of Action attribute in HTML form? Give example.
The action attribute in HTML forms specifies the URL where the form data will be submitted upon
user submission. It indicates the server-side script or endpoint responsible for processing the form
data. The value of the action attribute can be a relative or absolute URL.
Eg: <form action= "process_form.php " method="post">
3. Name two methods for handling HTML form data in PHP.
• The GET method sends form data appended to the URL as query parameters.
• The POST method sends form data in the HTTP request body, not in the URL.
4. Differentiate between the GET and POST methods in HTML forms.
GET POST
Data is appended to the URL as a query string. Data is sent in the body of the HTTP request. It is not
This means that the data is visible in the URL. visible in the URL.
Suitable for small amounts of data. Suitable for large amounts of data.
Less secure for sensitive information. More secure for sensitive information.
Data can be cached by the browser. Data is not cached by default.

5. What are the limitations of using the GET method for transferring form data.
• There is a URL length limit, causing errors with large data in GET requests.
• GET expose form data in the URL, making it visible and insecure for sensitive information.
• GET request URLs can be bookmarked or shared, risking exposure of sensitive information.
• GET requests can be cached, leading to potential exposure of sensitive or outdated data.
6. What security considerations should be taken when handling form data in PHP?
• Always validate and sanitize user input to prevent malicious data from being processed or stored.
• Ensure proper session management and security. Use HTTPS to encrypt data transmitted between
the client and server, preventing tampering.
• Use prepared statements or parameterized queries while interacting with database to prevent SQL
injection attacks.
• If your application allows file uploads, restrict the file types, sizes, and locations where files can
be uploaded.
7. What is the purpose and functionality of $_SERVER['REQUEST_METHOD'] in PHP
when dealing with form submissions.
Purpose: $_SERVER['REQUEST_METHOD'] is used to determine the HTTP request method (e.g.,
GET, POST) used to access the page.
Functionality: Helps in processing form submissions by distinguishing between different request
methods to handle form data accordingly.
8. What is MySQL and how is it used in web development?
MySQL is an open-source relational database management system (RDBMS) that is widely used in
web development. MySQL uses Structured Query Language (SQL) to manage and manipulate data
stored in databases.
It is commonly used in web development to handle database operations such as storing user
information, content management, and supporting dynamic websites.
9. List any four data types in MySQL.
• INT
• VARCHAR
• DATE
• TEXT
10. Differentiate char and varchar data types.
char varchar
Stores fixed-length strings Stores variable-length strings
Pads values with spaces to fill the defined Does not pad values
length
Always consumes the full defined length Consumes actual length plus one bytes
Used when data length is consistent and known Used when data length varies or is not fixed

11. What is the purpose of an auto-increment field in a database table? Provide example of
auto increment field creation.
The purpose of an auto-increment field in a database table is to automatically generate a unique
identifier for each new record inserted into the table. This ensures that each record has a unique
primary key without the need for manual input.
Eg: CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50)
);
12. What is the MySQL client and what role does it play in database management?
The MySQL client is a program or software tool that allows users to interact with MySQL database
servers. It serves as an interface between users and the MySQL server, enabling them to perform
various database management tasks, such as executing SQL queries, managing database objects,
importing/exporting data, and administering server settings. Itprovides a command-line interface
(CLI) or graphical user interface (GUI) for interacting with MySQL databases.
13. Differentiate between MySQL client and phpMyAdmin for accessing MySQL.
MySQL Client: Provides a command-line interface (CLI) for interacting with MySQL databases
directly through SQL commands. It is text-based and used by database administrators and
developers comfortable with SQL.
phpMyAdmin: Offers a web-based graphical user interface (GUI) accessible via a web browser. It
allows users, including beginners and web developers, to manage MySQL databases using a point-
and-click interface, simplifying tasks like SQL query execution, database administration, and data
management.
14. List four common MySQL commands used for database management.
• SELECT • INSERT
• UPDATE • DELETE
15. How do you establish a connection to a MySQL database using PHP?
To establish a connection to a MySQL database using PHP, you can use the mysqli extension or the
PDO (PHP Data Objects) extension.
<?php $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername,$username,$password,$dbname); //Create connection
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else { echo “Connected Successfully”}
?>

16. What is purpose of mysqli_query() method ? Give usage example.


The mysqli_query()is used to perform SQL queries on a MySQL database. Its purpose is to send a
query to the MySQL database and return the result (if applicable).
Eg: $conn = new mysqli($servername,$username,$password,$dbname);
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);

17. Differentiate mysqli_num_rows( ) and mysqli_affected_rows( ) methods.


mysqli_num_rows(): Returns the number of rows in a result set obtained from a SELECT query
executed using mysqli_query(). It's typically used after executing a SELECT query with
mysqli_query().
mysqli_affected_rows(): Returns the number of rows affected by the last INSERT, UPDATE,
DELETE, or REPLACE query executed using mysqli_query(). It's often used after executing
INSERT, UPDATE, REPLACE, or DELETE queries with mysqli_query().
18. How do you execute simple queries in MySQL using PHP? Give example.
To execute simple queries in MySQL using PHP, you typically use the mysqli_query() function.
Eg: $conn = new mysqli($servername,$username,$password,$dbname);
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);

19. What function is used to retrieve query results in PHP from a MySQL database?
In PHP, the function used to retrieve query results from a MySQL database is mysqli_fetch_assoc().
This function is commonly used after executing a SELECT query using mysqli_query() to fetch
each row of the result set as an associative array.
20. How do you count the number of records returned by a MySQL query in PHP? Give code
example.
To count the number of records returned by a MySQL query in PHP, you can use the
mysqli_num_rows() function. This function counts the number of rows in the result set obtained
from a SELECT query executed using mysqli_query().
Eg: $conn = new mysqli($servername,$username,$password,$dbname);
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($result);
echo "Number of records returned: " . $num_rows;
mysqli_close($conn);
21. How to update records in a MySQL database using PHP. Give code example.
To update records in a MySQL database using PHP, you use an UPDATE SQL statement along with
the mysqli_query() function.
Eg: $conn = new mysqli($servername,$username,$password,$dbname);
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";
$result = mysqli_query($conn, $sql);
if ($result) { echo "Record updated successfully"; }

22. Give PHP code for validating email.


<?php
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "The email address is valid.";
} else {
echo "The email address is invalid.";
} ?>

23. List mysqli_fetch_array() constants in PHP.


• MYSQLI_ASSOC: This constant instructs mysqli_fetch_array() to return an associative array.
• MYSQLI_NUM: This constant instructs mysqli_fetch_array() to return a numeric array.
• MYSQLI_BOTH: This constant instructs mysqli_fetch_array() to return both an associative and a
numeric array.

Long Answer Questions


1. Explain the role of HTML forms in web development and discuss two methods for handling
form data in PHP. Provide examples to illustrate their usage.
Role of HTML Forms:
Data Collection: HTML forms allow websites to collect various types of user input, such as text,
numbers, dates, selections, and file uploads.
User Interaction: They enable users to submit information to a web server, initiating actions such
as submitting a search query, registering for an account, or completing an online purchase.
User Interface: Forms provide a structured layout for input fields, labels, buttons, and other
elements, facilitating a user-friendly interface for data entry.
Validation: Ensures that user input meets specified criteria before submission. Server-side
validation is also essential for security and data integrity.
2 methods for handling form data in PHP:
(i) Using $_POST and $_GET superglobal variables:
This method involves accessing form data through PHP's $_POST and $_GET superglobal arrays.
The $_POST array is used when the form's method attribute is set to "post", and $_GET is used
when the method is set to "get". Example (Using POST method):
HTML code :
<form method="post" action="process_form.php">
<input type="text" name="username" placeholder="Username"><br>
<input type="password" name="password" placeholder="Password"> <br>
<button type="submit">Submit</button>
</form>
PHP script :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
}
ii. Using $_REQUEST Super Global Variable:
The $_REQUEST superglobal array is a merge of $_GET, $_POST, and $_COOKIE. It can be used
to access form data regardless of the form's method attribute value.
Eg: <form method="post" action="process_form.php">
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
<?php
$email = $_REQUEST['email']; // Retrieving form data using $_REQUEST
echo "Your email is: $email";
?>
2. Explain any Five HTML form input types with usage syntax.
i. Text boxes: It accepts a wide range of alphanumeric text and other characters in a single-line box.
The general format of a text box input is:
<input type="text" name="name" size="size" maxlength="length" value="value">
The size attribute specifies the width of the box (in characters of the current font) as it should appear
on the screen, and maxlength specifies the maximum number of characters that a user is allowed to
enter into the field.
ii. Text Area: The <textarea> element in HTML is used to create a multiline text input area where
users can enter larger blocks of text. The general format of a text box input is:
<textarea name="name" cols="width" rows="height" wrap="type">
This is some default text.
</textarea>
iii. Checkboxes: The checkbox input type allows users to select one or more options from a set of
choices. The general format:
<input type="checkbox" name="name" value="value" checked="checked">
If you include the checked attribute, the box is already checked when the browser is displayed.
iv. Radio Buttons: Radio buttons allow users to select one option from multiple choices. They are
used when you want only a single value to be returned from a selection of two or more options.
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
v. <select>: The <select> tag lets you create a drop-down list of options, offering either single or
multiple selections. It conforms to the following syntax:
<select name="name" size="size" multiple="multiple">
The attribute size is the number of lines to display. If you use the multiple attribute, a user can select
multiple options from the list by pressing the Ctrl key when clicking.
3. Differentiate between the POST and GET methods in HTML forms. Give code examples to
illustrate both methods.
i. GET Method:
• Data is appended to the URL as query parameters.
• Limited amount of data can be sent (URL length restrictions).
• Suitable for requests where data is visible in the URL (e.g., searching, filtering).
• Not suitable for sensitive data like passwords.
• Data is visible in the browser's address bar.
• Caching is possible since the data is part of the URL.
Eg: <form method="get" action="process_get.php">
<label for="search_query">Search: </label>
<input type="text" name="search_query" id="search_query">
<input type="submit" value="Search">
</form>
<?php
if (isset($_GET['search_query'])) {
$search_query= $_GET['search_query'];
echo "You searched for: $search_query"; // Process the search query
} ?>
ii. POST Method:
• Data is sent in the request body, not visible in the URL.
• Can send large amounts of data.
• Suitable for sensitive data as it's not visible in the URL.
• Not cached, so it's more secure for sensitive data.
• Recommended for forms that involve updating or modifying data.
Eg: <form method="post" action="process_form.php">
<input type="text" name="username" placeholder="Username"><br>
<input type="password" name="password" placeholder="Password"> <br>
<button type="submit">Submit</button>
</form>
<?php
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST["username"];
$password = $_POST["password"];
// Process login credentials
echo "Username: $username ";
echo "Password: $password";
} ?>
4. Explain the key terms used in database management systems, highlighting the significance
of concepts such as tables, rows, columns, and primary keys.
Database: A database is a structured collection of data that is organized and managed for efficient
retrieval, storage, and manipulation. It can contain one or more tables and related data.
Tables: Tables are the fundamental structure in a relational database where data is organized. Each
table consists of rows and columns. Tables provide a structured way to store related data. They
allow data to be logically organized into rows (records) and columns (fields), facilitating efficient
data storage and retrieval.
Rows (Records): Rows, also known as records or tuples, represent individual entries or instances of
data within a table. Each row in a table corresponds to a single entity or record, such as a customer,
product, or transaction. Rows store specific data values across different columns, collectively
forming a complete dataset.
Columns (Fields): Columns represent the attributes or properties of the data stored in a table. Each
column has a unique name and data type. Columns define the structure and characteristics of the
data within a table. They specify what type of data can be stored (e.g., integers, strings, dates).
Primary Key: A primary key is a column or a set of columns that uniquely identifies each row in a
table. Primary keys ensure the uniqueness of each row in a table, preventing duplicate entries and
facilitating efficient data retrieval through indexing. They enforce data integrity by ensuring that
every row has a unique identifier.

5. Explain any five data types in MySQL, including numeric, string, date/time, and Boolean
data types, and provide examples of their usage.
Numeric Data Types:
INT: Used for storing whole numbers (integers) within a specified range. Examples: 1, -5, 1000.
CREATE TABLE users ( id INT PRIMARY KEY, age INT);
DECIMAL: Used for storing exact numeric values with fixed precision and scale.
CREATE TABLE products ( id INT PRIMARY KEY, price DECIMAL(10, 2));
String Data Types:
VARCHAR: Variable-length character string. It allows storing a variable number of characters, up
to a maximum specified length.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100));
TEXT: Used for storing large amounts of text data, such as long paragraphs or documents.
CREATE TABLE posts (
id INT PRIMARY KEY,
message TEXT);
Date/Time Data Types:
DATE: Used for storing dates in the format 'YYYY-MM-DD'.
CREATE TABLE events (
id INT PRIMARY KEY,
event_date DATE );
Boolean Data Type:
BOOL or BOOLEAN: Used for storing boolean values, which represent true or false states.
CREATE TABLE tasks (
id INT PRIMARY KEY,
task_name VARCHAR(100),
completed BOOLEAN
);
6. Differentiate between accessing MySQL using the MySQL client and using phpMyAdmin.
Explain the advantages and disadvantages of each approach.
MySQL Client: Provides a command-line interface (CLI) for interacting with MySQL databases
directly through SQL commands. It is text-based and used by database administrators and
developers comfortable with SQL.
Advantages:
• The MySQL client is a standalone tool that doesn't require additional software installation.
• Users familiar with SQL can quickly execute queries without the overhead of a GUI interface.
• It can be integrated into scripts for automating database tasks.
Disadvantages:
• It requires familiarity with SQL commands and syntax, which can be challenging for beginners.
• Users who prefer visual tools may find it less intuitive to work with compared to GUI-based tools
• It may lack some advanced features and functionalities available in GUI-based tools.
phpMyAdmin: Offers a web-based graphical user interface (GUI) accessible via a web browser. It
allows users, including beginners and web developers, to manage MySQL databases using a point-
and-click interface, simplifying tasks like SQL query execution, database administration, and data
management.
Advantages:
• phpMyAdmin offers a graphical user interface (GUI) that makes it easy for users to interact with
the database visually.
• Since phpMyAdmin is web-based, it can be accessed from any web browser,
• phpMyAdmin provides a wide range of features for managing databases, including
importing/exporting data, creating/modifying tables
Disadvantages:
• Running phpMyAdmin requires a web server (like Apache or Nginx) and PHP, which can
consume more system resources compared to the lightweight MySQL client.
• Being web-based, phpMyAdmin may pose security risks if not properly configured and secured.
• Users need to have a web server environment set up with PHP support to run phpMyAdmin.

7. Outline the essential MySQL commands necessary for database management, including
creating databases, tables, inserting data, querying data, and updating records.
CREATE DATABASE: To create a new database
CREATE DATABASE dbname;
USE: To select a specific database to work with
USE dbname;
CREATE TABLE: To create a new table within the selected database
CREATE TABLE tablename (
column1 datatype constraints,
column2 datatype constraints, ... );
INSERT: To insert data into a table
INSERT INTO tablename (column1, column2, ...) VALUES (value1, value2, ...);
SELECT: To retrieve data from a table
SELECT column1, column2, ... FROM tablename WHERE condition;
UPDATE: To update existing records in a table
UPDATE tablename SET column1 = value1, column2 = value2 WHERE condition;
DELETE: To delete specific records from a table
DELETE FROM tablename WHERE condition;
DROP: To delete a table from the database or to delete the entire database.
DROP TABLE tablename;
DROP DATABASE dbname;
SHOW: To display a list of databases or to display a list of tables in the current database.
SHOW DATABASES;
SHOW TABLES;

8. Explain the process of connecting to MySQL using PHP. Give the PHP code for connecting
and Selecting Specific database.
Connecting to MySQL using PHP involves several steps, including establishing a connection to the
MySQL server, selecting a specific database, executing queries, and handling errors.
• Establishing a Connection: Use the mysqli_connect() function to establish a connection to the
MySQL server. This function requires the hostname, username, password, and optionally the port
number as parameters.
• Checking Connection Status: Check if the connection was successful using the
mysqli_connect_errno() function. If it returns 0, the connection was successful. Otherwise, an error
occurred.
• Selecting a Specific Database: Once the connection is established, use the mysqli_select_db()
function to select a specific database to work with.
<?php
// MySQL server configuration
$hostname = "localhost"; // Change this to your MySQL server hostname
$username = "username"; // Change this to your MySQL username
$password = "password"; // Change this to your MySQL password
$database = "dbname"; // Change this to the name of your database
// Establishing a connection to MySQL
$connection = mysqli_connect($hostname, $username, $password);
// Check if the connection was successful
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// Selecting a specific database
if (!mysqli_select_db($connection, $database)) {
die("Failed to select database: " . mysqli_error($connection));
}
echo "Connected to MySQL successfully and selected database: $database";
// You can proceed with executing queries and performing database operations here.
// Don't forget to close the connection when done
mysqli_close($connection);
?>
9. Explain the process of executing simple queries in MySQL using PHP. Provide a code
example demonstrating how to execute a SELECT query and retrieve the results using PHP
MySQL functions.
Establish a Connection: Use the mysqli_connect() function to establish a connection to the
MySQL server.
Execute the Query: Use the mysqli_query() function to execute the SQL query.
Retrieve the Results: If the query is successful, fetch the results using functions like
mysqli_fetch_assoc(), mysqli_fetch_array(), or mysqli_fetch_row() depending on the desired
format of the result set.
Iterate Over the Results: Use a loop to iterate over the result set and process each row.
Close the Connection: Close the MySQL connection using the mysqli_close() function when done.
Example:
<?php
// MySQL server configuration
$hostname = "localhost"; // Change this to your MySQL server hostname
$username = "username"; // Change this to your MySQL username
$password = "password"; // Change this to your MySQL password
$database = "dbname"; // Change this to the name of your database
// Establishing a connection to MySQL
$connection = mysqli_connect($hostname, $username, $password, $database);
// Check if the connection was successful
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// Execute a SELECT query
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// Check if the query was successful
if (!$result) {
die("Error executing query: " . mysqli_error($connection));
}
// Fetch and process the results
while ($row = mysqli_fetch_assoc($result)) {
// Process each row of the result set
echo "User ID: " . $row['id'] . ", Username: " .
$row['username'] . "<br>";
}
// Free the result set
mysqli_free_result($result);
// Close the connection
mysqli_close($connection);
?>
10. Explain the process of updating records in a MySQL database.
Establish a Connection: First, establish a connection to the MySQL server using PHP's MySQL
functions (mysqli_connect()).
Construct the UPDATE Statement: Write an SQL UPDATE statement to specify the table to
update, the columns to modify, and the new values. You can also include a WHERE clause to
specify which records to update based on certain conditions.
Execute the UPDATE Statement: Use the mysqli_query() function to execute the UPDATE
statement.
Handle Errors: Check if the query was successful using mysqli_affected_rows() or by checking for
errors using mysqli_error(). Handle any errors that occur during the update process.
Close the Connection: Close the MySQL connection using mysqli_close() when done.
<?php
// MySQL server configuration
$hostname = "localhost"; // Change this to your MySQL server hostname
$username = "username"; // Change this to your MySQL username
$password = "password"; // Change this to your MySQL password
$database = "dbname"; // Change this to the name of your database
// Establishing a connection to MySQL
$connection = mysqli_connect($hostname, $username, $password, $database);
// Check if the connection was successful
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// Construct the UPDATE statement
$query = "UPDATE users SET email = '[email protected]' WHERE id = 1";
// Execute the UPDATE statement
$result = mysqli_query($connection, $query);
// Check if the query was successful
if (!$result) {
die("Error updating record: " . mysqli_error($connection));
}
// Check the number of affected rows
$affected_rows = mysqli_affected_rows($connection);
echo "Number of rows updated: " . $affected_rows;
// Close the connection
mysqli_close($connection);
?>
11. Explain the process of retrieving query results in PHP after executing a SELECT
statement in MySQL with code example.
Execute the SELECT Statement: Use the mysqli_query() function to execute the SELECT
statement.
Fetch the Results: Use functions like mysqli_fetch_assoc(), mysqli_fetch_array(), or
mysqli_fetch_row() to fetch the result set row by row. These functions return the data in different
formats (associative array, numeric array, or both).
Process the Results: Use a loop to iterate over the result set and process each row. You can access
the columns of each row using the associative or numeric indices.
Free the Result Set: After processing the results, free the memory associated with the result set
using mysqli_free_result().
Close the Connection: Close the MySQL connection using mysqli_close() when done.
Example:
<?php
// MySQL server configuration
$hostname = "localhost"; // Change this to your MySQL server hostname
$username = "username"; // Change this to your MySQL username
$password = "password"; // Change this to your MySQL password
$database = "dbname"; // Change this to the name of your database
// Establishing a connection to MySQL
$connection = mysqli_connect($hostname, $username, $password, $database);
// Check if the connection was successful
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// Execute the SELECT statement
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// Check if the query was successful
if (!$result) {
die("Error executing query: " . mysqli_error($connection));
}
// Fetch and process the results
while ($row = mysqli_fetch_assoc($result)) {
// Process each row of the result set
echo "User ID: " . $row['id'] . ", Username: " . $row['username'] . "<br>";
}
// Free the result set
mysqli_free_result($result);
// Close the connection
mysqli_close($connection);
?>

You might also like