如何在更新之前让sql检查多个条件?

时间:2013-08-09 15:46:22

标签: php sql sql-server-2008

我正在使用php,一些javascript和sql server 2008进行调度项目。用户可以使用作业表单来更新预定作业。可以更改的字段包括:作业编号,开始时间,结束时间,描述和作业状态。 sql需要在更新之前测试所有这些内容。

  1. 我遇到的一些问题是:
    1. 如果用户增加了结束时间(以后的时间),则允许在计划中重叠
    2. 如果用户将开始时间移回(更早的时间),则允许重叠
    3. 如果用户选择过去的日程安排日期,则会与将来安排的项目发生日程安排冲突。
  2. 我已经坚持了两天,并且已经多方向去解决这些问题。这就是我目前所拥有的:

     <?php 
    include_once("../php/functions.php");
        $conn = connect();
        $params = array
            (
                $jobNum         =   $_POST['jobNum'],
                $asset          =   $_POST['drp_asset'],
                $jobStatus      =   $_POST['drp_status'],
                $sDate          =   $_POST['startTime'],
                $eDate          =   $_POST['endTime'],
                $department     =   $_POST['drp_department'],
                $descrip        =   $_POST['txtarea_description'],
                $job            =   $_POST['jobid'],
                $asset2         =   $_POST['drp_asset']
            );
    /********************************************
    Check to see if the delete button was pressed
    And if the pre-check warning was confirmed 
    delete the record.
    ********************************************/
    if (isset($_POST['updateDelete']))
    {
        $tsql = "Delete from Calendar_view
                where JobID = '$job'";
    
        $stmt = sqlsrv_query($conn, $tsql);
        if ($stmt)
        {
            checkRows($stmt);
            returnTo($conn);
        }
        else
        {
            errMsg();
        }
    }
    /****************************************
    If the times and/or asset have not changed 
    update the job status
    ****************************************/
    else
    {
        $tsql_check ="select StartTime, EndTime, Asset
                        from  Calendar_View
                        where '$sDate' = StartTime and '$eDate' = EndTime and '$asset' = Asset";
        $stmt = sqlsrv_query($conn, $tsql_check);
        $rows = sqlsrv_has_rows($stmt);
        if($stmt)
        {
            if ($rows === true)
            {
                updateJobStatus($conn, $params);
            }
    
            else
            {
                timeChanges($conn, $params);
            }
        }
    }
    
    function checkOverlaps($conn, $params)
    {
        $sDate = $params[3];
        //$sDate = new DateTime($params[4]);
        //$sDate = date_format($sDate,'Y-m-d G:i:s');
        $eDate = $params[4];
        //$eDate = new DateTime($params[5]);
        //$eDate = date_format($eDate,'Y-m-d G:i:s');
        $asset = $params[1];
    
        $tsql_check ="select StartTime, EndTime
                        from  Calendar_View
                        where (('$sDate' < EndTime and '$sDate' >= StartTime) or ('$eDate' < EndTime and '$eDate' > StartTime)) and '$asset' = Asset";
        $stmt = sqlsrv_query($conn, $tsql_check);
    
        if ($stmt)
        {
            // If there is a match, there will be an overlap
            $rows = sqlsrv_has_rows($stmt);
            if ($rows === true)
            {
                checkRows($stmt);
            }
            //If there is no match then job is being moved
            //to an open spot
            else
            {
                updateJob($conn, $params);
            }
        }
    }
    /************************************
    If the start time or end time have changed
    /***********************************/
    function timeChanges($conn, $params)
    {
        $sDate = $params[3];
        $eDate = $params[4];
        $asset = $params[1];
    
        $tsql_timeCheck ="select StartTime, EndTime
                        from  Calendar_View
                        where (('$sDate' <= StartTime) or ('$eDate' <= EndTime)) and '$asset' = Asset"; 
        $stmt2 = sqlsrv_query($conn, $tsql_timeCheck);
    
        if ($stmt2 == true)
        {
            $rows = sqlsrv_has_rows($stmt2);
            if ($rows === true)
            {
                updateJobStatus($conn, $params);
                //updateJobStatus($conn, $params);
            }
            else
            {
                checkOverlaps($conn, $params);
            }
        }
    }
    function updateJob($conn, $params)
    {
        $tsql = "UPDATE Calendar_View
                    SET     JobNum = ?,
                            Asset = ?,
                            JobStatus =?,
                            StartTime =?,
                            EndTime =?,
                            Department = ?,
                            Description = ?
                    WHERE   JobID = ?";
    
        $stmt = sqlsrv_query($conn, $tsql, $params);
        if ($stmt)
        {
            checkRows($stmt);
            returnTo($conn);
        }
            else
        {
            errMsg();
        }
    }
    /***************************************
    Update job status
    ****************************************/
    function updateJobStatus($conn, $params)
    {
        $tsql = "UPDATE Calendar_View
                    SET     JobNum = ?,
                            Asset = ?,
                            JobStatus =?,
                            StartTime =?,
                            EndTime =?,
                            Department = ?,
                            Description = ?
                    WHERE   JobID = ? and Asset = ?";
    
        $stmt = sqlsrv_query($conn, $tsql, $params);
        if ($stmt)
        {
            checkRows($stmt);
            returnTo($conn);
        }
            else
        {
            errMsg();
        }
    }
    /**********************************
    Return user to scheduling page they
    were working on.
    ***********************************/
    function returnTo($conn)
    {
        sqlsrv_close($conn);
        echo "<meta http-equiv='refresh' content='1;URL=../pages/schedule2.php' />";
    }
    function errMsg()
    {
        die( print_r(sqlsrv_errors(), true));
        exit;
    }
    /*************************************
    Check if any rows were altered by the 
    query. If so alert success, else alert
    that there was a conflict (nothing done)
    **************************************/
    function checkRows($stmt)
    {
        $rows_affected = sqlsrv_rows_affected($stmt);
        if ($rows_affected > 0)
        {
        echo "Job updated successfully!<br>";
        }
        else
        echo "There was a scheduling conflict.";
        echo "<meta http-equiv='refresh' content='2;URL=../pages/schedule2.php' />";
    }
    ?>
    

    非常感谢任何和所有帮助!

3 个答案:

答案 0 :(得分:1)

我看到很多查询来检查一切是否正常......你也可以使用这种方法:

  • 首先创建一个映射数组,如下所示:

    Array( 'key1' => 'val1',
       'key2' => 'val2',
       'key3' => 'val3',
       'key4' => 'val4');
    
  • 确保将帖子变量放在此结构中

  • 确保对数据库中与映射对应的所有字段执行查询,并将它们放入相同结构的新实例中

  • 使用array_diff_assoc比较差异

  • 如果时间上有不同的内容,请执行一些逻辑(可能是查询数据库)以查看日期是否匹配

如果你需要帮助来实现这个想法,我可以帮助你,但先为自己尝试一些事情;)

答案 1 :(得分:0)

在找到更有效的解决方案之前,您可以在事务中进行更改,然后查询数据库以查看是否有任何条件失败。如果他们这样做,你可以回滚。

我想要非常小心,你应该查询更新前后的失败次数,如果失败则回滚。这样,您可以确定您的更改是引入错误的更改。

答案 2 :(得分:0)

以下解决方案用于检查计划中的所有重叠。

<?php 
include_once("../php/functions.php");
    $conn = connect();

    $controlDate1   =   date_format(new DateTime($_POST['pickedDate']),'Y-m-d H:i:s');
    $controlDate2   =   date_format(new DateTime($_POST['pickedDate']),'Y-m-d 23:59:00');
    $jobNum         =   $_POST['jobNum'];
    $asset          =   $_POST['drp_asset'];
    $jobStatus      =   $_POST['drp_status'];
    $sDate          =   date_format(new DateTime($_POST['startTime']),'Y-m-d H:i:s');
    $eDate          =   date_format(new DateTime($_POST['endTime']),'Y-m-d H:i:s');
    $descrip        =   $_POST['txtarea_description'];
    $job            =   $_POST['jobid'];
/*****************************************************
used for testing purposes
******************************************************
$checkVals = array(
            $controlDate1   =   $controlDate1,
            $controlDate2   =   $controlDate2,
            $jobNum         =   $_POST['jobNum'],
            $asset          =   $_POST['drp_asset'],
            $jobStatus      =   $_POST['drp_status'],
            $sDate          =   $sDate,
            $eDate          =   $eDate,
            $descrip        =   $_POST['txtarea_description'],
            $job            =   $_POST['jobid'],
            );
/***************************************************/
/********************************************
Check to see if the delete button was pressed
And if the pre-check warning was confirmed 
delete the record.
********************************************/
if (isset($_POST['updateDelete']))
{
    $tsql = "Delete from Calendar_view
            where JobID = '$job'";

    $stmt = sqlsrv_query($conn, $tsql);
    if ($stmt)
    {
        checkRows($stmt);
        returnTo($conn);
    }
    else
    {
        errMsg();
    }
}
/****************************************
If the times and/or asset have not changed 
update the job status, description
****************************************/
else
{
    $tsql_check ="SELECT JobNum, StartTime, EndTime, Description, Asset, JobStatus, JobID
                    from  Calendar_View
                    where JobID = '$job' and JobNum = '$jobNum' and StartTime = '$sDate' and EndTime = '$eDate' and Asset = '$asset'";
    $stmt = sqlsrv_query($conn, $tsql_check);
    $rows = sqlsrv_has_rows($stmt);
    if($stmt)
    {
        if ($rows === true)
        {
            $params = array($jobStatus,$descrip, $job, $asset);
            updateJobStatus($conn, $params);
        }

        else
        {
            $tsql_check ="SELECT JobNum, StartTime, EndTime, Description, Asset, JobStatus, JobID
                            from  Calendar_View
                            where (JobID != '$job' and 
                            (StartTime < '$controlDate2' and StartTime > '$controlDate1') and 
                            (('$sDate' < EndTime and '$sDate' >= StartTime) or ('$eDate' < EndTime and '$eDate' > StartTime) or ('$sDate' < StartTime and '$eDate' > EndTime)))
                            and Asset = '$asset'";
            $stmt = sqlsrv_query($conn, $tsql_check);
            $rows = sqlsrv_has_rows($stmt);
            if($stmt)
            {
                if ($rows === true)
                {
                    checkRows($stmt);
                }
                else
                {
                    //pass values to updateJob()
                    $params = array($jobNum,
                                    $asset,
                                    $jobStatus,
                                    $sDate,
                                    $eDate,
                                    $descrip,
                                    $job);
                    updateJob($conn, $params);
                }
            }
        }
    }
}
function updateJob($conn, $params)
{
    $tsql = "UPDATE Calendar_View
                SET     JobNum = ?,
                        Asset = ?,
                        JobStatus =?,
                        StartTime =?,
                        EndTime =?,
                        Description = ?
                WHERE   JobID = ?";

    $stmt = sqlsrv_query($conn, $tsql, $params);
    if ($stmt)
    {
        checkRows($stmt);
        returnTo($conn);
    }
        else
    {
        errMsg();
    }
}
/***************************************
Update job status
****************************************/
function updateJobStatus($conn, $params)
{
    $tsql = "UPDATE Calendar_View
                SET     JobStatus =?,
                        Description = ?
                WHERE   JobID = ? and Asset = ?";

    $stmt = sqlsrv_query($conn, $tsql, $params);
    if ($stmt)
    {
        checkRows($stmt);
        returnTo($conn);
    }
        else
    {
        errMsg();
    }
}
/**********************************
Return user to scheduling page they
were working on.
***********************************/
function returnTo($conn)
{
    sqlsrv_close($conn);
    echo "<meta http-equiv='refresh' content='1;URL=../pages/schedule2.php' />";
}
function errMsg()
{
    die( print_r(sqlsrv_errors(), true));
    exit;
}
/*************************************
Check if any rows were altered by the 
query. If so alert success, else alert
that there was a conflict (nothing done)
**************************************/
function checkRows($stmt)
{
    $rows_affected = sqlsrv_rows_affected($stmt);
    if ($rows_affected > 0)
    {
        echo "Job updated successfully!<br>";
    }
    else
    {
        echo "There was a scheduling conflict.";
    }
    echo "<meta http-equiv='refresh' content='2;URL=../pages/schedule2.php' />";
}
?>