Current Location: Home> Latest Articles> How to Implement Inventory Query Function in PHP: A Simple Tutorial and Code Example

How to Implement Inventory Query Function in PHP: A Simple Tutorial and Code Example

gitbox 2025-06-13

Introduction

For an inventory management system, the inventory query function is crucial. It helps businesses keep track of inventory status and provides timely inventory reports. In this article, we will walk through a simple PHP code example that demonstrates how to implement this query function.

1. Creating the Database Table

First, we need to create a database table to store inventory information. Let’s assume the table is named "inventory" and contains the following fields:

  • id (Primary key, auto-increment)
  • name (Product name)
  • quantity (Inventory quantity)
  • price (Product price)

You can create the table with the following SQL statement:

  CREATE TABLE inventory (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(255) NOT NULL,
    quantity int(11) NOT NULL,
    price decimal(10,2) NOT NULL,
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  

2. Connecting to the Database

In the code, we need to first establish a connection to the database, so that we can perform subsequent inventory query operations. Below is the code to connect to the database:

  <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "inventory_db";

    // Create database connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }

    echo "Database connected successfully!";
  ?>
  

Make sure to adjust the $servername, $username, $password, and $dbname variables according to your actual database setup.

3. Writing the Inventory Query Code

Next, we will write the inventory query function code. This will fetch inventory information from the database and display it on the webpage. Here is the full code:

  <?php
    // Query inventory information
    $sql = "SELECT * FROM inventory";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
      // Output data for each row
      while ($row = $result->fetch_assoc()) {
        echo "Product Name: " . $row["name"] . " - Quantity: " . $row["quantity"] . " - Price: $" . $row["price"] . "<br>";
      }
    } else {
      echo "No inventory data found";
    }

    // Close database connection
    $conn->close();
  ?>
  

Conclusion

Through the code example above, we have learned how to implement a basic inventory query function in PHP. This simple example provides a framework that you can further modify and extend to meet the needs of different inventory management systems.