PHP如果num_rows不为空,则插入数据,否则更新信息

时间:2018-03-20 15:10:45

标签: php mysqli

我得到了这个执行此函数的if语句

如果表不为空,则更新所需信息,否则执行insert查询。但问题是我无法进入插入部分,而是即使表是空的,我也会返回更新查询。

下面是我的查询,它检查信息是否已经在表格中。

$checkquery = "SELECT user_type_id , user_school_verification_id , resource_no ,resource_title , SUM(quantity) as Total_Quantity FROM tbl_borrow_issuance WHERE user_type_id = ? AND user_school_verification_id = ? AND resource_no = ?";
    $stmt1 = $mysqlconnection->prepare($checkquery);
    $stmt1->bind_param("sss",$getusertype, $getstudentno , $getresourceno );
    $stmt1->execute();
    $stmt1->store_result();
    $stmt1->bind_result($user_type_id, $user_school_verification_id, $resource_no, $resource_title, $Total_Quantity );

这是我的if语句

if($stmt1->num_rows > 0){

    while ($stmt2->fetch())
    {
        $user_type_id = $user_type_id;
        $borrow_count = $borrow_count;  
        $Total_Quantity = $Total_Quantity;
        $resource_no = $resource_no;
        // $gettotalfinal = $getresourcequantity + 

        if ($getusertype == $user_type_id && $getresourcequantity <= $borrow_count)
        {
            if ($getusertype == $user_type_id && $Total_Quantity == $borrow_count){

                echo "ERRORMAX";

            }
            else
            {
                $add_quantity = "UPDATE tbl_borrow_issuance SET quantity = quantity + ? WHERE resource_no = ? ";
                $stmt3 = $mysqlconnection->prepare($add_quantity);
                $stmt3->bind_param("ss", $getresourcequantity, $resource_no);
                if ($stmt3->execute()) {
                    echo "SUCCESS";
                }else
                {
                echo "ERROR";
                }
            }
        }
        else
        {
        echo "ERRORUSER";
        }
    }   
}
else
{
        $query = "INSERT INTO tbl_borrow_issuance (user_type_id , user_school_verification_id, resource_no , resource_title , quantity ) VALUES (? , ? , ? ,? , ?)";
        $stmt = $mysqlconnection->prepare($query);
        $stmt->bind_param("sssss",$getusertype, $getstudentno, $getresourceno , $getresourcetitle ,$getresourcequantity);
        if ($stmt->execute()) 
        {

            echo "SUCCESS1";
        }
        else
        {

            echo "ERROR";
        }
}

1 个答案:

答案 0 :(得分:0)

在查询中使用SUM时,您正在执行聚合查询。长话短说,这个查询总是返回1行,没有其他表格。

您想要检查总数量,而不是行号。

所以将if改为:

if($Total_Quantity > 0){

应该做的伎俩。