单击按钮时,将行的内容添加到表中

时间:2017-12-29 16:01:41

标签: php html sql button mamp

我正在使用PHP,SQl和HTML编写Web应用程序。到目前为止,我可以使用关键字和查询来搜索我的Products表,该查询显示结果的HTML表。我还有一个按钮'收藏夹'对于HTML表的每一行。我希望能够在单击相应按钮时在我的收藏夹表中插入一行。

“我的产品”列的列(ID,product_name,品牌,国家/地区,image_url)

我的收藏夹表的列(id,product_name,品牌)

如果它更令人困惑,请暂时忽略ID。附上我的代码和截图:

Screenshot

<?php

if (isset($_POST['submit'])) 
{
    try 
    {   
        require "../config.php";
        require "../common.php";

        $connection = new PDO($dsn, $username, $password, $options);

        $sql = "SELECT product_name, brands, countries, image_url 
                FROM Products
                WHERE product_name LIKE :product_name OR brands LIKE :product_name";

        $product_name = $_POST['product_name'];


        if(empty(trim($product_name))) {
            //do nothing
        }
        else {
            $product_name = "%".$product_name."%";
            $statement = $connection->prepare($sql);
            $statement->bindParam(':product_name', $product_name, PDO::PARAM_STR);
            $statement->execute();

            $result = $statement->fetchAll();
        }
    }

    catch(PDOException $error) 
    {
       echo $sql . "<br>" . $error->getMessage();
    }
    }
?>
<?php require "templates/header.php"; ?>

    <h3>Find food product based on keywords</h3>

    <form method="post">
         <label for="product_name">Product Name</label>
         <input type="text" id="product_name" name="product_name">
         <input type="submit" name="submit" value="View Results">
    </form>

<a href="index.php">Back to home</a>

<?php  
if (isset($_POST['submit'])) 
{
     if ($result && $statement->rowCount() > 0) 
     { ?>
         <h2>Results</h2>

         <table>
             <thead>
                  <tr>
                       <th>Product Name</th>
                       <th>Brand</th>
                       <th>Countries</th>
                       <th>Image</th>
                 </tr>
             </thead>
        <tbody>
    <?php 
         foreach ($result as $row) 
         { ?>
         <tr>
            <td><?php echo escape($row["product_name"]); ?></td>
            <td><?php echo escape($row["brands"]); ?></td>
            <td><?php echo escape($row["countries"]); ?></td>
            <td><img src="<?php echo escape($row["image_url"]); ?>" alt=""/></td>
            <td><input type="submit" name="favorite" value="Favorite"></td>
        </tr>
    <?php 
    } ?>
    </tbody>
</table>
<?php 
} 
else 
{ ?>
    <blockquote>No results found for <?php echo escape($_POST['product_name']); ?></blockquote>
<?php
    } 
}?> 

<?php require "templates/footer.php"; ?>

0 个答案:

没有答案