Can someone explain this code for me

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
denniss
Forum Newbie
Posts: 9
Joined: Wed Sep 09, 2009 9:10 am

Can someone explain this code for me

Post 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"); 
        }
    }
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Can someone explain this code for me

Post 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...
denniss
Forum Newbie
Posts: 9
Joined: Wed Sep 09, 2009 9:10 am

Re: Can someone explain this code for me

Post by denniss »

how do i know what the values are though?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Can someone explain this code for me

Post 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.
denniss
Forum Newbie
Posts: 9
Joined: Wed Sep 09, 2009 9:10 am

Re: Can someone explain this code for me

Post 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?
Post Reply