如何使用 php 重复添加按钮


How to repeatedly add a button using php

>我正在尝试在数据库中的每条记录旁边添加一个"添加到愿望清单"按钮。如果我在循环中添加表单标签,它会出现一个错误,要求在操作中放置";"。如果我在循环外添加按钮,它只会显示一次。我做错了什么?

编辑:我得到的错误是Parse error: syntax error, unexpected ''>' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';' in /home/sta402/PHP_stuff/CarTemplate/Views/CarList.phtml on line 16,代码的下划线部分位于按钮表单中"动作"后面的引号之间。

    <?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') ?>

您得到的错误是因为您在单引号封装字符串中使用单引号 ( ' )。您可以通过多种方式解决此问题:

  1. 在字符串中使用双引号 ( " ):

    echo '<form method="POST" action="">
        blablabla
    </form>';
    
  2. 转义字符串中的单引号:

    echo '<form method="POST" action=''''>
        blablabla
    </form>';
    
  3. 使用heredoc语法:

    echo <<<HTML
    <form method="POST" action=''>
        blablabla
    </form>
    HTML;
    
  4. echo 语句后退出php

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

然后,您可以将正确的echo语句放在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
} ?>

阅读本文以正确了解如何使用字符串