One place for hosting & domains

      Store

      How To Store WordPress Assets on DigitalOcean Spaces With Ubuntu 20.04


      Introduction

      DigitalOcean Spaces is an object storage service that can be used to store large amounts of diverse, unstructured data. WordPress sites, which often include image and video assets, can be good candidates for object storage solutions. Using object storage for these types of static resources can optimize site performance by freeing up space and resources on your servers. For more information about object storage and WordPress check out our tutorial on How To Back Up a WordPress Site to Spaces.

      In this tutorial, you’ll learn how to use a WordPress plugin that works directly with DigitalOcean Spaces as the primary asset store. The DigitalOcean Spaces Sync plugin routes the data of our WordPress media library to Spaces and provides you with various configuration options based on your needs, streamlining the process of using object storage with your WordPress instance.

      Prerequisites

      This tutorial assumes that you have a WordPress instance on a server you’ll use as a DigitalOcean Space. If you do not have this set up, you can complete the following:

      With these prerequisites in place, you’re ready to begin using this plugin.

      Modifying WordPress Permissions

      Throughout this tutorial, you will be working with the wp-content/uploads folder in your WordPress project, so it is important that this folder exists and has the correct permissions. You can create it with the mkdir command using the -p flag in order to create the folder if it doesn’t exist, and avoid throwing an error if it does:

      • sudo mkdir -p /var/www/html/wp-content/uploads

      You can now set permissions on the folder. First, set the ownership to your user (you will use sammy here, but be sure to use your non-root sudo user), and group ownership to the www-data group:

      • sudo chown -R sammy:www-data /var/www/html/wp-content/uploads

      Next, establish the permissions that will give the web server write access to this folder:

      • sudo chmod -R g+w /var/www/html/wp-content/uploads

      You will now be able to use our plugins to create a store in object storage for the assets in the wp-content/uploads folder, and to engage with your assets from the WordPress interface.

      Installing DigitalOcean Spaces Sync

      The first step in using DigitalOcean Spaces Sync will be to install it in your WordPress folder. You can navigate to the plugin folder within our WordPress directory:

      • cd /var/www/html/wp-content/plugins

      From here, install DigitalOcean Spaces Sync using the wp command:

      • wp plugin install do-spaces-sync

      To activate the plugin, you can run:

      • wp plugin activate do-spaces-sync

      From here, navigate to the plugins tab on the left-hand side of our WordPress administrative dashboard:

      WordPress Plugin Tab

      You should see DigitalOcean Spaces Sync in your list of activated plugins:

      Spaces Sync Plugin Screen

      To manage the settings for DigitalOcean Spaces Sync, navigate to our Settings tab, and select DigitalOcean Spaces Sync from the menu:

      Settings Tab

      DigitalOcean Spaces Sync will now give you options to configure your asset storage:

      DO Spaces Sync Configuration

      The Connection Settings field in the top half of the screen asks for your Spaces Access Key and Secret. It will then ask for your Container, which will be the name of your Space, and the Endpoint.

      You can determine the endpoint of your Space based on its URL. For example, if the URL of your Space is https://example-name.nyc3.digitaloceanspaces.com, then example-name will be your bucket/container, and nyc3.digitaloceanspaces.com will be your endpoint.

      In the plugin’s interface, the Endpoint section will be pre-filled with the default https://ams3.digitaloceanspaces.com. You should modify this endpoint if your Space lives in another region.

      Next, you will be asked for File & Path Settings. In the field marked Full URL-path to files, you can input either a storage public domain, if your files will be stored only on your Space, or a full URL path, if you will store them on your Space and server.

      For example, if your WordPress project is located in /var/www/html, and you want to store files on both your server and Space, then you would enter:

      • http://your_server_ip/wp-content/uploads in the Full URL-path to files field
      • /var/www/html/wp-content/uploads in the Local path field

      The Storage prefix and Filemask settings are prefilled, and do not need to be modified unless you would like to specify certain types of files for your sync.

      You will cover the specifics of storing files on your server and Space and on your Space alone in the following sections.

      Syncing and Saving Files in Multiple Locations

      DigitalOcean Spaces Sync offers the option of saving files to your server while also syncing them to your Space. This utility can be helpful if you need to keep files on your server, but would also like backups stored elsewhere. For this tutorial, you will go through the process of syncing a file to your Space while keeping it on your server. For the purposes of this example, you will assume that you have a file called sammy10x10.png that you would like to store in your media library and on your Space.

      First, navigate to the Settings tab on your WordPress administrative dashboard, and select DigitalOcean Spaces Sync from the menu of presented options.

      Next, in the Connections Settings field, enter your Spaces Key and Secret, followed by your Container and Endpoint. Remember, if the URL of your Space is https://example-name.nyc3.digitaloceanspaces.com, then example-name will be your Container, and nyc3.digitaloceanspaces.com will be your Endpoint. Test your connections by clicking the Check the Connection button at the bottom of the Connection Settings field:

      Check Connection Button

      Now you are ready to fill out the File & Path Settings.

      In the Full URL-path to files field you can enter our full URL path, since you are saving your file on your server and on your Space. You’ll use your server’s IP here, but if you have a domain, you can swap out the IP address for your domain name. For more about registering domains with DigitalOcean, see our tutorial on How To Set Up a Host Name with DigitalOcean. In this case, the Full URL-path to files will be http://your_server_ip/wp-content/uploads.

      Next, you will fill out the Local path field with the local path to the uploads directory: /var/www/html/wp-content/uploads.

      Because you are working with a single file, you do not need to modify the Storage prefix and Filemask sections. As your WordPress media library grows in size and variety, you can modify this setting to target individual file types using wildcards and extensions such as *.png in the Filemask field.

      Your final File & Path Settings will look like this:

      Sync Server and Cloud

      Be sure to save your configuration changes by clicking the Save Changes button at the bottom of the screen.

      Now you can add the file, sammy10x10.png, to our WordPress media library. You’ll use the wp media import command, which will import the file from your home directory to your WordPress media library. In this case, your home directory will belong to sammy, but in your case this will be your non-root sudo user. As you move the file, you will use the --path parameter to specify the location of our WordPress project:

      • wp media import --path=/var/www/html/ /home/sammy/sammy10x10.png

      Looking at the WordPress interface, you should now see the file in your Media Library. You can navigate there by following the Media Library tab on the left side of our WordPress administrative dashboard:

      Media Library Tab

      If you navigate to your Spaces page in the DigitalOcean control panel, you should also see the file in your Space.

      Finally, you can navigate to our wp-content/uploads folder, where WordPress will have created a sub-folder with the year and month. Within this folder you should see our sammy10x10.png file.

      Storing Files on Spaces

      The DigitalOcean Spaces Sync plugin has an additional option that will allow you to store files only on your Space, in case you would like to optimize space and resources on our server. You will work with another file, sammy-heart10x10.png, and set your DigitalOcean Spaces Sync settings so that this file will be stored only on your Space.

      First, let’s navigate back to the plugin’s main configuration page:

      DO Spaces Sync Configuration

      You can leave the Connection Settings information, but will modify the File & Path Settings. First, in the Full URL-path to files, you will write the storage public domain. Again, you will use your server IP, but you can swap this out for a domain if you have one: http://uploads.your_server_ip

      Next, navigate to Sync Settings, at the bottom of the page, and click the first box, which will allow you to “store files only in the cloud and delete after successful upload.” Your final File & Path Settings will look like this:

      Sync Cloud Only

      Be sure to save your changes by clicking the Save Changes button at the bottom of the screen.

      Back on the command line, move sammy-heart10x10.png from your user’s home directory to your Media Library using wp media import:

      • wp media import --path=/var/www/html/ /home/sammy/sammy-heart10x10.png

      If you navigate back to your WordPress interface, you will not see sammy-heart10x10.png or sammy10x10.png in your Media Library. Next, return to the command line and navigate to your wp-content/uploads directory — you should see that sammy-heart10x10.png is missing from your timestamped sub-folder.

      Finally, if you navigate to the Spaces page in the DigitalOcean control panel, you should see both files stored in your Space.

      Conclusion

      This tutorial covered two different options you can use to store your WordPress media files to DigitalOcean Spaces using DigitalOcean Spaces Sync. This plugin offers additional options for customization, which you can learn more about by reading the developer’s article “Sync your WordPress media with DigitalOcean Spaces.”

      If you would like more general information about working with Spaces, check out our introduction to DigitalOcean Spaces and our guide to best practices for performance on Spaces.



      Source link

      How To Store and Retrieve Data in MariaDB Using Python on Ubuntu 18.04


      The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      MariaDB is an open source version of the popular MySQL relational database management system (DBMS) with a SQL interface for accessing and managing data. It is highly reliable and easy to administer, which are essential qualities of a DBMS capable of serving modern applications. With Python’s growing popularity in technologies like artificial intelligence and machine learning, MariaDB makes a good option for a database server for Python.

      In this tutorial, you will connect a Python application to a database server using the MySQL connector. This module allows you to make queries on the database server from within your application. You’ll set up MariaDB for a Python environment on Ubuntu 18.04 and write a Python script that connects to and executes queries on MariaDB.

      Prerequisites

      Before you begin this guide, you will need the following:

      Step 1 — Preparing and Installing

      In this step, you’ll create a database and a table in MariaDB.

      First, open your terminal and enter the MariaDB shell from the terminal with the following command:

      Once you’re in the MariaDB shell, your terminal prompt will change. In this tutorial, you’ll write Python to connect to an example employee database named workplace and a table named employees.

      Start by creating the workplace database:

      • CREATE DATABASE workplace;

      Next, tell MariaDB to use workplace as your current database:

      You will receive the following output, which means that every query you run after this will take effect in the workplace database:

      Output

      Database changed

      Next, create the employees table:

      • CREATE TABLE employees (first_name CHAR(35), last_name CHAR(35));

      In the table schema, the parameters first_name and a last_name are specified as character strings (CHAR) with a maximum length of 35.

      Following this, exit the MariaDB shell:

      Back in the terminal, export your MariaDB authorization credentials as environment variables:

      • export username="username"
      • export password="password"

      This technique allows you to avoid adding credentials in plain text within your script.

      You’ve set up your environment for the project. Next, you’ll begin writing your script and connect to your database.

      Step 2 — Connecting to Your Database

      In this step, you will install the MySQL Connector and set up the database.

      In your terminal, run the following command to install the Connector:

      • pip3 install mysql-connector-python

      pip is the standard package manager for Python. mysql-connector-python is the database connector Python module.

      Once you’ve successfully installed the connector, create and open a new file Python file:

      In the opened file, import the os module and the mysql.connector module using the import keyword:

      database.py

      import os
      import mysql.connector as database
      

      The as keyword here means that mysql.connector will be referenced as database in the rest of the code.

      Next, initialize the authorization credentials you exported as Python variables:

      database.py

      . . .
      username = os.environ.get("username")
      password = os.environ.get("password")
      

      Follow up and establish a database connection using the connect() method provided by database. The method takes a series of named arguments specifying your client credentials:

      database.py

      . . .
      connection = database.connect(
          user=username,
          password=password,
          host=localhost,
          database="workplace")
      

      You declare a variable named connection that holds the call to the database.connect() method. Inside the method, you assign values to the user, password, host, and database arguments. For user and password, you will reference your MariaDB authorization credentials. The host will be localhost by default if you are running the database on the same system.

      Lastly, call the cursor() method on the connection to obtain the database cursor:

      database.py

      . . .
      cursor = connection.cursor()
      

      A cursor is a database object that retrieves and also updates data, one row at a time, from a set of data.

      Leave your file open for the next step.

      Now you can connect to MariaDB with your credentials; next, you will add entries to your database using your script.

      Step 3 — Adding Data

      Using the execute() method on the database cursor, you will add entries to your database in this step.

      Define a function add_data() to accept the first and last names of an employee as arguments. Inside the function, create a try/except block. Add the following code following your cursor object:

      database.py

      . . .
      def add_data(first_name, last_name):
          try:
              statement = "INSERT INTO employees (first_name,last_name) VALUES (%s, %s)"
              data = (first_name, last_name)
              cursor.execute(statement, data)
              connection.commit()
              print("Successfully added entry to database")
          except database.Error as e:
              print(f"Error adding entry to database: {e}")
      

      You use the try and except block to catch and handle exceptions (events or errors) that disrupt the normal flow of program execution.

      Under the try block, you declare statement as a variable holding your INSERT SQL statement. The statement tells MariaDB to add to the columns first_name and last_name.

      The code syntax accepts data as parameters that reduce the chances of SQL injection. Prepared statements with parameters ensure that only given parameters are securely passed to the database as intended. Parameters are generally not injectable.

      Next you declare data as a tuple with the arguments received from the add_data function. Proceed to run the execute() method on your cursor object by passing the SQL statement and the data. After calling the execute() method, you call the commit() method on the connection to permanently save the inserted data.

      Finally, you print out a success message if this succeeds.

      In the except block, which only executes when there’s an exception, you declare database.Error as e. This variable will hold information about the type of exception or what event happened when the script breaks. You then proceed to print out an error message formatted with e to end the block using an f-string.

      After adding data to the database, you’ll next want to retrieve it. The next step will take you through the process of retrieving data.

      Step 4 — Retrieving Data

      In this step, you will write a SQL query within your Python code to retrieve data from your database.

      Using the same execute() method on the database cursor, you can retrieve a database entry.

      Define a function get_data() to accept the last name of an employee as an argument, which you will call with the execute() method with the SELECT SQL query to locate the exact row:

      database.py

      . . .
      def get_data(last_name):
          try:
            statement = "SELECT first_name, last_name FROM employees WHERE last_name=%s"
            data = (last_name,)
            cursor.execute(statement, data)
            for (first_name, last_name) in cursor:
              print(f"Successfully retrieved {first_name}, {last_name}")
          except database.Error as e:
            print(f"Error retrieving entry from database: {e}")
      

      Under the try block, you declare statement as a variable holding your SELECT SQL statement. The statement tells MariaDB to retrieve the columns first_name and last_name from the employees table when a specific last name is matched.

      Again, you use parameters to reduce the chances of SQL injection.

      Smilarly to the last function, you declare data as a tuple with last_name followed by a comma. Proceed to run the execute() method on the cursor object by passing the SQL statement and the data. Using a for loop, you iterate through the returned elements in the cursor and then print out if there are any successful matches.

      In the except block, which only executes when there is an exception, declare database.Error as e. This variable will hold information about the type of exception that occurs. You then proceed to print out an error message formatted with e to end the block.

      In the final step, you will execute your script by calling the defined functions.

      Step 5 — Running Your Script

      In this step, you will write the final piece of code to make your script executable and run it from your terminal.

      Complete your script by calling add_data() and get_data() with sample data (strings) to verify that your code is working as expected.

      If you would like to add multiple entries, you can call add_data() with further sample names of your choice.

      Once you finish working with the database make sure that you close the connection to avoid wasting resources:
      connection.close():

      database.py

      import os
      import mysql.connector as database
      
      username = os.environ.get("username")
      password = os.environ.get("password")
      
      connection = database.connect(
          user=username,
          password=password,
          host=localhost,
          database="workplace")
      
      cursor = connection.cursor()
      
      def add_data(first_name, last_name):
          try:
          statement = "INSERT INTO employees (first_name,last_name) VALUES (%s, %s)"
          data = (first_name, last_name)
            cursor.execute(statement, data)
          cursor.commit()
          print("Successfully added entry to database")
          except database.Error as e:
          print(f"Error adding entry to database: {e}")
      
      def get_data(last_name):
          try:
            statement = "SELECT first_name, last_name FROM employees WHERE last_name=%s"
            data = (last_name,)
            cursor.execute(statement, data)
            for (first_name, last_name) in cursor:
              print(f"Successfully retrieved {first_name}, {last_name}")
          except database.Error as e:
            print(f"Error retrieving entry from database: {e}")
      
      add_data("Kofi", "Doe")
      get_data("Doe")
      
      connection.close()
      

      Make sure you have indented your code correctly to avoid errors.

      In the same directory, you created the database.py file, run your script with:

      You will receive the following output:

      Output

      Successfully added entry to database Successfully retrieved Kofi, Doe

      Finally, return to MariaDB to confirm you have successfully added your entries.

      Open up the MariaDB prompt from your terminal:

      Next, tell MariaDB to switch to and use the workplace database:

      After you get the success message Database changed, proceed to query for all entries in the employees table:

      You output will be similar to the following:

      Output

      +------------+-----------+ | first_name | last_name | +------------+-----------+ | Kofi | Doe | +------------+-----------+ 1 row in set (0.00 sec)

      Putting it all together, you’ve written a script that saves and retrieves information from a MariaDB database.

      You started by importing the necessary libraries. You used mysql-connector to connect to the database and os to retrieve authorization credentials from the environment. On the database connection, you retrieved the cursor to carry out queries and structured your code into add_data and get_data functions. With your functions, you inserted data into and retrieved data from the database.

      If you wish to implement deletion, you can build a similar function with the necessary declarations, statements, and calls.

      Conclusion

      You have successfully set up a database connection to MariaDB using a Python script on Ubuntu 18.04. From here, you could use similar code in any of your Python projects in which you need to store data in a database. This guide may also be helpful for other relational databases that were developed out of MySQL.

      For more on how to accomplish your projects with Python, check out other community tutorials on Python.



      Source link

      How To Use the MySQL BLOB Data Type to Store Images with PHP on Ubuntu 18.04


      The author selected Girls Who Code to receive a donation as part of the Write for DOnations program.

      Introduction

      A Binary Large Object (BLOB) is a MySQL data type that can store binary data such as images, multimedia, and PDF files.

      When creating applications that require a tightly-coupled database where images should be in sync with related data (for example, an employee portal, a student database, or a financial application), you might find it convenient to store images such as students’ passport photos and signatures in a MySQL database alongside other related information.

      This is where the MySQL BLOB data type comes in. This programming approach eliminates the need for creating a separate file system for storing images. The scheme also centralizes the database, making it more portable and secure because the data is isolated from the file system. Creating backups is also more seamless since you can create a single MySQL dump file that contains all your data.

      Retrieving data is faster, and when creating records you can be sure that data validation rules and referential integrity are maintained especially when using MySQL transactions.

      In this tutorial, you will use the MySQL BLOB data type to store images with PHP on Ubuntu 18.04.

      Prerequisites

      To follow along with this guide, you will need the following:

      Step 1 — Creating a Database

      You’ll start off by creating a sample database for your project. To do this, SSH in to your server and then run the following command to log in to your MySQL server as root:

      Enter the root password of your MySQL database and hit ENTER to continue.

      Then, run the following command to create a database. In this tutorial we’ll name it test_company:

      • CREATE DATABASE test_company;

      Once the database is created, you will see the following output:

      Output

      Query OK, 1 row affected (0.01 sec)

      Next, create a test_user account on the MySQL server and remember to replace PASSWORD with a strong password:

      • CREATE USER 'test_user'@'localhost' IDENTIFIED BY 'PASSWORD';

      You’ll see the following output:

      Output

      Query OK, 0 rows affected (0.01 sec)

      To grant test_user full privileges on the test_company database, run:

      • GRANT ALL PRIVILEGES ON test_company.* TO 'test_user'@'localhost';

      Make sure you get the following output:

      Output

      Query OK, 0 rows affected (0.01 sec)

      Finally, flush the privileges table in order for MySQL to reload the permissions:

      Ensure you see the following output:

      Output

      Query OK, 0 rows affected (0.01 sec)

      Now that the test_company database and test_user are ready, you’ll move on to creating a products table for storing sample products. You’ll use this table later to insert and retrieve records to demonstrate how MySQL BLOB works.

      Log out from the MySQL server:

      Then, log back in again with the credentials of the test_user that you created:

      When prompted, enter the password for the test_user and hit ENTER to continue. Next, switch to the test_company database by typing the following:

      Once the test_company database is selected, MySQL will display:

      Output

      Database changed

      Next, create a products table by running:

      • CREATE TABLE `products` (product_id BIGINT PRIMARY KEY AUTO_INCREMENT, product_name VARCHAR(50), price DOUBLE, product_image BLOB) ENGINE = InnoDB;

      This command creates a table named products. The table has four columns:

      • product_id: This column uses a BIGINT data type in order to accommodate a large list of products up to a maximum of 2⁶³-1 items. You’ve marked the column as PRIMARY KEY to uniquely identify products. In order for MySQL to handle the generation of new identifiers for inserted columns, you have used the keyword AUTO_INCREMENT.

      • product_name: This column holds the names of the products. You’ve used the VARCHAR data type since this field will generally handle alphanumerics up to a maximum of 50 characters—the limit of 50 is just a hypothetical value used for the purpose of this tutorial.

      • price: For demonstration purposes, your products table contains the price column to store the retail price of products. Since some products may have floating values (for example, 23.69, 45.36, 102.99), you’ve used the DOUBLE data type.

      • product_image: This column uses a BLOB data type to store the actual binary data of the products’ images.

      You’ve used the InnoDB storage ENGINE for the table to support a wide range of features including MySQL transactions. After executing this for creating the products table, you’ll see the following output:

      Output

      Query OK, 0 rows affected (0.03 sec)

      Log out from your MySQL server:

      You will get the following output

      Output

      Bye

      The products table is now ready to store some records including products’ images and you’ll populate it with some products in the next step.

      Step 2 — Creating PHP Scripts for Connecting and Populating the Database

      In this step, you’ll create a PHP script that will connect to the MySQL database that you created in Step 1. The script will prepare three sample products and insert them into the products table.

      To create the PHP code, open a new file with your text editor:

      • sudo nano /var/www/html/config.php

      Then, enter the following information into the file and replace PASSWORD with the test_user password that you created in Step 1:

      /var/www/html/config.php

      <?php
      
      define('DB_NAME', 'test_company');
      define('DB_USER', 'test_user');
      define('DB_PASSWORD', 'PASSWORD');
      define('DB_HOST', 'localhost');
      
      $pdo = new PDO("mysql:host=" . DB_HOST . "; dbname=" . DB_NAME, DB_USER, DB_PASSWORD);
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
      
      

      Save and close the file.

      In this file, you’ve used four PHP constants to connect to the MySQL database that you created in Step 1:

      • DB_NAME : This constant holds the name of the test_company database.

      • DB_USER : This variable holds the test_user username.

      • DB_PASSWORD : This constant stores the MySQL PASSWORD of the test_user account.

      • DB_HOST: This represents the server where the database resides. In this case, you are using the localhost server.

      The following line in your file initiates a PHP Data Object (PDO) and connects to the MySQL database:

      ...
      $pdo = new PDO("mysql:host=" . DB_HOST . "; dbname=" . DB_NAME, DB_USER, DB_PASSWORD);
      ...
      

      Toward the end of the file, you’ve set a couple of PDO attributes:

      • ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION: This attribute instructs PDO to throw an exception that can be logged for debugging purposes.
      • ATTR_EMULATE_PREPARES, false: This option increases security by telling the MySQL database engine to do the prepare instead of PDO.

      You’ll include the /var/www/html/config.php file in two PHP scripts that you will create next for inserting and retrieving records respectively.

      First, create the /var/www/html/insert_products.php PHP script for inserting records to the products table:

      • sudo nano /var/www/html/insert_products.php

      Then, add the following information into the /var/www/html/insert_products.php file:

      /var/www/html/insert_products.php

      <?php
      
      require_once 'config.php';
      
      $products = [];
      
      $products[] = [
                    'product_name' => 'VIRTUAL SERVERS',
                    'price' => 5,
                    'product_image' => file_get_contents("https://i.imgur.com/VEIKbp0.png")
                    ];
      
      $products[] = [
                    'product_name' => 'MANAGED KUBERNETES',
                    'price' => 30,
                    'product_image' => file_get_contents("https://i.imgur.com/cCc9Gw9.png")
                    ];
      
      $products[] = [
                    'product_name' => 'MySQL DATABASES',
                    'price' => 15,
                    'product_image' => file_get_contents("https://i.imgur.com/UYcHkKD.png" )
                    ];
      
      $sql = "INSERT INTO products(product_name, price, product_image) VALUES (:product_name, :price, :product_image)";
      
      foreach ($products as $product) {
          $stmt = $pdo->prepare($sql);
          $stmt->execute($product);
      }
      
      echo "Records inserted successfully";
      

      Save and close the file.

      In the file, you’ve included the config.php file at the top. This is the first file you created for defining the database variables and connecting to the database. The file also initiates a PDO object and stores it in a $pdo variable.

      Next, you’ve created an array of the products’ data to be inserted into the database. Apart from the product_name and price, which are prepared as strings and numeric values respectively, the script uses PHP’s in-built file_get_contents function to read images from an external source and pass them as strings to the product_image column.

      Next, you have prepared an SQL statement and used the PHP foreach{...} statement to insert each product into the database.

      To execute the /var/www/html/insert_products.php file, run it in your browser window using the following URL. Remember to replace your-server-IP with the public IP address of your server:

      http://your-server-IP/insert_products.php
      

      After executing the file, you’ll see a success message in your browser confirming records were inserted into the database.

      A success message showing that records were inserted to database

      You have successfully inserted three records containing product images into the products table. In the next step, you’ll create a PHP script for retrieving these records and displaying them in your browser.

      Step 3 — Displaying Products’ Information From the MySQL Database

      With the products’ information and images in the database, you’re now going to code another PHP script that queries and displays the products’ information in an HTML table on your browser.

      To create the file, type the following:

      • sudo nano /var/www/html/display_products.php

      Then, enter the following information into the file:

      /var/www/html/display_products.php

      <html>
        <title>Using BLOB and MySQL</title>
        <body>
      
        <?php
      
        require_once 'config.php';
      
        $sql = "SELECT * FROM products";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        ?>
      
        <table border = '1' align = 'center'> <caption>Products Database</caption>
          <tr>
            <th>Product Id</th>
            <th>Product Name</th>
            <th>Price</th>
            <th>Product Image</th>
          </tr>
      
        <?php
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo '<tr>';
            echo '<td>' . $row['product_id'] . '</td>';
            echo '<td>' . $row['product_name'] . '</td>';
            echo '<td>' . $row['price'] . '</td>';
            echo '<td>' .
            '<img src = "data:image/png;base64,' . base64_encode($row['product_image']) . '" width = "50px" height = "50px"/>'
            . '</td>';
            echo '</tr>';
        }
        ?>
      
        </table>
        </body>
      </html>
      

      Save the changes to the file and close it.

      Here you’ve again included the config.php file in order to connect to the database. Then, you have prepared and executed an SQL statement using PDO to retrieve all items from the products table using the SELECT * FROM products command.

      Next, you have created an HTML table and populated it with the products’ data using the PHP while() {...} statement. The line $row = $stmt->fetch(PDO::FETCH_ASSOC) queries the database and stores the result in the $row variable as a multi-dimensional array, which you have then displayed in an HTML table column using the $row['column_name'] syntax.

      The images from the product_image column are enclosed inside the <img src = ""> tags. You’ve used the width and height attributes to resize the images to a smaller size that can fit in the HTML table column.

      In order to convert the data held by the BLOB data type back to images, you’ve used the in-built PHP base64_encode function and the following syntax for the Data URI scheme:

      data:media_type;base64, base_64_encoded_data
      

      In this case, the image/png is the media_type and the Base64 encoded string from the product_image column is the base_64_encoded_data.

      Next, execute the display_products.php file in a web browser by typing the following address:

      http://your-server-IP/display_products.php
      

      After running the display_products.php file in your browser, you will see an HTML table with a list of products and associated images.

      List of products from MySQL database

      This confirms that the PHP script for retrieving images from MySQL is working as expected.

      Conclusion

      In this guide, you used the MySQL BLOB data type to store and display images with PHP on Ubuntu 18.04. You’ve also seen the basic advantages of storing images in a database as opposed to storing them in a file system. These include portability, security, and ease of backup. If you are building an application such as a students’ portal or employees’ database that requires information and related images to be stored together, then this technology can be of great use to you.

      For more information about the supported data types in MySQL follow the MySQL Data Types guide. If you’re interested in further content relating to MySQL and PHP, check out the following tutorials:



      Source link