0% found this document useful (0 votes)
22 views9 pages

UNIT 5-part 2

The document provides an overview of MySQL commands and functions, including creating and managing databases and tables, executing queries, and using prepared statements in PHP. It emphasizes the importance of security and efficiency in database operations, particularly through the use of prepared statements to prevent SQL injection. Additionally, it outlines the setup and installation process for PHP and MySQL, as well as the functionality of the MySQL client for database management.

Uploaded by

sonuaishu47
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)
22 views9 pages

UNIT 5-part 2

The document provides an overview of MySQL commands and functions, including creating and managing databases and tables, executing queries, and using prepared statements in PHP. It emphasizes the importance of security and efficiency in database operations, particularly through the use of prepared statements to prevent SQL injection. Additionally, it outlines the setup and installation process for PHP and MySQL, as well as the functionality of the MySQL client for database management.

Uploaded by

sonuaishu47
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/ 9

MySQL Commands:

1. Create a Database: Creates a new database with the specified name.


Example:
CREATE DATABASE college;
2. Drop (Delete) a Database: Deletes an existing database and all its contents.
Example:
DROP DATABASE college;
3. Create a Table:
Defines a new table within the selected database with specified columns and data types.
Example:
CREATE TABLE student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
regno VARCHAR(100)
);
4. Drop (Delete) a Table: Deletes an existing table and all its data.
Example:
DROP TABLE student;
5. Alter a Table Structure: Modifies an existing table's structure, such as adding a new column.
Example:
ALTER TABLE student
ADD birthdate DATE;
6. Insert Data into a Table: Adds a new row to a table with specified values for each column.
INSERT INTO student (name, regno)
VALUES ('John', 'bc123');
7. Update Existing Data: Modifies existing records in a table based on a condition.
Example:
UPDATE student
SET reg_no = 'bc126'
WHERE name = 'John';
8. Delete Data from a Table: Removes records from a table based on a specified condition.
Example:
DELETE FROM users
WHERE name = 'John';
Select Data from a Table: Explanation: Retrieves data from one or more columns of a table
MySQL Functions:

Dept of BCA ,SRNMNC, Page 1


1. Connect()
This function is used to establish a connection to the MySQL database. The connect() function in
MySQLi is part of the mysqli object-oriented or procedural approach. It is commonly used as new
mysqli() in object-oriented style.
Syntax:
$connection = new mysqli($servername, $username, $password, $dbname);
Example:
$connection = new mysqli("localhost", "root", "", "student");
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
This statement creates a connection to the database “student”, if failed , print the message “ Connection
failed” and terminate execution.
2. query()
This function is used to execute a MySQL query. The query() function is used to perform a
query against the database.
Syntax:
$result = $connection->query($sql);
Example:
$sql = "SELECT * FROM Std";
$result = $connection->query($sql);
These statements execute select all the data from table std and selected data rows are stored in $result.

3. Prepare
This function prepares an SQL statement for execution. The prepare() function is used to prepare an
SQL statement for execution. It’s useful for preventing SQL injection by separating SQL logic from
data.
$stmt = $connection->prepare($sql);
$stmt = $connection->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
Here, insert query is created as a prepared statement with placeholder ‘?’ which will be later replaced
by using bind_param() beore execution.

4. bind_param()

Dept of BCA ,SRNMNC, Page 2


This function binds variables to the prepared statement as parameters. The bind_param() function
is used to bind variables to the placeholders in a prepared SQL statement.
Synatx:
$stmt->bind_param("ss", value1, value2);
Example:
$username = "john";
$email = "[email protected]";
$stmt->bind_param("ss", $username, $email);
"ss": Indicates the types of the variables (s for string) and $username, $email: Variables to bind. When
using bind_param() in PHP with MySQL, we specify the data types of the variables that will be bound
to the prepared statement. The data types are represented by specific characters. We use ‘s’ for string
, ‘i’ for integer, ‘d’ for double data, ‘b’ for binary data. The number of characters in the string passed
to bind_param() directly corresponds to the number of values to be bound to the placeholders (?) in
the SQL statement. If we use "sid", it means we are binding three parameters, and each of those
parameters is expected to be a string (s), integer (i), double (d).

5. Execute()
This function executes a prepared query. The execute() function is used to execute a prepared
statement.
Syntax:
$stmt->execute();
Example:
$username = "john";
$email = "[email protected]";
$stmt->bind_param("ss", $username, $email);
$stmt->execute();
6. fetch_assoc:
This function fetches a result row as an associative array. The fetch_assoc() function fetches a result
row as an associative array where the keys are the column names.
Syntax:
$row = $result->fetch_assoc();
Example:
while($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"] . " - Email: " . $row["email"] . "<br>";
}
The fetch_assoc() method fetches the next row from the result set as an associative array.

Dept of BCA ,SRNMNC, Page 3


$row is an array where each key corresponds to a column name from the result set.
The while loop continues to run as long as there are rows in the result set. Each iteration fetches the
next row.
7. Close():
This function closes the database connection. The close() function is used to close an open database
connection.
Syntax:
$connection->close();
Example:
$connection->close();
Example Program:
// 1. Connect to the database
$connection = new mysqli("localhost", "root", "password", "database_name");

// 2. Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}

// 3. Prepare an SQL statement


$stmt = $connection->prepare("INSERT INTO users (username, email) VALUES (?, ?)");

// 4. Bind parameters
$username = "john_doe";
$email = "[email protected]";
$stmt->bind_param("ss", $username, $email);

// 5. Execute the statement


$stmt->execute();

// 6. Close the statement and connection


$stmt->close();
$connection->close();

Prepared Statements in PHP:

Dept of BCA ,SRNMNC, Page 4


Prepared statements are a feature in PHP used to execute SQL queries efficiently and securely. They
consist of two main phases: The SQL query is sent to the database with placeholders instead of actual
values. The database parses, compiles, and optimizes the query for execution. The actual values are
bound to the placeholders and the query is executed. This can be done multiple times with different
values without the need to recompile the query.
Prepared statements are used for the following reasons:
1. Security - Prevent SQL Injection:
SQL injection is a common security vulnerability where an attacker can execute
arbitrary SQL code by manipulating query inputs.Prepared statements mitigate this risk
by separating SQL logic from data. User inputs are treated as data, not executable code.
2. Efficiency:
Prepared statements can be executed multiple times with different parameters, without
recompiling the SQL statement. This reduces the overhead, especially in applications
with repeated queries.
3. Code Clarity:
Prepared statements make the code more readable by clearly separating the query logic
from the data.
When to Use Prepared Statements:
Whenever user input is involved: Any time a query involves user input (e.g., form data, URL
parameters), you should use prepared statements to ensure that the input is handled securely.
For repeated execution of the same query: When the same query needs to be executed
multiple times with different parameters, prepared statements can improve performance.

Example:
$stmt = $connection->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
$stmt->execute();
Example Script:
$connection = new mysqli("localhost", "root", "password", "database_name");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$stmt = $connection->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$username = "john_doe";
$email = "[email protected]";
$stmt->bind_param("ss", $username, $email);
$stmt->execute();

Dept of BCA ,SRNMNC, Page 5


$stmt->close();
$connection->close();

Executing Simple quires:


To execute simple queries in PHP, you can use the mysql. Below is a basic example using mysql to
execute queries like SELECT, INSERT, UPDATE, and DELETE.
1. Connecting to the Database
$connection = new mysqli("localhost", "root", "password", "database_name");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
2. Executing select query
$result = $connection->query("SELECT username, email FROM users");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"] . " - Email: " . $row["email"] . "<br>";
}
} else {
echo "No results found.";
}
3. Executing an INSERT query
$sql = "INSERT INTO users (username, email) VALUES ('jane_doe', '[email protected]')";

if ($connection->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
}
4. Executing UPDATE query
$sql = "UPDATE students SET register_number='67890' WHERE student_name='John Doe'"; if
($connection->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error
updating record: " . $connection->error; }

5. Executing DELETE query:


$sql = "DELETE FROM students WHERE student_name='John Doe'";

Dept of BCA ,SRNMNC, Page 6


if ($connection->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $connection->error;
}
6. Closing connection
$connection->close();

Retrieving Query results:


To retrieve query results in PHP using mysql , we can use the query() method to execute the query and
then fetch the results using methods like fetch_assoc(), fetch_array(), or fetch_row(). Below is an
example demonstrating how to retrieve and display query results:
$connection = new mysqli("localhost", "root", "password", "database_name");

if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$sql = "SELECT student_name, register_number FROM students";
$result = $connection->query($sql);

1. Retrieving results using fetch assoc():


This method fetches a result row as an associative array, where the column names are the keys.
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Student Name: " . $row["student_name"] . " - Register Number: " . $row["register_number"]
. "<br>";
}
} else {
echo "No results found.";
}

2. Retreiving using fetch array():


This method fetches a result row as both an associative array and a numeric array
if ($result->num_rows > 0) {

Dept of BCA ,SRNMNC, Page 7


while ($row = $result->fetch_array()) {
echo "Student Name: " . $row[0] . " - Register Number: " . $row[1] . "<br>";
}
} else {
echo "No results found.";
}

3. Retrieving results using fetch_row()


This method fetches a result row as a numeric array, where the column values are accessed by their
index.
if ($result->num_rows > 0) {
while ($row = $result->fetch_row()) {
echo "Student Name: " . $row[0] . " - Register Number: " . $row[1] . "<br>";
}
} else {
echo "No results found.";
}

Set Up and Installation process:


1. Prerequisites
Before you can use PHP and MySQLi (MySQL Improved Extension) to develop and run web
applications, you need to ensure that the following prerequisites are met:
• Web Server: A web server such as Apache or Nginx to serve your PHP scripts.
• PHP: The PHP programming language installed on your system.
• MySQL Database Server: The MySQL or MariaDB database server installed for storing and
managing your data.
• MySQLi Extension: The MySQLi extension for PHP, which allows PHP to communicate with
the MySQL database.
2. Common Ports
• HTTP Port: 80 - The default port used by web servers to serve web pages over HTTP.
• HTTPS Port: 443 - The default port used for secure HTTPS connections.
• MySQL Port: 3306 - The default port used by MySQL database servers to listen for
connections.
3. Setup and Installation Procedure
Step 1: Installing a Web Server, PHP, and MySQL
1. Download XAMPP:

Dept of BCA ,SRNMNC, Page 8


o Download XAMPP from the official website.
2. Install XAMPP:
o Run the installer and follow the prompts to install XAMPP, which includes Apache
(web server), PHP, and MySQL.
3. Start XAMPP:
o Open the XAMPP Control Panel and start Apache and MySQL.

MySQL client:
The MySQL client is a command-line utility designed for interacting with MySQL database
servers. It provides a direct way to connect to the server, execute SQL queries, and manage databases
from the terminal. Users can perform a wide range of tasks, including creating and modifying databases,
querying data, and handling administrative functions such as backups and restores. The client is highly
efficient for these tasks, allowing for quick and precise control over database operations.
While the MySQL client does not offer a graphical user interface, it compensates with powerful
features and flexibility. It supports secure connections via SSL to ensure encrypted communication
between the client and the server. Additionally, the client can execute SQL scripts, making it ideal for
automating repetitive tasks and managing complex operations. Although it may have a steeper learning
curve for those unfamiliar with command-line tools or SQL, it remains an essential tool for developers
and database administrators who require robust database management capabilities.

Dept of BCA ,SRNMNC, Page 9

You might also like