dimanche 26 mars 2017

MySQL/PHP - Checkbox array to delete multiple rows from database

i'm having some trouble passing Form checkbox array as mysql_query in order to delete multiple rows from table.

The structure is as follows:

HTML

<form action="usunogrod.php" method="POST" enctype="multipart/form-data">
    <?php
     $ogrodysql = "SELECT id_ogrodu, nazwa FROM ogrody";
     $result = mysqli_query($con, $ogrodysql);

     if (mysqli_num_rows($result) > 0) {

         while($row = mysqli_fetch_assoc($result)) {
              echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
         }
     } 
     else {
         echo "0 results";
     }
     ?>

    <br><br>
    <input type="submit" value="Usuń zaznaczony ogród."/>
</form>

PHP for processing form in usunogrod.php

<?php

$db_host = 'xxxxx';
$db_user = 'xxxxx';
$db_pwd = 'xxxxx';
$con = mysqli_connect($db_host, $db_user, $db_pwd);  
$database = 'xxxxx';

if (!mysqli_connect($db_host, $db_user, $db_pwd))
    die("Brak połączenia z bazą danych.");

if (!mysqli_select_db($con, $database))
    die("Nie można wybrać bazy danych.");

function sql_safe($s)
{
    if (get_magic_quotes_gpc())
        $s = stripslashes($s);
    global $con;
    return mysqli_real_escape_string($con, $s);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {   

    $ogrod_id = trim(sql_safe($_POST['removegarden[]']));

    if (isset($_POST['removegarden[]'])) {

                mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu='$ogrod_id'");

                $msg = 'Ogród został usunięty.';
    }
    elseif (isset($_GET['removegarden[]']))
        $msg = 'Nie udało się usunąć ogrodu.';
};
?>

MySQL table

ogrody

#      id_ogrodu      nazwa
       1              garden1

How may i process an array from checkboxes form so that i will be able to pass a query to delete all checked elements?

EDIT:

I have been able to make it work to a moment where it only deleted one of the checked positions, or the other time just got an error saying i can't pass and array to mysqli_query.




Aucun commentaire:

Enregistrer un commentaire