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

UNIT 5-Part 2

The document provides a comprehensive guide on MySQL commands and functions, including creating and deleting databases and tables, inserting, updating, and deleting data, as well as connecting to a MySQL database using PHP. It explains the use of prepared statements for secure and efficient query execution, along with examples of executing simple queries and retrieving results. Additionally, it outlines the prerequisites and installation process for setting up a web server, PHP, and MySQL for development purposes.

Uploaded by

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

UNIT 5-Part 2

The document provides a comprehensive guide on MySQL commands and functions, including creating and deleting databases and tables, inserting, updating, and deleting data, as well as connecting to a MySQL database using PHP. It explains the use of prepared statements for secure and efficient query execution, along with examples of executing simple queries and retrieving results. Additionally, it outlines the prerequisites and installation process for setting up a web server, PHP, and MySQL for development purposes.

Uploaded by

mohammedawt1605
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 9
MySQL Comman 1. Create a Database: Creates a new database with the speci 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) dv 4, Drop (Delete) a Table 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’, ‘be123}); 7. Update Existing Data: Modifies existing records in a table based on a condition, Example: UPDATE student SET reg_n WHERE name = ‘John’ 'bel26 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 conneet() 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: ‘Sconnection = new mysqli(Sservername, Susername, Spassword, Sdbname); Example: Sconnection = new mysqli("localhost", "root", "", "student”): 1 Check connection if (Sconnection->connect_error) { die(’Connection failed: " . Sconnection->connect_error); , This statement creates a connection to the database “student”, iff 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 = Sconnection->query(Ssql); ‘SELECT * FROM Std’ Sconnection->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); ‘Sstmt = Sconnection->prepare("INSERT INTO users (username, email) VALUES (2, 2)"); Here, insert query is created as a prepared statement with placeholder *2” 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 Sstmt->bind_param("ss”, valuel, value?) Example: $username = "john"; Semail = "[email protected]"; ‘Sstmt->bind_param("ss", Susername, Semail) "ss": Indicates the types of the variables (s for string) and Susername, $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 , ‘’ for integer, ‘c’ 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: Susername Semail Sstmt->bind_param("ss", Susername, Semail); john’; *[email protected]"; Sstmt->execute(); 6. fetch_assoe: ‘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: Srow = Sresult->fetch_assoe(); Example: while($row result->Fetch_assoc)) { echo "Username: " . Srow{"username”] . " - Email: " . Srow|"email"] } The fetch_assoc() method fetches the next row from the result set as an "elose(); Sconnection->close(); Example Program: 11, Connect to the database Sconnection = new mysqli("localhost”, "oot", 12, Check connection if (Sconnection->connect_error) { die "Connection failed: " . Sconnection->conneet_error); 13, Prepare an SQL statement Sstmt = Sconnection->prepare("INSERT INTO users (username, email) VALUES (?, 2) 1/4, Bind parameters john_doe" Susermame: Semail $stmt->bind_param john @example.com’ ", username, Semail); 1/5, Execute the statement Sstmt-Sexecute(); 1/6, Close the statement and connection Sstmt->elose(): Sconnection->close(); Prepared Statements in PHP: ‘password, “database_name"); Dept of BCA SRNMNC, Page + 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. Bfficieney: 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 = Sconnection-> prepare(" INSERT INTO users (username, email) VALUES (?, 2)"); ‘Sstiit->bind_param( "ss", Susername, Semail); Sstmt-rexecuted) Example Script: Sconnection = new mysqli("Iocalhost”, "root", "password", “database_name"); if (Sconnection->connect_error) { die("Connection failed: 1 Sstmt = Sconnection->prepare("INSERT INTO users (username, email) VALUES (°, 2)"; Sconnection->connect_error); "john_doe"; Dept of BCA SRNMNC, Page 5 $stmt->bind_param("ss", $username, Semail); Sstmt-rexecute(); Sstmt->elose(): Sconnection->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 Sconnection = new mysqli("localhost”, "root", "passwor ‘database_name"); if (Sconnection->connect_error) { die("Connection failed: " . Sconnection->connect_error); ) 2. Executing select query Sresult = Sconnection->query("SELECT username, email FROM users"); if (Sresult->num_rows > 0) { while (Stow = Sresult-fetch_assoc)) { echo "Username: " . $row{"username"] ." - Email: ". Srow{"email"] . "
"; } J else { echo "No results found. } 3. Executing an INSERT query $sql = "INSERT INTO users (username, email) VALUES (jane_doe’, [email protected])"; if (Sconnection->query($sql) === TRUE) { echo "New record created successfully"; Jelse { echo "Error: ". $sql ."sbr>" . Sconnection->error; ) 4, Executing UPDATE query Ssql = "UPDATE students SET register_number='67890° WHERE. student_nam« John. Doe"; if (Sconnection->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . Sconnection->error; } 5. Executing DELETE query: Dept of BCA SRNMNC, Page 6 $sql = "DELETE FROM students WHERE student_nam if (Sconnection->query(Ssql) === TRUE) { echo "Record deleted successfully"; Jelse ( ‘echo "Error deleting record: " . Sconnection->error, } 6. Closing connection Sconnection->closeQ); 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: Sconnection = new mysqli( “localhost”, “root”, “password”, “database_name”); if (Sconnection->connect_error) { die("Connection failed: " . $connection->connect_error); ) $sql $result = Sconneetion->query(Ssql): ‘SELECT student_name, register_number FROM students"; 1. Retrieving results using fetch assoc(): This method fetches a result row as an associative array, where the column names are the keys if (Sresult->num_rows > 0) { while (Srow = Sresult->fetch_assoc()) { ‘ho "Student Name: Srow["student_name"] - Register Number: J else { echo "No results found. 2. Retreiving using fetch array( Dept of BCA SRNMNC, Page 7 This method fetches a result row as both an associative array and a numeric array if (Sresult->num_rows > 0) { while (Stow = Sresult->fetch_array()) { echo "Student Name: " . $row{0) . " } J else { "Register Number: " . $row 1] . "
"; echo "No results found." 43. 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 (Gresult->num_rows > 0) { while (Srow = Sresult->fetch_row() ( echo "Student Name: " . Srow{0] ." - Register Number: " . $row[1] . "
"; ) Jelse { 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 Dept of BCA SRNMNC, Page 8 Step 1: Installing a Web Server, PHP, and MySQL 1. Download XAMPP: © Download XAMPP from the official website 2. Install XAMPP: Run the installer and follow the prompts to install XAMPP, which includes Apache (web server), PHP, and MySQL. 3. Start XAMPP: © Open the XAMPP Control Panel and start Apache and MySQL. MySQL ‘The MySQL client is a command-line utility designed for interacting with MySQL database ent: 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 execut © 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