Display 2nd upload

7 posts by 3 authors in: Forums > CMS Builder
Last Post: November 3, 2008   (RSS)

Hello,

I have a field (upload) which allows up to 4 uploads (in the same field)

Is there anyway I can display the 2nd upload (image) only?

For example:
<?php foreach ($tableRecord['photo'] as $upload): ?>
img src="<?php echo $upload['urlPath'] ?>" />
<?php break; ?>
<?php endforeach ?>


That above code, using the BREAK will display the first upload, and then stop i.e. display upload 1.

Can I make it display upload 2... maybe either through an ONLY DISPLAY 2 (instead of a foreach), or a foreach, that STARTS at 2 and then stop with BREAK.

Hope that makes sense

Cheers
Rob

PS I know I can do through by separating uploads into separate fields (i.e. photo_1, photo_2, photo_3, photo_4) as then I just set the upload to display, but I won't want to have to separate the uploads...!

Re: [rjbathgate] Display 2nd upload

By Dave - November 2, 2008

Hi Rob,

You can, it takes a little bit of more advanced PHP. Here's the details:

The value of $tableRecord['photo'] is actually a PHP array, so you can refer to an element in the array by number like this: $tableRecord['photo'][0]. Note that arrays start counting at 0, so the second image would be accessed with [1].

Try this:

<?php if (@$tableRecord['photo'][1]): ?>
<img src="<?php echo $tableRecord['photo'][1]['urlPath'] ?>" />
<?php endif ?>


Or if it makes it more readable you can assign the 2nd upload to a variable first:

<?php $upload = @$tableRecord['photo'][1]; ?>
<?php if (@$upload): ?>
<img src="<?php echo $upload['urlPath'] ?>" />
<?php endif ?>


Hope that helps!
Dave Edis - Senior Developer
interactivetools.com

Re: [Dave] Display 2nd upload

Superb, thanks Dave...

Simply
<img src="<?php echo $tableRecord['photo'][2]['urlPath'] ?>" />

works a treat.

Cheers
Rob

Re: [rjbathgate] Display 2nd upload

By Dave - November 3, 2008

Just make sure you always have an image uploaded though or you'll get an 'undefined variable' error. That's what the if tests for.

Glad it's working!
Dave Edis - Senior Developer
interactivetools.com

Re: [Dave] Display 2nd upload

Good point, cheers.

Out of interest, what does the @ in the IF statement do?

<?php if (@$tableRecord['photo'][1]): ?>

I can't see how that IF statement checks that it is an image in the record... or is that the @?

Cheers Dave!

Re: [Perchpole] Display 2nd upload

By Dave - November 3, 2008

You are. :) Otherwise you'll get an error if the variable isn't defined such as "Undefined Index 'photo'" or "undefined Index '1'".

You can prevent something from giving errors usually by putting a @ in front of it.

The "proper" way is to check if a key exists with the array_key_exists() function, but it makes for much more verbose, less readable code:

<?php if (array_key_exists('photo', $tableRecord) and array_key_exists('1', $tableRecord['photo'])): ?>

So I prefer the previous way.
Dave Edis - Senior Developer
interactivetools.com