Crazy Horse
asked on
Can a html button have php attributes?
I am playing around with integrating a shopping cart into my own website and the way you create a product or buy button is like this:
This could get tedious if for every item you had to now do this. Can you make these dynamic with PHP? I would more than likely have all products in the database but for simplicity lets say I have:
How could I put that into the button code? I have tried various ways but none of them work so I am obviously doing something wrong.
<button
class="add-item"
data-item-id="2"
data-item-name="Bacon"
data-item-price="3.00"
data-item-weight="20"
data-item-url="http://mysite.com/products/bacon"
data-item-description="Some fresh bacon">
Buy bacon
</button>
This could get tedious if for every item you had to now do this. Can you make these dynamic with PHP? I would more than likely have all products in the database but for simplicity lets say I have:
<?php
$id = 2;
$item_name = "cheese";
$item_price = 3.00;
$item_weight = 20;
$item_description = "Chedder Cheese";
?>
How could I put that into the button code? I have tried various ways but none of them work so I am obviously doing something wrong.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Awesome, that worked! :)
ASKER
Sorry, Julian. Only got your response after accepting Marco's. Why would you recommend HEREDOC ?
Why would you recommend HEREDOC ?
PHP provides for three type of string output
Single quotes - everything inside the quotes is taken literally - there is no substitution of variable names. Single quotes must be escaped (\') double quotes can be used as is
Example
$name = "Julian";
$mystring = 'My name is "{$name}" and my neighbour\'s name is Fred';
Will output
My name is "{$name}" and my neighbour's name is Fred
Note the escape '\' is not in the outputDouble Quotes - any variables in the string will be replaced with their values, single quotes can be used as is double quotes must be escaped (\")
Example
$name = "Julian";
$mystring = "My name is \"{$name}\" and my neighbour's name is Fred";
Will output
My name is "Julian" and my neighbour's name is Fred
HEREDOC is the best of both worlds
You can include both single and double quotes in the string without escaping them and you can include variable names. For situations (like yours) where you want to output a block of text with double quote (around the class names) and variables in the string it makes for a much neater ordering of your code.
Example
$name = "Julian";
$mystring = <<< ARBITARYTAG
My name is "{$name}" and my neighbour's name is Fred
ARBITARYTAG;
You can read more about it here
ASKER
Helpful, thank you!
Open in new window