chap-4
chap-4
The MySQL client is a command-line tool that allows users to interact with a MySQL database server. It
provides a text-based interface to perform various database operations such as querying data, modifying
• The MySQL client operates through the command line, making it lightweight and scriptable.
• Users can enter SQL commands directly into the terminal to interact with the database.
2. SQL Execution:
• The primary purpose of the MySQL client is to execute SQL queries. These can include commands for
3. Database Administration:
• The MySQL client allows administrators to manage databases, users, and permissions.
• Commands like `CREATE DATABASE`, `GRANT`, and `FLUSH PRIVILEGES` can be executed to
• The client can be used to export and import database data using commands like `mysqldump` for
5. Script Automation:
• SQL scripts can be executed through the MySQL client, enabling automation of repetitive tasks.
• Batch processing of SQL commands can be achieved by redirecting input from a file.
6. Connectivity Options:
• The client can connect to MySQL servers locally or remotely using TCP/IP.
1. Connecting to the Server :To connect to a MySQL server, you need to know the server’s hostname
(or IP address), the port number (default is 3306), the username, and the password.
Example Command
Explanation:
• `-h localhost`: Specifies the host where the MySQL server is running. `localhost` means it’s running on
• `-u root`: Specifies the username to connect as. In this example, `root` is used, which is the default
administrative user.
• `-p`: Prompts for the password for the specified user. You will be prompted to enter the password after
2. Executing SQL Commands: Once connected, you can start executing SQL commands.
Example Commands
SHOW DATABASES;
USE mydatabase;
Explanation:
• `USE mydatabase;`: Selects the database named `mydatabase` to use. This is necessary before
• `SELECT * FROM users;`: Selects and displays all records from the `users` table in the currently
selected database.
3. Command-Line Options: The MySQL client supports various command-line options to customize its
behavior.
Common Options:
Example Command
Explanation:This command connects to the MySQL server on `localhost` as the `root` user, prompts for
the password, executes the `SHOW DATABASES;` command, and then exits.
Exporting Data: To export a database to a file, you use the `mysqldump` command.
Example Command
Explanation:
• `-h localhost`: Specifies the host where the MySQL server is running.
Importing Data
Example Command
• `-h localhost`: Specifies the host where the MySQL server is running.
To exit the MySQL client, simply type `EXIT;` or `QUIT;` at the MySQL prompt.
Example Command
EXIT;
`EXIT;`: Command to exit the MySQL client. You will be returned to the
USING phpMyAdmin
phpMyAdmin is a popular web-based interface for managing MySQL databases. It simplifies database
management tasks such as creating databases, running queries, and managing users. Here’s a detailed
A convenient way to install all these components is to use a software bundle like XAMPP or WAMP, which
2. Install XAMPP: Run the downloaded installer and follow the installation instructions.
• Start the Apache and MySQL services by clicking the “Start” buttons next to each.
II . Accessing phpMyAdmin
After installing and starting XAMPP, you can access phpMyAdmin via your web browser:
• Leave the password field empty unless you have set a root password for MySQL.
IV . Using phpMyAdmin: Dashboard Overview-Once logged in, you’ll see the phpMyAdmin dashboard
• Left Panel: Lists all databases. You can click on a database to view its tables.
• Right Panel: Shows various tabs for performing actions like browsing data, running SQL queries,
User Interface Graphical User Interface (GUI) Command Line Interface (CLI)
(UI)
Ease of Use Easier to learn and use, Requires knowledge of MySQL commands and
Speed Generally slower than CLI for Faster for experienced users due to direct
browser
Security Requires secure web server More secure due to direct connection (less
Power & Limited to basic functions with Full access to all MySQL functionalities
MYSQL FUNCTIONS
MySQL database server using the MySQLi (MySQL Improved) extension. MySQLi provides improved
performance and security features over the older MySQL extension. Here's a detailed explanation of how
Syntax
1. hostname: The hostname or IP address of the MySQL server. The default value is 'localhost'.
5. port (optional): The port number to use when connecting to the MySQL server. The default MySQL port
is 3306.
6. socket (optional): The socket or named pipe to use for the connection.
Return Value
• On success: Returns a MySQLi link identifier, which is a resource representing the connection to the
MySQL server.
Example
$host = "localhost";
$username = "your_username";
HCES BCA GADAG
8 Accessing Mysql
$password = "your_password";
$database = "your_database";
Use the `mysqli_connect` function to attempt a connection to the MySQL server.If the connection is
In PHP, the `mysqli_query` and `mysqli_multi_query` functions are used to perform SQL queries against a
MySQL database. These functions are part of the MySQLi extension, which provides a procedural and
mysqli_query: The `mysqli_query` function is used to execute a single SQL query. This function can be
used for a variety of SQL commands such as `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and others.
Return Value: For `SELECT`, `SHOW`, `DESCRIBE`, or `EXPLAIN` queries, `mysqli_query` returns a
`mysqli_result` object representing the result set. For other types of queries, it returns `true` on success or
`false` on failure.
email VARCHAR(50),
)";
if (mysqli_query($conn, $sql)) {
} else {
`mysqli_multi_query`
The `mysqli_multi_query` function is used to execute multiple SQL queries in a single call. This can be
useful for batch processing or when you need to perform multiple related operations at once.
• $query: The SQL query string containing multiple queries separated by semicolons.
$sql = "
INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]');
INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]');
";
if (mysqli_query($conn, $sql)) {
} else {
• Single vs. Multiple Queries: `mysqli_query` is designed for executing a single query, whereas
• Result Handling: When using `mysqli_multi_query`, you need to handle multiple result sets if your
queries return data (e.g., `SELECT` queries). You need to loop through the results using
`mysqli_next_result`.
• Use Cases: `mysqli_query` is typically used for simpler, one-off queries. `mysqli_multi_query` is used
for batch operations or when executing multiple related queries together, such as setting up a database
When working with MySQL databases in PHP, you often need to retrieve and process query results.
MySQLi provides several functions for fetching rows from a result set.
Fetching Results -fetch and display the results using different MySQLi fetching functions.
if (mysqli_num_rows($result) > 0) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . " - Email: " . $row["email"]
. "<br>";
}}
2.`mysqli_fetch_row`: The `mysqli_fetch_row` function fetches a result row as a numeric array, where the
if (mysqli_num_rows($result) > 0) {
echo "id: " . $row[0] . " - Name: " . $row[1] . " " . $row[2] . " - Email: " . $row[3] . "<br>";
$resulttype: This defines the type of array that should be produced. It can be one of the following constants:
if (mysqli_num_rows($result) > 0) {
echo "id: " . $row[0] . " - Name: " . $row[“name] . " " . $row[2] . " - Email: " . $row[3] . "<br>";
4. `mysqli_fetch_object`: The `mysqli_fetch_object` function fetches a result row as an object, where the
if (mysqli_num_rows($result) > 0) {
echo "id: " . $row->id . " - Name: " . $row->firstname . " " . $row->lastname . " - Email: " . $row->email
. "<br>";
1. mysqli_connect_error(): Retrieves the error message associated with the last attempt to establish a
Syntax: mysqli_connect_error();
Output:Connection failed: Access denied
if (!$conn) { for user 'incorrect_username'@'localhost'
} else {
2. mysqli_error(): Retrieves the error message generated by the most recent MySQLi function call, not
just mysqli_connect(). It can be used to capture errors that occur after a successful connection, such as
Syntax: mysqli_error($conn);
if (!$result) {
Output Error running query: You have an error in your SQL syntax
3. mysqli_errno():Returns the error code for the last MySQLi function call. Error codes provide a more
granular way to identify the specific problem, often corresponding to error messages returned by
mysqli_error().
Syntax: mysqli_errno($conn);
Output
mysqli_real_escape_string: This function escapes special characters in a string for use in an SQL
$unsafe_string = "O'Reilly";
if (mysqli_query($conn, $query)) {
} else {
In this example, the apostrophe in the string O'Reilly is escaped to prevent SQL injection and syntax errors.
mysqli_affected_rows: This function returns the number of rows affected by the last INSERT, UPDATE,
Example:
if (mysqli_query($conn, $query)) {
$affected_rows = mysqli_affected_rows($conn);
} else {
In this example, the number of rows affected by the UPDATE query is displayed.
$num_rows = mysqli_num_rows($result);
In this example, the number of rows in the result set from the SELECT query is displayed.
mysqli_insert_id: This function returns the auto-generated ID used in the last query.
$query = "INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')";
if (mysqli_query($conn, $query)) {
$last_id = mysqli_insert_id($conn);
} else {
}In this example, after inserting a new record, the auto-generated ID of the inserted record is displayed.
To select or create a database in MySQL using PHP, you can use the `mysqli_select_db` function to select
an existing database or `mysqli_query` to create a new one. Below are examples of both scenarios:
<?php
specified by `$database`.
$database = "existing_database";
• If the database selection fails,
$conn = mysqli_connect($host, $username, $password);
`mysqli_select_db` returns
if (!mysqli_select_db($conn, $database)) {
mysqli_close($conn);
?>
HCES BCA GADAG
18 Accessing Mysql
<?php
$host = "localhost";
$username = "your_username";
$password = "your_password";
$new_database = "new_database";
if (mysqli_query($conn, $query)) {
} else {
mysqli_close($conn);
?>
In this example:
• `$query` contains the SQL query to create a new database with the specified name.
• `mysqli_query($conn, $query)` executes the SQL query. If the query is successful, it returns `TRUE`.
Otherwise, it returns `FALSE`, and you can use `mysqli_error($conn)` to get the error message.
Updating records in MySQL database using PHP involves using the `UPDATE` SQL statement along with
Assume you have a table named `users` with columns `id`, `firstname`, `lastname`, and `email`. Here's
<?php
$host = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
if (!$conn) {
$new_firstname = "abc";
$new_lastname = "xyz";
$new_email = "[email protected]";
if (mysqli_query($conn, $query)) {
} else {
mysqli_close($conn);
?>
database.
3. Update Data: Define variables `$id`, `$new_firstname`, `$new_lastname`, and `$new_email` with
the updated values you want to set for the record with `id=1`.
4. SQL Query:
5. Executing the Query:Use `mysqli_query($conn, $query)` to execute the SQL query. If successful,
6. Error Handling: Check if the query executed successfully. If not, print the error message using
`mysqli_error($conn)`.