mardi 22 mars 2022

php checking if value matches in table and checking checkboxes if its true

so I made a program in php where i can assign screens to users i got it working by using a pivot table and getting the screenId and userId and insert those into the table when i check the checkbox

the only thing i want to be able to see is if the link between the screenId and userId already exist in the pivot table to check the checkbox

here is an image of the table I'm showing with checkboxes

https://i.stack.imgur.com/T6XYp.jpg

code to show the screens in a table:

    $sql = "SELECT * FROM screens";

    $screenStmt = mysqli_stmt_init($conn);
    
    if(!mysqli_stmt_prepare($screenStmt, $sql)){
        echo "SQL Error: Screens";
    }
    else{
        mysqli_stmt_execute($screenStmt);
        $screenResult = mysqli_stmt_get_result($screenStmt);
    }
    
        while($screenRow = mysqli_fetch_assoc($screenResult)){
            echo "<td>".$screenRow["screenId"]."</td>";
            echo "<td>".$screenRow["screenGuid"]."</td>";
            echo "<td>".$screenRow["screenName"]."</td>";
            echo "<td>".$screenRow["screenDesc"]."</td>";
            echo "<td><input type='checkbox' name='screenLink[]' value='".$screenRow["screenId"]."'></td>";
            echo "</tr>";
        }

code for saving the link into table when checkboxes are checked:

    if(isset($_POST['screenLink'])){
    if(!empty($_POST['screenLink'])){
        foreach($_POST['screenLink'] as $check){
            
            $sqlCheck = "SELECT userKey FROM linked WHERE screenKey=?";
            $userLink = "INSERT INTO linked (userKey, screenKey) VALUES (?,?);";


            $stmtCheck = mysqli_stmt_init($conn);

            if(!mysqli_stmt_prepare($stmtCheck, $sqlCheck)){
                echo "SQL Error";
            }
            else{
                mysqli_stmt_bind_param($stmtCheck, "s", $check);
                mysqli_stmt_execute($stmtCheck);
                $result = mysqli_stmt_get_result($stmtCheck);
                $result = mysqli_fetch_assoc($result);
            }
            if($result > 0){

            }
            else{
                $stmtInsert = mysqli_stmt_init($conn);
                if(!mysqli_stmt_prepare($stmtInsert, $userLink)){
                    echo "SQL error";
                }
                else{
                    mysqli_stmt_bind_param($stmtInsert, "ss", $userId, $check);
                    mysqli_stmt_execute($stmtInsert);
                    header("Location: ../users.php?change=Success");
                }
            }
        }
    }

}

this is probably not the best way but i got it kinda working how i need it and can change it later




Aucun commentaire:

Enregistrer un commentaire