Skip to content
Advertisement

How to select different values in a column with the same ID and then delete them PHP SQL Server

I am new to the world of programming. I am in need of help in this sentence. what I want to do is select the 0.1,2 values from the CardIndex column and then be able to delete them. Rows must be removed as long as the condition is met. Or what would be the best way to do it.

CardIndex column must have the 3 values yes or yes to execute the delete. otherwise it will not be executed

enter image description here

$query = "SELECT * FROM CardData where UserIndex='$id' and CardIndex in (0,1,2) ";
$resultados = sqlsrv_query($conn,$query);

if($query1 = sqlsrv_fetch_array($resultados)){
        if($query1 == true){
        $cro =  "DELETE FROM CardData WHERE UserIndex='$id' and CardIndex in (0,1,2)";
        $query3 = sqlsrv_query($conn,$cro); 
        }

    echo 'funciona';
    }

    else{
     echo 'no funciona';    

}
?>

Advertisement

Answer

You want or, not and – otherwise you search for rows whose CardIndex has all three values at once, which, obviously, never happens:

DELETE FROM CardData 
WHERE 
    UserIndex = @UserIndex
    AND (CardIndex = 1 OR CardIndex = 2 OR CardIndex = 3)

This can be shortened with IN:

DELETE FROM CardData 
WHERE UserIndex = @UserIndex AND CardIndex IN (1, 2, 3)

Note that there is no point SELECTing the values before deleting them. You can just fire the DELETE directly: if no row matches the condition, no actual deletion will happen.

Finally: do not concatenate variables in the query string; this is inefficient and exposes your code to SQL injection. Instead, you should use parameterized queries (there are plenty of online resources that explain how to this right).


Edit

You want to delete all three records only if all three cardIndex values are available for the given userIndex. Assuming that there are no duplicate (userIndex, cardIndex), one method is an updateable CTE:

with cte as (
    select count(*) over() cnt
    from cardData
    where userIndex = @UserIndex and cardIndex in (1, 2, 3)
)
delete from cte where cnt = 3
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement