Introduction:
In an inventory management system, the inventory query function is crucial. It helps the management team quickly check the status of inventory, track inventory changes, and generate timely reports. This article will show you how to write a simple inventory query function in PHP, helping readers understand the basic steps to implement this feature.
First, we need to create a database table to store the inventory information. Let's assume the table is named "inventory" and contains the following fields:
You can use the following SQL statement to create this table:
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;
Next, we need to establish a connection to the database in our code so that we can perform inventory query operations. Use the following code to create the database connection:
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "inventory_db"; // Create database connection $conn = new mysqli($servername, $username, $password, $dbname); // Check if the connection is successful if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Successfully connected to the database!";
Make sure to adjust the database connection parameters ($servername, $username, $password, and $dbname) according to your environment.
Now, let's write the actual code for the inventory query function. The following code will query inventory information from the database and display it on the webpage:
// Query inventory information $sql = "SELECT * FROM inventory"; $result = $conn->query($sql); if ($result->num_rows > 0) { // Output each row of data while($row = $result->fetch_assoc()) { echo "Product Name: " . $row["name"] . " - Stock Quantity: " . $row["quantity"] . " - Product Price: $" . $row["price"] . "<br>"; } } else { echo "No inventory information"; } // Close the database connection $conn->close();
This code executes a simple SELECT query to retrieve all data from the "inventory" table in the database. Then, it loops through the results and displays the product name, stock quantity, and product price.
Through the above code example, we have learned how to implement an inventory query function in a PHP-based inventory management system. This simple example provides a basic framework, which you can modify and extend based on your needs. We hope this article helps you understand how to write inventory query functions!