Page 1 of 1

Can someone explain this code for me

Posted: Sat Sep 12, 2009 4:14 am
by denniss
This is a code taken from Head First PHP&MySQL
I am confused about the array within the while loop. Specifically, I want to know how it works, because i don't see anything action on the todelete[]

Code: Select all

<?php
    $dbc = mysqli_connect('localhost','root','','storeproj');
    $result = mysqli_query($dbc, "SELECT * FROM email_list");
    if(!isset($_POST['submit']))
    {
        while($row = mysqli_fetch_array($result))
        {
            echo '<input type = "checkbox" value ="' . $row['id'] . '" name = "todelete[]"/>';
            echo $row['first_name'] . " ";
            echo $row['last_name'] . " ";
            echo $row['email'];
            echo '</br>';
        }
        echo '<input type ="submit" value="submit" name="submit">'; 
    }
    else
    {
        foreach($_POST['todelete'] as $person)
        {
            mysqli_query($dbc , "DELETE FROM email_list WHERE id = $person"); 
        }
    }

Re: Can someone explain this code for me

Posted: Sat Sep 12, 2009 5:55 am
by jackpf
If you postfix an input's name with [], PHP will put all the values into an array for you...which is why $_POST['todelete'] is in that foreach loop down there...

Re: Can someone explain this code for me

Posted: Sat Sep 12, 2009 6:46 pm
by denniss
how do i know what the values are though?

Re: Can someone explain this code for me

Posted: Sat Sep 12, 2009 6:49 pm
by requinix

Code: Select all

print_r($_POST["todelete"]);
Beyond like idea, you don't know. That's why it's called "user input": the user decides what the values are, not you.

Re: Can someone explain this code for me

Posted: Sat Sep 12, 2009 7:22 pm
by denniss
I got something like

Array( [0] => 7[1] => 3)
Array( [0] => 7[1] => 3)

And i am still clueless on the inner working of this array.

I can see that the MySQL query is setting whatever inside the array to the column id.

Code: Select all

mysqli_query($dbc, "DELETE FROM email_list WHERE id = $person");
tho it appears that by printing it out, it is actually a 2 dimensional array?