Module 12 - Introducing MySQL

Introduction

History:

MySQL is an open-source relational database management system (RDBMS) that has played a crucial role in the world of databases and web development. It was initially developed by a Swedish company, MySQL AB, founded by Michael Widenius, David Axmark, and Allan Larsson. The development of MySQL started in the early 1990s, and the first version was released in 1995. Over the years, it has undergone significant enhancements and optimizations.

In 2008, Sun Microsystems acquired MySQL AB, and later, Oracle Corporation acquired Sun Microsystems in 2010. Despite changes in ownership, MySQL has remained open-source and is currently managed by the Oracle Corporation. The open-source nature of MySQL has contributed to its widespread adoption and community-driven development.

Development:

MySQL was originally designed to be a lightweight and fast database management system, focusing on simplicity and ease of use. It uses the SQL (Structured Query Language) for managing and manipulating relational databases. MySQL's architecture allows it to be used for various purposes, from small-scale projects to large-scale enterprise applications.

Over the years, MySQL has evolved with the addition of features such as stored procedures, triggers, views, and support for different storage engines. Its development community has played a crucial role in testing, bug fixing, and suggesting improvements, making it a robust and reliable database solution.

Popularity Over Time:

MySQL has consistently been one of the most popular databases in the world. Its open-source nature, reliability, and performance have contributed to its widespread adoption. The MySQL database is a default choice for many web developers, businesses, and organizations looking for a scalable and cost-effective database solution.

The popularity of MySQL is evident in various technology stacks and platforms, and it has been a go-to option for developers building dynamic web applications, content management systems (CMS), and other database-driven solutions.

Usage:

MySQL is used in a wide range of applications and industries. Some common use cases include:

  • Web Development: MySQL is a fundamental part of the LAMP (Linux, Apache, MySQL, PHP/Python/Perl) and MEAN (MongoDB, Express.js, AngularJS, Node.js) stacks, which are popular for web development. It is used to store and retrieve data for dynamic websites and web applications.
  • Enterprise Applications: MySQL is often used in enterprise-level applications where the need for a reliable and scalable database is essential. Its performance and support for ACID (Atomicity, Consistency, Isolation, Durability) properties make it suitable for critical business processes.
  • Embedded Systems: Due to its lightweight nature, MySQL is often used in embedded systems, including IoT (Internet of Things) devices, where efficient data storage and retrieval are crucial.
  • Data Warehousing: MySQL is used in data warehousing scenarios where data needs to be stored, organized, and analyzed for business intelligence purposes.
  • Content Management Systems (CMS): Many popular CMS platforms, such as WordPress and Joomla, utilize MySQL as their default database for storing content and user data.

Place in Full Stack Web Development:

In full-stack web development, MySQL often serves as the backend database for storing and managing data. It works in conjunction with server-side scripting languages like PHP, Python, or Node.js to handle database queries and updates. On the frontend, web developers use HTML, CSS, and JavaScript to create the user interface that interacts with the MySQL database through server-side scripts.

MySQL's integration into the popular web development stacks, as mentioned earlier (LAMP and MEAN stacks), showcases its pivotal role in full-stack web development. The ability to efficiently store and retrieve data makes MySQL a key component in creating dynamic and interactive web applications. Its compatibility with various programming languages and frameworks makes it a versatile choice for developers working on different aspects of the web development stack.

In summary, MySQL's history, open-source nature, reliability, and performance have contributed to its enduring popularity in the world of databases, making it a cornerstone in full-stack web development. Its usage spans a broad spectrum, from small-scale projects to large enterprise applications, showcasing its versatility and effectiveness as a relational database management system.



Getting Started

One of the easiest ways to get started learning MySQL is to use MAMP.  MAMP (Mac, Apache, MySQL, PHP) is a popular web development environment for macOS, and phpMyAdmin is a web-based tool for managing MySQL databases. If you've been following along with the rest of this course, you should already have MAMP installed and functioning on your own computer to simulate a production web server.

Here are detailed instructions on how to get started using phpMyAdmin through MAMP:

Step 1: Install MAMP

  1. Download MAMP from the official website: MAMP Downloads.
  2. Open the downloaded file and follow the installation instructions.
  3. Once the installation is complete, launch MAMP from your Applications folder.

Step 2: Start MAMP Servers

  1. Open MAMP and click on the "Start Servers" button. This will start the Apache web server and the MySQL database server.
  2. Confirm that both the Apache and MySQL servers are running by checking the indicators at the top of the MAMP window. The status should be green.

Step 3: Access phpMyAdmin

  1. Open your web browser and enter the following URL in the address bar: http://localhost:8888/phpmyadmin/. Note that the port number (8888) may vary if you've changed the default port in MAMP settings.
  2. You should see the phpMyAdmin login page. By default, MAMP sets up a MySQL user named "root" with the password "root." Enter these credentials and click "Go" or "Login."

Step 4: Create a Database

  1. Once logged in, you'll be in the phpMyAdmin dashboard. On the left-hand side, you'll see a panel with a list of databases.
  2. To create a new database, click on the "Database" tab at the top. Enter a name for your database in the "Create database" field and click "Create."

Step 5: Manage Tables and Data

  1. After creating a database, you can manage tables and data by clicking on the database name in the left panel.
  2. To create a new table, click on the "Structure" tab and then "Create Table." Fill in the table details and click "Save."
  3. To insert data into a table, click on the "Insert" tab and fill in the necessary information.


MySQL Database Structure

MySQL is a relational database management system (RDBMS), and its structure adheres to the principles of relational database design. Below are the major concepts of a relational database and the key constructs within MySQL:

Relational Database Concepts:

Tables: In a relational database, data is organized into tables. Each table represents an entity, such as customers, orders, products, etc. Tables are the primary containers for storing data.

Relationships: Tables in a relational database can be related to each other through keys. The relationships define how data in one table relates to data in another. Common types of relationships include one-to-one, one-to-many, and many-to-many.

Normalization: This is the process of organizing data to reduce redundancy and improve data integrity. Normalization involves breaking down large tables into smaller, related tables and using relationships between them.

Keys: Keys are used to uniquely identify records within a table. The Primary Key uniquely identifies each record in a table, and Foreign Keys establish relationships between tables.

Databases:

  • A MySQL database is a container for a collection of tables. It is the top-level organizational unit in MySQL.
  • Databases provide a way to separate and manage different sets of data logically.

Tables:

  • Tables are the fundamental building blocks of a MySQL database.
  • Each table has a name, and its columns define the structure of the data. Columns are also referred to as fields or attributes.

Columns (Fields):

  • Columns define the attributes or properties of the data stored in a table.
  • Each column has a name, a data type (such as INT, VARCHAR, etc.), and may have additional properties like whether it can contain NULL values.

Rows (Records):

  • Rows, also known as records, represent individual data entries in a table.
  • Each row contains values for each column defined in the table.

Primary Key:

  • The Primary Key uniquely identifies each record in a table.
  • It must contain unique values and cannot be NULL.

Foreign Key:

  • A Foreign Key is a column or a set of columns in a table that refers to the Primary Key of another table.
  • It establishes relationships between tables.

Understanding these fundamental concepts and constructs is crucial for designing and working with MySQL databases effectively. A well-designed database structure ensures data integrity, facilitates efficient querying, and supports the scalability and maintainability of the database system.



MySQL Data Types

Here's a description of most MySQL data types, including samples of data, data formatting constraints, and the best use for each type. You;ll. see that there are others, mostly made up of variations on these (LONGTEXT for TEXT, etc)

INT (Integer):

Description: Used for storing whole numbers without decimal points.
Sample Data: 123, -45, 0.
Formatting Constraints: Range depends on the signed or unsigned attribute (e.g., INT vs. UNSIGNED INT).
Best Use: Ideal for storing counts, quantities, or identifiers where decimal precision is not required.

VARCHAR (Variable Character):

Description: Variable-length character strings.
Sample Data: 'John', 'example@email.com'.
Formatting Constraints: Maximum length needs to be specified (e.g., VARCHAR(255)).
Best Use: Suitable for storing variable-length text data such as names, emails, or textual descriptions.

CHAR (Fixed-Length Character):

Description: Fixed-length character strings.
Sample Data: 'John', 'example@email.com'.
Formatting Constraints: Fixed length needs to be specified (e.g., CHAR(10)).
Best Use: Useful when the data length is consistent, such as for fixed-length codes or abbreviations.

TEXT:

Description: Variable-length text data.
Sample Data: 'This is a long text.'.
Formatting Constraints: Maximum length is quite large (up to 65,535 characters).
Best Use: Suitable for storing large amounts of text, such as articles or paragraphs.

DATE:

Description: Date values in the format 'YYYY-MM-DD'.
Sample Data: '2023-11-19'.
Formatting Constraints: Valid date format required.
Best Use: Ideal for storing date information, such as birthdates or event dates.

TIME:

Description: Time values in the format 'HH:MM:SS'.
Sample Data: '14:30:00'.
Formatting Constraints: Valid time format required.
Best Use: Useful for storing time-related information, such as the duration of an event.

DATETIME:

Description: Combination of date and time values in the format 'YYYY-MM-DD HH:MM:SS'.
Sample Data: '2023-11-19 14:30:00'.
Formatting Constraints: Valid datetime format required.
Best Use: When both date and time information is needed, such as recording when a record was created.

FLOAT:

Description: Floating-point numbers with decimal precision.
Sample Data: 3.14, -0.001.
Formatting Constraints: Precision depends on the size specified (e.g., FLOAT(5,2)).
Best Use: Suitable for situations requiring decimal precision but without the need for extremely precise calculations.

DOUBLE:

Description: Double-precision floating-point numbers.
Sample Data: 3.14, -0.001.
Formatting Constraints: Higher precision compared to FLOAT.
Best Use: When higher precision in decimal calculations is required.

BOOLEAN/TINYINT(1):

Description: Small integer type often used for boolean values (0 or 1).
Sample Data: 1, 0.
Formatting Constraints: Usually defined as TINYINT(1) for boolean storage.
Best Use: Ideal for representing true/false or yes/no values.

DECIMAL:

Description: Fixed-point numbers with user-specified precision and scale.
Sample Data: 123.45, -0.001.
Formatting Constraints: Specify precision and scale (e.g., DECIMAL(5,2)).
Best Use: Ideal for financial applications or scenarios requiring fixed-point decimal precision.

ENUM:

Description: A string object with a value chosen from a predefined list of values.
Sample Data: 'Red', 'Green'.
Formatting Constraints: Define a list of acceptable values.
Best Use: When the field should only have a limited set of possible values, like status or category.

These data types provide a flexible range of options to suit different data storage needs. Selecting the appropriate data type ensures efficient storage and retrieval, as well as maintaining data accuracy and integrity in your MySQL database.



Creating a Table

Let's say you are making a “Contacts” web app. The data for this app will be stored in a single MySQL table, and your php scripts will interact with that.

Let's go through the process of creating the "contacts" table using the phpMyAdmin interface for each field, providing explanations for each data type:

Step 1: Start MAMP Servers

  1. Open MAMP and ensure that the Apache web server and MySQL database server are running.
  2. Open your web browser and go to http://localhost:8888/phpmyadmin/.

Step 2: Access phpMyAdmin and Select Database

  1. Choose the database where you want to create the "contacts" table or create a new one.
  2. Click on the selected or newly created database in the left panel.

Step 3: Create the "contacts" Table and Define Fields

  1. Click on the "Structure" tab in phpMyAdmin.
  2. Click on the "Create Table" button to start creating the "contacts" table.
  3. For the first field, name it "id." Choose the data type as INT (Integer) since it will store numeric values. Check the "A_I" (Auto Increment) box, and set it as the primary key. This ensures each entry has a unique identifier.
  4. Add a field for "first_name" with the data type VARCHAR (Variable Character). VARCHAR is suitable for storing variable-length character strings, such as names. Specify a length, for example, 50.
  5. Add a field for "last_name" with the same VARCHAR data type and length.
  6. Create a field for "phone_number" with the VARCHAR data type. Adjust the length based on the expected length of phone numbers (e.g., 15 characters).
  7. For "email_address," use the VARCHAR data type with a suitable length (e.g., 100). VARCHAR is appropriate for storing email addresses.
  8. Add a field for "web_site" with the VARCHAR data type, accommodating the expected length of website URLs (e.g., 100 characters).
  9. For "birthday," use the DATE data type. This type is suitable for storing date values.
  10. Click on the "Save" button to create the "contacts" table.

Step 4: Verify Table Creation

  1. After saving, you should see the "contacts" table listed under your selected database.
  2. Click on the "Structure" tab to review the fields and their data types.

Step 5: Insert Sample Data (Optional)

If you want to insert sample data:

  1. Click on the "Browse" tab.
  2. Click on the "Insert" tab and fill in the data for each field.
  3. Click "Go" to insert the sample data.

Go ahead and enter a few sample records, so we can test out a PHP script to display them.



Displaying MySQL Data

To display records from the "contacts" table in alphabetical order by last name using PHP, you'll need to use the MySQLi extension. Below are step-by-step instructions and sample code for getting started using the table we created earlier in this module:

1. Database Connection Parameters:

// Database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

These variables store the connection parameters needed to connect to your MySQL database. Replace "your_username", "your_password", and "your_database" with your actual MySQL username, password, and database name.

2. Create Connection:

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

This line establishes a connection to the MySQL database using the mysqli_connect function. The connection details are provided as arguments. If the connection is successful, $conn will hold the connection object.

3. Check Connection:

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

This code checks if the connection was successful. If the connection fails, it terminates the script and outputs an error message using die() and mysqli_connect_error().

4. Prepare and Execute a Statement:

// Prepare and execute a statement to fetch records in alphabetical order by last name
$sql = "SELECT * FROM contacts ORDER BY last_name ASC";
$result = mysqli_query($conn, $sql);

The $sql variable holds a SQL query to select all columns from the "contacts" table and order the results by the "last_name" column in ascending order. mysqli_query executes the query and stores the result in the $result variable.

5. Check if There Are Rows Returned:

// Check if there are rows returned
if (mysqli_num_rows($result) > 0) {
// Code to execute if there are rows
} else {
// Code to execute if there are no rows
}

This part checks if there are rows returned by the query using mysqli_num_rows. If there are rows, it executes the code within the if block; otherwise, it executes the code within the else block.

6. Output Data in HTML Table:

echo "<table border='1'>";
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Phone Number</th><th>Email Address</th><th>Web Site</th><th>Birthday</th></tr>";

// Output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["first_name"] . "</td><td>" . $row["last_name"] . "</td><td>" . $row["phone_number"] . "</td><td>" . $row["email_address"] . "</td><td>" . $row["web_site"] . "</td><td>" . $row["birthday"] . "</td></tr>";
}

echo "</table>";

This section outputs the data in an HTML table. The table structure and header row are echoed first. Then, a while loop iterates through each row of the result set using mysqli_fetch_assoc. The data is displayed in table rows within the loop. Finally, the closing </table> tag is echoed.

7. Close the Connection:

// Close the connection
mysqli_close($conn);

This line closes the MySQL database connection using mysqli_close. It's good practice to close the connection when you're done to free up resources.

Here is the whole block of code:

// Database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Prepare and execute a statement to fetch records in alphabetical order by last name
$sql = "SELECT * FROM contacts ORDER BY last_name ASC";
$result = mysqli_query($conn, $sql);

// Check if there are rows returned
if (mysqli_num_rows($result) > 0) {
echo "<table border='1'>";
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Phone Number</th><th>Email Address</th><th>Web Site</th><th>Birthday</th></tr>";

// Output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["first_name"] . "</td><td>" . $row["last_name"] . "</td><td>" . $row["phone_number"] . "</td><td>" . $row["email_address"] . "</td><td>" . $row["web_site"] . "</td><td>" . $row["birthday"] . "</td></tr>";
}

echo "</table>";
} else {
echo "0 results";
}

// Close the connection
mysqli_close($conn);

Videos for Module 12 - Introducing MySQL

There are no videos yet this term for this Module. Check back soon!