views:

30

answers:

2

Can somebody explain me why the small piece of code doesn't work?

This is the error what is given:

Parse error: syntax error, unexpected '=' in /var/www/g35003/

$img_attributes= style='max-height: 100px; max-width: 100px' . 'alt="'.$product['product_name'].'"';
+2  A: 

You are messing the quotes, possible fix:

$img_attributes= "style='max-height: 100px; max-width: 100px'" . 'alt="'.$product['product_name'].'"';
jlru
+4  A: 

If this is PHP and you are trying to assign a string to a variable, there should be quotes arround the string.

Here, this specific portion of code is causing an error :

$img_attributes= style='max

There should be some kind of quote after the first = sign.


Something like this should work much better, for instance :

$img_attributes= 'style="max-height: 100px; max-width: 100px"'
     . ' alt="' . $product['product_name'] . '"';


As a sidenote : maybe some kind of escaping could be helpful, for the $product['product_name'] part ? to make sure it doesn't contain any HTML that would break your markup.
See htmlspecialchars, for instance.

For instance, if your product name is initialized this way :

$product['product_name'] = 'my mega "product"';

Then, using the portion of code I posted earlier will get you this output :

style="max-height: 100px; max-width: 100px" alt="my mega "product""

Which is not that nice...

Using htmlspecialchars, like this :

$img_attributes= 'style="max-height: 100px; max-width: 100px"'
     . ' alt="' . htmlspecialchars($product['product_name']) . '"';

The output would become :

style="max-height: 100px; max-width: 100px" alt="my mega "product""

Which, at least, is a portion of valid-HTML :-)

Pascal MARTIN
+1 for (sadly all-too-rare) correct usage of htmlspecialchars. I'm not sure `alt` is the best place for a product name though. Perhaps `title` would be more appropriate?
bobince
That would be better for SEO right?@ Pascal, thank you very much, good explanation.
Chris
@Chris : you're welcome :-) ;; @bobince : well, maybe (except for the fact that alt is required, and title is not -- so, if you only have one information, why not put it in alt ? but it's another question ^^ )
Pascal MARTIN