I use phpMyAdmin (php) my table doesn`t want to delete rows

  Kiến thức lập trình

I need to delete those rows from the Database (from the table) that were selected by me in the checkbox. That is, if the button is pressed, and the check box is pressed, it should be deleted.

<!--index.php-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
    <?php
    require_once 'DatabaseConnector.php';

    $databaseConnector = new DatabaseConnector("Products", "127.0.0.1");

    if ($databaseConnector->connect()) {
        $results = $databaseConnector->readAll("SELECT * FROM Items");

        if ($results) {
            echo '<form method="get" action="' . $_SERVER['PHP_SELF'] . '">';
            echo '<table>';
            echo '<tr>';
            echo '<th></th>';
            foreach (array_keys($results[0]) as $column) {
                if ($column != 'id') {
                    echo "<th>$column</th>";
                }
            }
            echo '</tr>';

            foreach ($results as $row) {
                $rowClass = (int) $row['id'] % 2 === 0 ? 'even' : 'odd';
                echo "<tr class='$rowClass'>";

                echo "<td><input type='checkbox' name='delete[]' value='{$row['id']}' data-id='{$row['id']}'></td>";
                foreach ($row as $column => $value) {
                    if ($column != 'id') {
                        echo "<td>$value</td>";
                    }
                }
                echo '</tr>';
            }
            echo '</table>';
            echo '<input type="submit" name="delete_submit" class="button_" value="Delete Selected">';
            echo '</form>';
        } else {
            echo "There are no positions available";
        }

        $databaseConnector->disconnect();
    } else {
        echo "Database connection error";
    }

    if (isset($_POST['delete_submit'])) {
        $selectedIDs = array();
        if (isset($_POST['delete'])) {
            foreach ($_POST['delete'] as $id) {
                $selectedIDs[] = (int) $id;
            }
        }

        if (!empty($selectedIDs)) {
            $databaseConnector = new DatabaseConnector("Products", "127.0.0.1");
            if ($databaseConnector->connect()) {
                $deletedRows = $databaseConnector->delete("Items", "id", $selectedIDs);
                $databaseConnector->disconnect();

                if ($deletedRows > 0) {
                    echo "<p>Successfully deleted $deletedRows rows.</p>";
                } else {
                    echo "<p>Could not delete any rows.</p>";
                }
            }
        }
    }
    ?>
    <div class="form-container">
        <form id="addForm" action="process.php" method="post">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required><br>

            <label for="country">Country:</label>
            <input type="text" id="country" name="country" required><br>

            <label for="producer">Producer:</label>
            <input type="text" id="producer" name="producer" maxlength="19" required><br>

            <label for="price">Price:</label>
            <input type="number" id="price" name="price" required><br>

            <button class="button_">ADD</button>
        </form>

        <form id="editForm" action="edit.php" method="get">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required><br>

            <label for="country">Country:</label>
            <input type="text" id="country" name="country" required><br>

            <label for="producer">Producer:</label>
            <input type="text" id="producer" name="producer" maxlength="19" required><br>

            <label for="price">Price:</label>
            <input type="number" id="price" name="price" required><br>
            <button class="button_" id="editButton" disabled>Change</button>
        </form>
    </div>
    <script>
    const checkboxes = document.querySelectorAll('input[type="checkbox"]');
    const deleteButton = document.querySelector('input[name="delete_submit"]');

    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', () => {
            const checkedCheckboxes = Array.from(checkboxes).filter(cb => cb.checked);
            deleteButton.disabled = checkedCheckboxes.length === 0;
        });
    });
</script>
</body>
</html>
<?php
class DatabaseConnector //DatabaseConnector.php
{
    //Записала змінні
    private $server; // localhost
    private $user; //root
    private $password; //його нема
    private $database; //Products
    private $port; //4000
    private $connection; // mysqli obj; для використання методів (read..) та властивостей (змінні вище)

    public function __construct(
        $databaseName,
        $serverAddress = 'localhost',
        $userName = 'root',
        $userPassword = '',
        $serverPort = 4000
    ) {
        $this->server = $serverAddress;
        $this->user = $userName;
        $this->password = $userPassword;
        $this->database = $databaseName;
        $this->port = $serverPort;
    }
    //connect - Відкриття підключення до БД з допомогою драйвера mysqli
    public function connect(): bool
    {
        $this->connection = new mysqli($this->server, $this->user, $this->password, $this->database, $this->port);
        return !$this->connection->connect_error;
        /* $hasConnectError = $this->connection->connect_error;
        $isConnected = !$hasConnectError;
        return $isConnected;
        */
    }
    //disconnect - Закриття цього підключення
    public function disconnect(): bool
    {
        if ($this->connection) { //якщо не порожня, завжди 1, перевірка на властивість connect_error
            $this->connection->close();
            return true;
        }
        return false;
    }
    // read - Отримання одного рядка результатів запиту
    public function read(string $query): ?array
    {
        $result = $this->connection->query($query);
        // отримання рядка результатів запиту в форматі ключ-значення масиву (асоціативного), де ключами є назви стовпців з бд
        if ($result) {
            return $result->fetch_assoc();
        }

        return null;
    }

    // readAll - Отримання всіх рядків результатів запиту
    public function readAll(string $query): ?array
    {
        $result = $this->connection->query($query);

        if ($result) {
            return $result->fetch_all(MYSQLI_ASSOC); //fetch_assoc для всіх рядків результату запиту
        }

        return null;
    }
    //insert - Додавання нового запису до таблиці
    public function insert(string $table, string $columns, string $values): bool
    {
        $query = "INSERT INTO $table ($columns) VALUES ($values)";
        return $this->connection->query($query);
    }
    //delete - Видалення запису з таблиці
    public function delete(string $table, string $column, array $values): bool
    {
        $placeholders = implode(', ', array_fill(0, count($values), '?'));
        $query = "DELETE FROM $table WHERE $column IN ($placeholders)";
    
        $stmt = $this->connection->prepare($query);
        if (!$stmt) {
            return false; 
        }

        $types = str_repeat('i', count($values)); 
        $stmt->bind_param($types, ...$values); 
    
        $stmt->execute();
    
        $affectedRows = $stmt->affected_rows;
    
        $stmt->close(); 
    
        return $affectedRows > 0;
    }
    
    public function change(string $table, array $data, string $condition): bool
    {
        // дата in setData
        $setData = [];
        foreach ($data as $column => $value) {
            $setData[] = "$column = '$value'";
        }
        //об'єднання
        $setData = implode(", ", $setData);

        $query = "UPDATE $table SET $setData WHERE $condition";
        return $this->connection->query($query);
    }

}
?>

What I can say for sure is that the problem is not in the Database, the table is working. I tried different codes. And it went through the GET request. But it did not change the table in any way. If you don’t choose anything, if there is such a code, then it gave me a message that there is nothing. I returned the code to the template state because I was already tired. Please help the student

New contributor

Анастасия Матакова is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT