Phantomazi
Phantomazi

Reputation: 408

How to repeatedly add a button using php

I am trying to add an "Add to wishlist" button next to every record from a database. If I add the form tags inside the loop it comes up with an error asking to place ";" inside action. If I add the button outside the loop it is shown only once. What am I doing wrong ?

EDIT: the error I get is Parse error: syntax error, unexpected ''>' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';' in /home/sta402/PHP_stuff/CarTemplate/Views/CarList.phtml on line 16 and the underlined part of the code is between the quotation marks after "action" in the form for the button.

    <?php require('template/header.phtml') ?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

    <br>
    <table class="table table-hover">
       <thead>
        <tr><th>Type</th><th>Make</th><th>Model</th><th>Colour</th><th>Price</th><th>Year</th><th>Picture</th></tr>


       </thead>   
    <tbody> 
        <?php foreach ($view->carDataSet as $carData) {
              echo '<tr> <td>' . $carData->getType() . '</td> <td>' . $carData->getMake() . '</td> <td>' . $carData->getModel() . '</td> <td>' . $carData->getColour() .'</td> <td>' . $carData->getPrice() . '</td> <td>' . $carData->getYearOfRegistration() . '</td><td>' . $carData->getPicture() . '</td></tr>';


        } ?>
        <form method="POST" action=''>
            <input type="submit" name="button1"  value="My Button">
        </form>
    </tbody>
  </table>  
</form>

<?php require('template/footer.phtml') ?>

Upvotes: 0

Views: 57

Answers (1)

Jonan
Jonan

Reputation: 2536

The error you're getting is because you're using single quotes (') within a single quote encapsulated string. You can fix this in multiple ways:

  1. use double quotes (") inside your string:

    echo '<form method="POST" action="">
        blablabla
    </form>';
    
  2. escape the single quotes in your string:

    echo '<form method="POST" action=\'\'>
        blablabla
    </form>';
    
  3. use the heredoc syntax:

    echo <<<HTML
    <form method="POST" action=''>
        blablabla
    </form>
    HTML;
    
  4. exit out of php after the echo statement:

    echo ?>
    <form method="POST" action=''>
        blablabla
    </form>
    <?php;
    

You can then put the correct echo statement in the foreach loop:

<?php foreach ($view->carDataSet as $carData) {
    echo '<tr> <td>' . $carData->getType() . '</td> <td>' . $carData->getMake() . '</td> <td>' . $carData->getModel() . '</td> <td>' . $carData->getColour() .'</td> <td>' . $carData->getPrice() . '</td> <td>' . $carData->getYearOfRegistration() . '</td><td>' . $carData->getPicture() . '</td></tr>';
    //one of the four above options for the button echo statement
} ?>

Read this to correctly learn how to use strings

Upvotes: 2

Related Questions