Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

foreach

php

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>
like image 278
dac Avatar asked Apr 24 '11 22:04

dac


2 Answers

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

like image 130
zerkms Avatar answered Nov 15 '22 14:11

zerkms


I think you mean:

foreach($updates as $key => $photoid) {
like image 45
Halcyon Avatar answered Nov 15 '22 14:11

Halcyon