有缺陷的插入算法


Defective Insert Algorithm

我正在实现一个系统,该系统可以在产品进货和缺货时跟踪所有实例。我在表中有一列记录了给定记录是打开还是关闭(打开意味着它缺货,还没有重新进货,关闭意味着它在某个时候又有存货)。到目前为止,在确保SQL查询工作时,我还没有遇到过那么多SQL查询问题。但是,我一直在运行用于此表填充的脚本,并且没有任何内容插入到表中。

我用于此特定表的更新的函数如下。

//Records item as being back in stock
function itemInStock($item){
    $db_controller = new DBHandler();
    $selectQuery = "SELECT * FROM out_of_stock_record
                    WHERE ListID = '$item->ID'
                    AND Status = 'OPEN'";
    $rs = $db_controller->select($selectQuery);
    /*If this record exists, then the only thing we need to do is update the BackInStockTS and Status columns.  It came back in stock on this date at this time, therefore it's closed.*/
    if($rs){
        $currentDate = date("Y-m-d H:i:s");
        $updateQuery = "UPDATE out_of_stock_record 
                        SET BackInStockTS = '$currentDate', Status = 'CLOSED' 
                        WHERE ID = '$item->ListID' AND Status = 'OPEN'";
        $db_controller->update($updateQuery);
    }
}
//Records item as being out of stock
function itemOOStock($item){
    $db_controller = new DBHandler();
    $selectQuery = "SELECT ID FROM out_of_stock_record
                    WHERE ID = '$item->ID'
                    AND Status = 'OPEN'";
    $rs = $db_controller->select($selectQuery);
    /*We only need to make sure the record DOESN'T exist, because if that's true, then all we need to do is insert this.  If it already exists, there's nothing to do.
      The only other check occurs later on that sees if the item is back in stock, then updates the existing open record in order to close it and record the date it
      came back in stock.*/
    if(!$rs){
        $currentDate = date("Y-m-d H:i:s");
        $start = "INSERT INTO out_of_stock_record (ID, OutOfStockTS, BackInStockTS, Status) VALUES (";
        $end = sprintf("'%s', '%s', NULL, '%s')", $item->ID, $currentDate, "OPEN");
        $start .= $end;
        $db_controller->insert($start);
    }
}

我不知道问题出在哪里。在这个脚本的另一个部分中,我使用完全相同的数据库处理程序来插入一个不同名称的表,但我没有任何问题,我不确定这是否与表的结构有关。它包括ID和状态的varchar列,OOS和IS日期的datetime列,我还包括了另一列,用于记录该表的最后一次更新,但在插入时会自动更改。

除了我无意中创建并后来更正的一些问题外,我以前从未对这个脚本有过任何问题。该表应该在我每次访问此页面的URL时更新。关于可能导致这种情况的原因,有什么建议吗?如果有帮助的话,这个脚本使用的数据库和它所在的网站都在同一台服务器上。

我对if语句使用了错误的检查。它们本来应该是这样的。

if(mysql_num_rows($rs) == 0){
    //Insert record
}
if(mysql_num_rows($rs) != 0){
    //Update record
}