dac
dac

Reputation: 821

php fatal error "Cannot access empty property" generated by foreach

I'm getting a "cannot access empty property error" on the line with the foreach in this code. print_r($captions) and print_r($updates) show the the expected values in each array.

$updates is an array of checked checkboxes where the user wants to update the captions for the photos. $captions is the array of all captions from the databases.

PHP processing shown here omits data sanitation for brevity. The codes gives the error with or without the sanitation routines.

if(isset($_POST['update']) && isset($_POST['caption'])){
    //check whether any photo captions are marked for update
    @$updates=$_POST['update'];
    @$captions=$_POST['caption'];           
    foreach($updates as $key->$photoid){
        $query="
        UPDATE photo 
        SET caption='".$captions[$key]."' 
        WHERE id='".$photoid."'
        LIMIT 1";
        $result=query($query);
        $message[]="Caption for photo # $photoid was successfully updated.";
    }
}

The form is generated by a loop that populates each row with a record (photoid, image, and caption) from the database and adds a checkbox to indicate whether user wants to update caption.

<tr>
    <td><? echo $thisphotoid; ?>.</td>
    <td><img src="<? echo '.SITE_URL.'images/banner/'.$thisfilename; ?>" /></td>
    <td><textarea name="caption[]" cols="40" rows="5"><? echo $thiscaption; ?></textarea></td>
    <td><input type="checkbox" name="update[]" value="<? echo $thisphotoid; ?>" /></td>
</tr>

Upvotes: 5

Views: 3674

Answers (2)

zerkms
zerkms

Reputation: 254985

Replace $key->$photoid to $key => photoid

Upvotes: 7

Halcyon
Halcyon

Reputation: 57693

I think you mean:

foreach($updates as $key => $photoid) {

Upvotes: 2

Related Questions