search
HomeBackend DevelopmentPHP TutorialHow to use PHP and Vue to develop price management functions for warehouse management

How to use PHP and Vue to develop price management functions for warehouse management

How to use PHP and Vue to develop the price management function of warehouse management

In modern logistics warehousing management, price management is a crucial function. It can help warehouse managers and logistics personnel accurately manage the pricing information of inventory items for reasonable pricing and profit control of goods. This article will introduce how to use PHP and Vue to develop the price management function in the warehouse management system, and provide specific code examples.

1. Preparation
Before you start, make sure you have installed the development environment of PHP and Vue. You can use any code editor you like to write code.

2. Create a database table
First, we need to create a database table to store price information. Suppose our table is named prices and contains the following fields:

  • id: the unique identifier of the price record, auto-increment type
  • product_name: Product name, string type
  • #price: Price, floating point type
  • created_at: Record creation Time, date time type
  • updated_at: Record update time, date time type

You can use the following SQL statement to create a database table:

CREATE TABLE `prices` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `product_name` VARCHAR(255) NOT NULL,
  `price` FLOAT NOT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=INNODB;

3. Writing the back-end interface
Next, we need to use PHP to write the back-end interface to handle the price management function. Create a PHP file price.php and add the following code:

<?php
header('Content-Type: application/json');

// 连接数据库
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "your_database_name";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// 获取所有价格记录
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $sql = "SELECT * FROM `prices`";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $prices = [];
        while ($row = $result->fetch_assoc()) {
            $prices[] = $row;
        }
        echo json_encode($prices);
    } else {
        echo "[]";
    }
}

// 添加价格记录
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_name = $_POST['product_name'];
    $price = $_POST['price'];

    $sql = "INSERT INTO `prices` (`product_name`, `price`) VALUES ('$product_name', '$price')";
    if ($conn->query($sql) === TRUE) {
        echo "Price record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// 更新价格记录
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    parse_str(file_get_contents("php://input"), $put_vars);

    $id = $put_vars['id'];
    $product_name = $put_vars['product_name'];
    $price = $put_vars['price'];

    $sql = "UPDATE `prices` SET `product_name`='$product_name', `price`='$price', `updated_at`=CURRENT_TIMESTAMP WHERE `id`='$id'";
    if ($conn->query($sql) === TRUE) {
        echo "Price record updated successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// 删除价格记录
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    parse_str(file_get_contents("php://input"), $delete_vars);

    $id = $delete_vars['id'];

    $sql = "DELETE FROM `prices` WHERE `id`='$id'";
    if ($conn->query($sql) === TRUE) {
        echo "Price record deleted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

$conn->close();
?>

Make sure to replace your_database_name with your database name and modify the database connection information as needed.

4. Writing the front-end page
We will use Vue to write the front-end page. Create an HTML file index.html and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>价格管理</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <div id="app">
        <h1 id="价格管理">价格管理</h1>
        <form @submit.prevent="addPrice">
            <input type="text" placeholder="产品名称" v-model="newPrice.product_name" required>
            <input type="number" step="0.01" placeholder="价格" v-model="newPrice.price" required>
            <button type="submit">添加</button>
        </form>
        <table>
            <thead>
                <tr>
                    <th>产品名称</th>
                    <th>价格</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="price in prices" :key="price.id">
                    <td>{{ price.product_name }}</td>
                    <td>{{ price.price }}</td>
                    <td>
                        <button @click="editPrice(price)">编辑</button>
                        <button @click="deletePrice(price)">删除</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <script>
        new Vue({
            el: '#app',
            data: {
                prices: [],
                newPrice: {
                    product_name: '',
                    price: ''
                },
                editPrice: {
                    id: '',
                    product_name: '',
                    price: ''
                }
            },
            created: function() {
                this.getPrices();
            },
            methods: {
                getPrices: function() {
                    axios.get('price.php')
                        .then(function(response) {
                            this.prices = response.data;
                        }.bind(this))
                        .catch(function(error) {
                            console.log(error);
                        });
                },
                addPrice: function() {
                    axios.post('price.php', this.newPrice)
                        .then(function(response) {
                            console.log(response.data);
                            this.getPrices();
                            this.newPrice.product_name = '';
                            this.newPrice.price = '';
                        }.bind(this))
                        .catch(function(error) {
                            console.log(error);
                        });
                },
                editPrice: function(price) {
                    this.editPrice.id = price.id;
                    this.editPrice.product_name = price.product_name;
                    this.editPrice.price = price.price;
                },
                updatePrice: function() {
                    axios.put('price.php', this.editPrice)
                        .then(function(response) {
                            console.log(response.data);
                            this.getPrices();
                            this.editPrice.id = '';
                            this.editPrice.product_name = '';
                            this.editPrice.price = '';
                        }.bind(this))
                        .catch(function(error) {
                            console.log(error);
                        });
                },
                deletePrice: function(price) {
                    axios.delete('price.php', { data: price })
                        .then(function(response) {
                            console.log(response.data);
                            this.getPrices();
                        }.bind(this))
                        .catch(function(error) {
                            console.log(error);
                        });
                }
            }
        });
    </script>
</body>
</html>

5. Run the project
and change price.php and index.htmlPut the file into the website directory of your server and start the server. Then open the browser and visit index.html, and you will see a simple price management page.

On the page, you can enter the product name and price, and click the Add button to add a new price record. Click the Edit button to modify the price record information. Click the Delete button to delete the price record.

6. Summary
In this article, we used PHP and Vue to develop the price management function in a simple warehouse management system. Through this function, warehouse administrators can easily manage product pricing information and achieve reasonable pricing and profit control. By writing the back-end interface and front-end page, we show how to use PHP and Vue to implement this function, and provide detailed code examples. Hope this article is helpful to you!

The above is the detailed content of How to use PHP and Vue to develop price management functions for warehouse management. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.