如果未创建行,则发送PHP错误

时间:2018-08-14 13:51:48

标签: php sql sql-server

我正在尝试防止创建重复的行。我当前的语句有效,这意味着它可以防止创建重复项,但是它总是将执行成功返回,这意味着如果未创建任何行,我不会收到“错误”消息。

谢谢

$tsql = "
    IF NOT EXISTS ( SELECT 1 FROM SOMETABLE WHERE SOMEROW = 'VALUE' )
        BEGIN
            INSERT INTO SOMETABLE (
                SOMEROW
            )

            VALUES (
                'SOMETHING'
            )
            END
    ";


$stmt = sqlsrv_query( $conn, $tsql);


if(gettype($stmt)=='boolean'){
    if($stmt){
        echo "Success"; 
    } else {
        echo "This Row already Exists";
        die( print_r( sqlsrv_errors(), true));  
    } 

如果未创建任何内容,我想失败 sql执行,在这种情况下不会执行。 (总是成功发送回去。

谢谢

2 个答案:

答案 0 :(得分:1)

解决方案1:

此解决方案基于您所期望的方法,并在使用RAISEERROR()的SQL状态下引发错误,因此sqlsrv_query()将返回FALSE

<?php
# Connection
$server = 'server\instance,port';
$database = 'database';
$uid = 'username';
$pwd = 'password';
$cinfo = array(
    "Database" => $database,
    "UID" => $uid,
    "PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if ( $conn === false ) {
    echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
    exit;
}

# INSERT statement
$tsql = 
    "
    IF NOT EXISTS (SELECT 1 FROM SOMETABLE WHERE SOMEROW = 'VALUE5' ) BEGIN
        INSERT INTO SOMETABLE (SOMEROW) VALUES ('VALUE5')
        END
    ELSE BEGIN
        RAISERROR (N'This row already exists.', 10, 1);
    END;
    ";
$stmt = sqlsrv_query($conn, $tsql);  
if ($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
} else {
    sqlsrv_free_stmt($stmt);
    echo "Success"; 
}   

# End
sqlsrv_close($conn);
?>

解决方案2:

可以返回语句的输出,然后使用sqlsrv_fetch_array()检查结果:

<?php
# Connection
$server = 'server\instance,port';
$database = 'database';
$uid = 'username';
$pwd = 'password';
$cinfo = array(
    "Database" => $database,
    "UID" => $uid,
    "PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if ( $conn === false ) {
    echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
    exit;
}

# INSERT statement
$tsql = 
    "
    SET NOCOUNT ON;
    IF NOT EXISTS (SELECT 1 FROM SOMETABLE WHERE SOMEROW = 'VALUE' ) BEGIN
        INSERT INTO SOMETABLE (SOMEROW) VALUES ('VALUE')
        SELECT @@ROWCOUNT AS RC
        END
    ELSE BEGIN
        SELECT 0 AS RC
    END;
    ";
$stmt = sqlsrv_query($conn, $tsql);  
if ($stmt === false) {
    die( print_r( sqlsrv_errors(), true));
}

# Row count information
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    $rc = $row['RC'];
}
if ($rc == 0) {
    echo "This Row already Exists";
} else {
    echo "Success"; 
}

# End
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>

注意:

SQLSRV驱动程序支持sqlsrv_rows_affected()sqlsrv_num_rows()函数,可以使用某些功能。

答案 1 :(得分:1)

变量的布尔检查是为了成功执行查询,您应该检查它是否为布尔型并且为空。这是通过empty函数完成的。

if (empty($stmt)){
    var_dump(sqlsrv_errors());
    die();
}