首页 > 解决方案 > 调节从表中选择

问题描述

我有这个练习,我只需要列出当前不在购物车中的虚拟产品表中的产品。

我在创建购物车数组时发现了大问题(我已经通过_SESSION不确定是否可行)并创建条件语句以仅选择未在提交后推送的购物车项目。我不知道我是否清楚,因为实际$cart是一个数组数组,我想创建一个条件语句$sql= "SELECT * FROM products";来检查是否是SELECT * FROM PRODUCTSelseSELECT * FROM products WHERE 'id' NOT IN $cart或类似的东西。

索引.php

<?php
require_once('common.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Index</title>
</head>
<body>
<?php while($product=$products->fetch(PDO::FETCH_ASSOC)):?>
<form method='post' action=''>
        <input type='hidden' name='id' value="<?=$product['id']?>">
        <table class='product'>
            <thead>
                <tr>
                    <th class='image' rowspan='3'><img src='img1.jpg' /></th>
                    <th class='title'><?=$product['title']?></th>
                    <th class='buy' rowspan='3'><button type='submit' name='add'>Add</button></th>
                </tr>
                <tr>
                    <td class='description'><?=$product['description']?></td>
                </tr>
                <tr>
                    <td class='price'><?=$product['price']?></td>
                </tr>
            </thead>
        </table>
</form>
<?php endwhile;?>
<a href="./cart.php">
        <button >Got to cart</button>
</a>
</body>
</html>

常见的.php

<?php
require_once('config.php');
//Connection display all products
try {
  $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
  $sql= "SELECT * FROM `products`";
  $products = $con->prepare($sql);
  $products->execute();
}
catch(PDOException $exception){
  echo "Connection error: " . $exception->getMessage();
}
if(isset($_POST['id']))
{ 
  session_start();
  $cart = array($_POST['id']);
  $_SESSION['cart'] =count($_SESSION['cart'])>0?$_SESSION['cart']:array();
  array_push($_SESSION['cart'],$cart);
  $cart = $_SESSION['cart'];
  print_r($cart);
};

标签: phpmysqlconditional-statementscrudcart

解决方案


推荐阅读