简体   繁体   中英

How do I subtract a number from my quantity stored in my mysql database

I have a website which is used to key in and store stock data. Right now I am creating a component which is used to take out stock. What I want to do is key in a number in the text box and the database will subtract the number from the quantity.

I have tried subtracting with a fixed hard coded number such as

//rest api to update record in mysql database
app.put('/stockdata/subtract', function (req, res) {
  connection.query('UPDATE stockin SET Quantity = Quantity - 5 WHERE id=?', [req.body.Quantity, req.body.id], function (error, results, fields) {
    if (error) throw error;
    res.end(JSON.stringify(results));
  })

It works well. But when i wants to change the -5 to my own input I don't know how to get it working. Here is my input code

// component that contains the logic to update a product
window.UpdateProductComponent = React.createClass({
    getInitialState: function () {
        // Get this product fields from the data attributes we set on the
        // #content div, using jQuery
        return {
            id: 0,
            Quantity: 0,
            successUpdate: null
        };
    },

    // on mount, fetch all categories and one product data to stored them as this component's state
    componentDidMount: function () {
        // read one product data
        var productId = this.props.productId;
        this.serverRequestProd = $.get("http://localhost:4000/stockdata/" + productId,
            function (product) {
                this.setState({ id: product.id });
                this.setState({ Quantity: product.Quantity });
            }.bind(this));

        $('.page-header h1').text('Update product');
    },

    // on unmount, kill categories fetching in case the request is still pending
    componentWillUnmount: function () {
        this.serverRequestCat.abort();
        this.serverRequestProd.abort();
    },
    // handle Quantity change
    onQuantityChange: function (e) {
        this.setState({ Quantity: e.target.value });
    },

    // handle save changes button clicked
    onSave: function (e) {
        var productId = this.props.productId;
        // data in the form
        var form_data = {
            id: this.props.productId,
            Quantity: this.state.Quantity,
        };

        // submit form data to api
        $.ajax({
            url: "http://localhost:4000/stockdata/subtractfiv",
            type: "PUT",
            contentType: 'application/json',
            data: JSON.stringify(form_data),
            success: function (response) {
                this.setState({ successUpdate: response['message'] });
            }.bind(this),
            error: function (xhr, resp, text) {
                // show error to console
                console.log(xhr, resp, text);
            }
        });

        e.preventDefault();
    },

    render: function () {
        return (
            <div>
                {
                    this.state.successUpdate == "Product was updated." ?
                        <div className='alert alert-success'>
                            Product was updated.
                    </div>
                        : null
                }

                {
                    this.state.successUpdate == "Unable to update product." ?
                        <div className='alert alert-danger'>
                            Unable to update product. Please try again.
                    </div>
                        : null
                }

                <a href='#'
                    onClick={() => this.props.changeAppMode('read')}
                    className='btn btn-primary margin-bottom-1em'>
                    Read Products
            </a>

                <form onSubmit={this.onSave}>
                    <table className='table table-bordered table-hover'>
                        <tbody>
                            <tr>
                                <td>Quantity </td>
                                <td>
                                    <input
                                        type='number'
                                        className='form-control'
                                        value={this.props.Quantity}
                                        required
                                        onChange={this.onQuantityChange} />
                                </td>
                                <tr>
                                    <td></td>
                                    <td>
                                        <button
                                            className='btn btn-primary'
                                            onClick={this.onSave}>Save Changes</button>
                                    </td>
                                </tr>
                            </tr>
                        </tbody>
                    </table>
                </form>
            </div>
        );
    }

});

Is there anyway I could subtract the quantity in my database with my own input number?

I suspect it's something like this: (never used mysqljs)

connection.query('UPDATE stockin SET Quantity = Quantity - ? WHERE id=?', [req.body.Quantity, req.body.id] ...

Just make sure your Quantity value in your request is not 0!

For more info see How to pass parameters to mysql query callback in nodejs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM