用于获取库存数量的SQL SELECT查询未在函数中返回值但从phpMyAdmin返回

问题描述

当我手动编辑库存水平时,我正在wordpress / Woocommerce中的一个函数中运行此代码以将库存值更新到wp_stock_log表。 我正在尝试获取产品的最新“数量”值,然后将其设置为var $ old_qty。 然后,我想将其作为“ old_qty”插入到新行的表中,以便查看库存量增加了多少。

当我在PHPMyAdmin中运行SELECT查询时,我成功获取了最后一行的'qty',但是当我在wordpress中运行该函数时,我总是得到的值为1。

我已经测试过,是否从SQL查询返回的值是整数,但不是-但不确定为什么为什么'qty'列是整数类型?即使将其转换为整数,我也总是获得$ old_qty值为'1'。

为什么我总是得到1的值?

    public function save_stock( $product ) {
        $current_user = wp_get_current_user();
        global $wpdb;
        
        //get the most recent qty for the product from wp_stock_log table
        $old_qty = $wpdb->get_results("SELECT qty FROM wp_stock_log WHERE product_id = '".$product->get_id()."' ORDER BY id DESC LIMIT 1 ");
        
        $old_qty = intval($old_qty);
        $qty = $product->get_stock_quantity();

        $data = array();

        $data['date_created'] = date( 'Y-m-d H:i:s',time() );
        $data['old_qty'] = $old_qty;
        $data['qty'] = $product->get_stock_quantity();
        $data['product_id'] = $product->get_id();
        $data['user'] = $current_user->display_name;
        $data['reason'] = 'Stock Level Adjusted';
        $wpdb->insert( $wpdb->prefix.'stock_log',$data ); 
    
    }

编辑 wp_stock_logs表结构如下:

|--------|--------------|------------|-----|---------|---------|----------|
|   ID   | date_created | product_id | qty | old_qty | user    | reason   |
|--------|--------------|------------|-----|---------|---------|----------|
| bigint | datetime     |  bigint    | int | int     | varchar | varchar  |
|--------|--------------|------------|-----|---------|---------|----------|
|   1    | 14-08-2020   | 123        | 12  | 10      | user1   | added 2  |
|--------|--------------|------------|-----|---------|---------|----------|
|   2    | 15-08-2020   | 123        | 15  | 12      | user1   | added 3  |
|--------|--------------|------------|-----|---------|---------|----------|
|   3    | 15-08-2020   | 123        | 14  | 15      | user1   | deduct 1 |
|--------|--------------|------------|-----|---------|---------|----------|

解决方法

由于我只想从数据库中检索单个值,因此应使用 get_var ,而不要使用 get_results (返回数组)。

azure-cli