1 Accessing Mysql
WHAT IS MYSQL CLIENT
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
data, and managing database structures
Key Features of MySQL Client
1. Command-Line Interface (CLI):
• 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
creating, reading, updating, and deleting data (CRUD operations).
• It supports all standard SQL operations as well as MySQL-specific features.
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
configure the MySQL server.
4. Data Export and Import:
• The client can be used to export and import database data using commands like `mysqldump` for
exporting and `mysqlimport` for importing.
• This is useful for backup and restoration purposes.
5. Script Automation:
• SQL scripts can be executed through the MySQL client, enabling automation of repetitive tasks.
HCES BCA GADAG
2 Accessing Mysql
• 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.
• Connection parameters include the hostname, port, username, and password.
HOW TO CONNECT TO MYSQL CLIENT
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
mysql -h localhost -u root -p
Explanation:
• `mysql`: The command to start the MySQL client.
• `-h localhost`: Specifies the host where the MySQL server is running. `localhost` means it’s running on
the same machine.
• `-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
running the command.
2. Executing SQL Commands: Once connected, you can start executing SQL commands.
Example Commands
SHOW DATABASES;
USE mydatabase;
SELECT * FROM users;
HCES BCA GADAG
3 Accessing Mysql
Explanation:
• `SHOW DATABASES;`: Lists all databases on the MySQL server.
• `USE mydatabase;`: Selects the database named `mydatabase` to use. This is necessary before
performing any operations on the database.
• `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:
• `-h, --host`: Specify the MySQL server host.
• `-u, --user`: Specify the MySQL user.
• `-p, --password`: Prompt for the password.
• `-D, --database`: Specify the default database to use.
• `-e, --execute`: Execute the specified statement and exit.
Example Command
mysql -h localhost -u root -p -e "SHOW DATABASES;
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.
4. Exporting and Importing Data
Exporting Data: To export a database to a file, you use the `mysqldump` command.
Example Command
mysqldump -h localhost -u root -p mydatabase > backup.sql
HCES BCA GADAG
4 Accessing Mysql
Explanation:
• `mysqldump`: The utility to export the database.
• `-h localhost`: Specifies the host where the MySQL server is running.
• `-u root`: Specifies the username to connect as.
• `-p`: Prompts for the password.
• `mydatabase`: The name of the database to export.
• `> backup.sql`: Redirects the output to a file named `backup.sql`.
Importing Data
To import data from a file, you use the `mysql` command.
Example Command
mysql -h localhost -u root -p mydatabase < backup.sql
• `mysql`: The command to start the MySQL client.
• `-h localhost`: Specifies the host where the MySQL server is running.
• `-u root`: Specifies the username to connect as.
• `-p`: Prompts for the password.
• `mydatabase`: The name of the database to import data into.
• `< backup.sql`: Redirects the input from the file `backup.sql`.
5. Exiting the MySQL Client
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
HCES BCA GADAG
5 Accessing Mysql
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
guide on how to use phpMyAdmin on Windows:
A convenient way to install all these components is to use a software bundle like XAMPP or WAMP, which
includes Apache, MySQL, and PHP.
Installing phpMyAdmin with XAMPP
1. Download XAMPP: Go to the [XAMPP website](https://www.apachefriends.org/index.html) and
download the installer for Windows.
2. Install XAMPP: Run the downloaded installer and follow the installation instructions.
3. Start Apache and MySQL:
• Open the XAMPP Control Panel.
• Start the Apache and MySQL services by clicking the “Start” buttons next to each.
4. Access phpMyAdmin: Open a web browser and go to `http://localhost/phpmyadmin`.
II . Accessing phpMyAdmin
After installing and starting XAMPP, you can access phpMyAdmin via your web browser:
• Open a web browser and navigate to `http://localhost/phpmyadmin`.
• You will see the phpMyAdmin login page.
III . Logging into phpMyAdmin
1. Login with Root User:
• By default, you can log in as the `root` user.
• The default username is `root`.
HCES BCA GADAG
6 Accessing Mysql
• Leave the password field empty unless you have set a root password for MySQL.
• Click “Go” to log in.
IV . Using phpMyAdmin: Dashboard Overview-Once logged in, you’ll see the phpMyAdmin dashboard
with the following key sections:
• 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,
importing/exporting data, and managing users.
phpMyAdmin vs. MySQL Client (CLI)
Feature phpMyAdmin MySQL Client (CLI)
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
especially for beginners syntax
Speed Generally slower than CLI for Faster for experienced users due to direct
complex tasks interaction
Accessibility Accessible from any web Requires access to a command line
browser
Security Requires secure web server More secure due to direct connection (less
configuration vulnerable to man-in-the-middle attacks)
Power & Limited to basic functions with Full access to all MySQL functionalities
Flexibility option for raw SQL
Batch Can be cumbersome for Ideal for scripting and automation
Processing repetitive tasks
Customization Limited customization options Highly customizable through scripting
HCES BCA GADAG
7 Accessing Mysql
MYSQL FUNCTIONS
1. mysqli_connect: `mysqli_connect` is a function in PHP that allows you to establish a connection to a
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
`mysqli_connect` works and how to use it.
Syntax
mysqli_connect(hostname, username, password, database, port, socket);
1. hostname: The hostname or IP address of the MySQL server. The default value is 'localhost'.
2. username: The MySQL username to use for authentication.
3. password: The password to use for authentication.
4. database: The name of the database to connect to.
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.
• On failure: Returns `FALSE`.
Example
Step 1: Initialize Connection Variables
$host = "localhost";
$username = "your_username";
HCES BCA GADAG
8 Accessing Mysql
$password = "your_password";
$database = "your_database";
$port = 3306; // optional
$socket = ""; // optional
Step 2: Establish the Connection
$conn = mysqli_connect($host, $username, $password, $database, $port, $socket);
Use the `mysqli_connect` function to attempt a connection to the MySQL server.If the connection is
successful, `$conn` will hold a resource representing the connection.
3. Check the Connection:
The `if` statement checks if the connection was
successful. If not, it calls `die` with an error message
if (!$conn) { obtained from `mysqli_connect_error()`. This function
returns a string description of the last connection error.If
the connection is successful, it prints a success
die("Connection failed: " . mysqli_connect_error()); message.
}echo "Connected successfully";
2. `mysqli_query` and `mysqli_multi_query`(EXECUTING SIMPLE QUERIES)
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
object-oriented interface for accessing MySQL databases.
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.
Syntax: mysqli_query($connection, $query)
• $connection: The MySQLi connection object connection variable.
• $query: The SQL query string to be executed.
HCES BCA GADAG
9 Accessing Mysql
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.
// SQL query to create a table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
email VARCHAR(50),
)";
// Execute the query
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
`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.
Syntax: mysqli_multi_query($connection, $query)
• $connection: The MySQLi connection object.
• $query: The SQL query string containing multiple queries separated by semicolons.
HCES BCA GADAG
10 Accessing Mysql
Return Value: Returns `true` on success or `false` on failure.
Example: Executing Multiple Queries
// SQL query string containing multiple queries
$sql = "
INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john.doe@example.com');
INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary.moe@example.com');
INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley',
'julie.dooley@example.com');
SELECT id, firstname, lastname, email FROM MyGuests;
";
// Execute the queries
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
Differences Between `mysqli_query` and `mysqli_multi_query`
• Single vs. Multiple Queries: `mysqli_query` is designed for executing a single query, whereas
`mysqli_multi_query` allows for executing multiple queries in a single call.
HCES BCA GADAG
11 Accessing Mysql
• 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
schema or performing complex transactions.
Fetching Results with MySQLi in PHP(RETRIEVING QUERY RESULTS)
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.
// SQL query to select data
$sql = "SELECT id, firstname, lastname, email FROM MyGuests";
$result = mysqli_query($conn, $sql);
Fetching Results -fetch and display the results using different MySQLi fetching functions.
1.`mysqli_fetch_assoc` : The `mysqli_fetch_assoc` function fetches a result row as an associative array,
where the keys are the column names.
Syntax: array mysqli_fetch_assoc( $result)
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . " - Email: " . $row["email"]
. "<br>";
}}
HCES BCA GADAG
12 Accessing Mysql
2.`mysqli_fetch_row`: The `mysqli_fetch_row` function fetches a result row as a numeric array, where the
keys are the column numbers starting from 0.
Syntax: array mysqli_fetch_row($result)
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_row($result)) {
echo "id: " . $row[0] . " - Name: " . $row[1] . " " . $row[2] . " - Email: " . $row[3] . "<br>";
3. `mysqli_fetch_array`: The `mysqli_fetch_array` function fetches a result row as an associative array,
a numeric array, or both.
Syntax: array mysqli_fetch_array($result, $resulttype )
$resulttype: This defines the type of array that should be produced. It can be one of the following constants:
• `MYSQLI_ASSOC` for an associative array.
• `MYSQLI_NUM` for a numeric array.
• `MYSQLI_BOTH` for both associative and numeric array.
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo "id: " . $row[0] . " - Name: " . $row[“name] . " " . $row[2] . " - Email: " . $row[3] . "<br>";
HCES BCA GADAG
13 Accessing Mysql
4. `mysqli_fetch_object`: The `mysqli_fetch_object` function fetches a result row as an object, where the
properties are the column names.
Syntax: object mysqli_fetch_object($result)
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_object($result)) {
echo "id: " . $row->id . " - Name: " . $row->firstname . " " . $row->lastname . " - Email: " . $row->email
. "<br>";
All the above fetch code will have output like
ID: 1, Name: John Doe
ID: 2, Name: Mary Moe
ID: 3, Name: Julie Dooley
ERROR HANDLING FUNCTIONS
1. mysqli_connect_error(): Retrieves the error message associated with the last attempt to establish a
connection to the MySQL server using mysqli_connect().
Syntax: mysqli_connect_error();
Output:Connection failed: Access denied
if (!$conn) { for user 'incorrect_username'@'localhost'
echo "Connection failed: " . mysqli_connect_error(); (using password: YES)
} else {
echo "Connected successfully!"; // This won't be executed in this case}
HCES BCA GADAG
14 Accessing Mysql
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
invalid queries, syntax errors, or permission issues.
Syntax: mysqli_error($conn);
$sql = "SELECT * FROM non_existent_table"; // Invalid query
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "Error running query: " . mysqli_error($conn);
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);
Example : echo "Error code: " . mysqli_error($conn);
Output
Error code: 1064
HCES BCA GADAG
15 Accessing Mysql
mysqli_real_escape_string: This function escapes special characters in a string for use in an SQL
statement, taking into account the current charset of the connection.
Syntax: mysqli_real_escape_string ( $link , $escapestr )
$unsafe_string = "O'Reilly";
$safe_string = mysqli_real_escape_string($conn, $unsafe_string);
$query = "INSERT INTO users (name) VALUES ('$safe_string')";
if (mysqli_query($conn, $query)) {
echo "Record inserted successfully";
} else {
echo "Error: " . mysqli_error($conn);
In this example, the apostrophe in the string O'Reilly is escaped to prevent SQL injection and syntax errors.
COUNTING RETURNED RECORDS
mysqli_affected_rows: This function returns the number of rows affected by the last INSERT, UPDATE,
REPLACE, or DELETE query.
Syntax: mysqli_affected_rows ($link )
Example:
$query = "UPDATE users SET email = 'new_email@example.com' WHERE id = 1";
if (mysqli_query($conn, $query)) {
$affected_rows = mysqli_affected_rows($conn);
echo "$affected_rows rows affected.";
HCES BCA GADAG
16 Accessing Mysql
} else {
echo "Error: " . mysqli_error($conn);
In this example, the number of rows affected by the UPDATE query is displayed.
mysqli_num_rows: This function returns the number of rows in a result set.
Syntax: mysqli_num_rows ( $result )
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);
$num_rows = mysqli_num_rows($result);
echo "Number of rows: $num_rows";
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.
Syntax: mysqli_insert_id ($link )
$query = "INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com')";
if (mysqli_query($conn, $query)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: $last_id";
} else {
echo "Error: " . mysqli_error($conn);
}In this example, after inserting a new record, the auto-generated ID of the inserted record is displayed.
HCES BCA GADAG
17 Accessing Mysql
Select Or Create A Database
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:
1. Selecting an Existing Database
<?php
$host = "localhost"; In this example:
$username = "your_username"; • `mysqli_select_db($conn,
$password = "your_password"; $database)` selects the database
specified by `$database`.
$database = "existing_database";
• If the database selection fails,
$conn = mysqli_connect($host, $username, $password);
`mysqli_select_db` returns
if (!$conn) { `FALSE`, and you can use
`mysqli_error($conn)` to get the
die("Connection failed: " . mysqli_connect_error());
error message.
}
// Select the database
if (!mysqli_select_db($conn, $database)) {
die("Database selection failed: " . mysqli_error($conn));
echo "Database selected successfully";
// Close the connection
mysqli_close($conn);
?>
HCES BCA GADAG
18 Accessing Mysql
2. Creating a New Database
<?php
$host = "localhost";
$username = "your_username";
$password = "your_password";
$new_database = "new_database";
$conn = mysqli_connect($host, $username, $password);
if (!$conn) {die("Connection failed: " . mysqli_connect_error());}
// Create a new database
$query = "CREATE DATABASE $new_database";
if (mysqli_query($conn, $query)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
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.
HCES BCA GADAG
19 Accessing Mysql
Updating Records In Mysql
Updating records in MySQL database using PHP involves using the `UPDATE` SQL statement along with
the `mysqli_query` function to execute the query.
Assume you have a table named `users` with columns `id`, `firstname`, `lastname`, and `email`. Here's
how you can update a record in this table:
<?php
$host = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
$conn = mysqli_connect($host, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
// Sample data for updating
$id = 1; // ID of the record to update
$new_firstname = "abc";
$new_lastname = "xyz";
$new_email = "new_email@example.com";
HCES BCA GADAG
20 Accessing Mysql
// SQL query to update record
$query = "UPDATE users SET firstname='$new_firstname', lastname='$new_lastname',
email='$new_email' WHERE id=$id";
if (mysqli_query($conn, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
mysqli_close($conn);
?>
1. Connection Setup: Replace `"localhost"`, `"your_username"`, `"your_password"`, and
`"your_database"` with your actual database connection details.
2. Connection Establishment: The `mysqli_connect` function establishes a connection to the MySQL
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:
• Construct an `UPDATE` query using the `UPDATE` statement. In this example:
• `UPDATE users`: specifies the table `users` to update.
• `SET firstname='$new_firstname', lastname='$new_lastname', email='$new_email'`: sets the
new values for `firstname`, `lastname`, and `email`.
• `WHERE id=$id`: specifies which record to update based on the `id`.
HCES BCA GADAG
21 Accessing Mysql
5. Executing the Query:Use `mysqli_query($conn, $query)` to execute the SQL query. If successful,
`mysqli_query` returns `TRUE`; otherwise, it returns `FALSE`, and `mysqli_error($conn)` provides
the error message.
6. Error Handling: Check if the query executed successfully. If not, print the error message using
`mysqli_error($conn)`.
7. Closing the Connection: Close the MySQL connection using `mysqli_close($conn)`.
HCES BCA GADAG