簡體   English   中英

如何過濾屬於特定類別的帖子 [產品]

[英]How to filter posts [products] that belong to a specific category

我需要按不同類別過濾我網站上的產品。 例如,如果您選擇“DRINKS”類別,它將向我顯示屬於該類別的產品。

為了更好地解釋自己。

我需要按類別過濾我網站的出版物 [產品],例如,在選擇一個類別時說“飲料”,只顯示屬於該類別的出版物 [產品]。

數據庫 [圖像]

類別

數據庫類別圖像

帖子 [產品]

數據庫帖子 [產品] 圖片

例如,選擇“飲料”類別時,僅顯示標有此類別的產品,在本例中為“產品”

這是我目前的代碼:

代碼顯示categories.php [index]中的產品

<?php include($_SERVER['DOCUMENT_ROOT'].'/app/controllers/products.php');
include('app/includes/categories.php');
$categorias = selectAll('categories');
$capitulos = selectAll('products');

<div class="productos-list">
    
<?php foreach ($productos as $key => $producto): ?>           
<ul>
    <a href="/ver/productos.php?id=<?php echo $producto['id']?>">
    <li class="producto-name"><?php echo $producto['name']?></li>
    </a>
</ul>
<?php endforeach; ?> 
    </div>

產品.PHP

<?php 

include($_SERVER['DOCUMENT_ROOT'].'/app/database/db.php');
include($_SERVER['DOCUMENT_ROOT'].'/app/helpers/validatePost.php');

$table = 'posts';
$categorias = selectAll('categorias');

$errors = array();
$id = '';
$title = '';
$productos = '';
$categoria_id = '';

$productos = selectAll($table);


if (isset($_POST['add-post'])) {
    $_POST['topic_id']=serialize($_POST['topic_id']);
    $errors = validatePost($_POST);
    
    if (!empty($_FILES['image']['name'])) {
        $image_name = time() . '_' . $_FILES['image']['name'];
        $destination = "../../images/" . $image_name;
        
        $result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);
        
        if ($result){
            $_POST['image'] = $image_name;
        } else {
            array_push($errors, "¡Algo fallo al subir la imagen!");
        }
        
        
    } else {
      array_push($errors, "¡Necesitas subir una imagen!");
    }
    
    if (count($errors) === 0){
        unset($_POST['add-post']);
        $post_id = create($table, $_POST);
        $_SESSION['message'] = '¡Post creado correctamente!';
        $_SESSION['type'] = 'success';
        header('location: ../../admin/posts/index.php');
        exit();
    } else {
        $id = $_POST['id'];
        $title = $_POST['title'];
        $topic = $_POST['categoria_id'];
    }
}

if (isset($_GET['id'])){
    $id = $_GET['id'];
    $post = selectOne($table, ['id' => $id]);
}

if (isset($_GET['del_id'])){
    $id = $_GET['del_id'];    
    $count = delete($table, $id);
    $_SESSION['message'] = '¡Post eliminado correctamente!';
    $_SESSION['type'] = 'success';
    header('location: ../../admin/posts/index.php');
    exit();
}

if (isset($_POST['update-post'])){
    $errors = validateEdit($_POST); 
    
    if (count($errors) === 0){
        $id = $_POST['id'];
        unset($_POST['update-post'], $_POST['id']);
        $post_id = update($table, $id, $_POST);
        $_SESSION['message'] = '¡Post actualizado correctamente!';
        $_SESSION['type'] = 'success';
        header('location: ../../admin/topics/index.php');
        exit();        
    } else {
        $id = $_POST['id'];
        $title = $_POST['title'];
        $topic = $_POST['categoria_id'];
}
} 
?>     

類別.PHP

<?php 

include($_SERVER['DOCUMENT_ROOT'].'/app/database/db.php');
include($_SERVER['DOCUMENT_ROOT'].'/app/helpers/validateCategoria.php');

$table = 'categorias';

$errors = array();
$id = '';
$name = '';
$title = '';
$productos = '';
$categoria_id = '';

$categorias = selectAll($table);


if (isset($_POST['add-post'])) {
    $errors = validateCategoria($_POST);
    
    if (count($errors) === 0){
        unset($_POST['add-post']);
        $post_id = create($table, $_POST);
        $_SESSION['message'] = '¡Categoria creada correctamente!';
        $_SESSION['type'] = 'success';
        header('location: ../../admin/categorias/index.php');
        exit();
    } else {
        $id = $_POST['id'];
        $name = $_POST['name'];
    }
}

if (isset($_GET['id'])){
    $id = $_GET['id'];
    $post = selectOne($table, ['id' => $id]);
}

if (isset($_GET['del_id'])){
    $id = $_GET['del_id'];    
    $count = delete($table, $id);
    $_SESSION['message'] = '¡Categoria eliminada correctamente!';
    $_SESSION['type'] = 'success';
    header('location: ../../admin/categorias/index.php');
    exit();
}

if (isset($_POST['update-post'])){
    $errors = validateEdit($_POST); 
    
    if (count($errors) === 0){
        $id = $_POST['id'];
        unset($_POST['update-post'], $_POST['id']);
        $post_id = update($table, $id, $_POST);
        $_SESSION['message'] = '¡Categoria actualizada correctamente!';
        $_SESSION['type'] = 'success';
        header('location: ../../admin/categorias/index.php');
        exit();        
    } else {
        $id = $_POST['id'];
        $name = $_POST['name'];

}
} 
?>  

                             

數據庫文件

<?php

session_start();
require('connect.php');

function dd($value)
{
    echo "<pre>", print_r($value, true), "</pre>";
    die();
}


function executeQuery($sql, $data)
{
    global $conn;
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $stmt = $conn->prepare($sql);
    $values = array_values($data);
    $types = str_repeat('s', count($values));
    $stmt->bind_param($types, ...$values);
    $stmt->execute();
    return $stmt;
}


function selectAll($table, $conditions = [])
{
    global $conn;
    $sql = "SELECT * FROM $table";
    if (empty($conditions)) {
        $sql = $sql . " ORDER BY id DESC";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        $records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        return $records;    
    } else {
        // $sql = "SELECT * FROM $table WHERE username='ElVictox' AND admin=1";
        
        $i = 0;
        foreach ($conditions as $key => $value) {
            if ($i === 0){
                $sql = $sql . " WHERE $key=?";
                
            } else {
                $sql = $sql . " AND $key=?"; 
            }
            $i++;
        }
        
        $stmt = $conn->prepare($sql);
        $values = array_values($conditions);
        $types = str_repeat('s', count($values));
        $stmt->bind_param($types, $values);
        $stmt->execute();
        $records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        return $records;
    }
}



function selectOne($table, $conditions)
{
    global $conn;
    $sql = "SELECT * FROM $table ";

        $i = 0;
                foreach ($conditions as $key => $value) {
            if ($i === 0){
                $sql = $sql . " WHERE $key=?";
                
            } else {
               $sql = $sql . " AND $key=?"; 
            }
            $i++;
        }
        $sql = $sql . " LIMIT 1";
        $stmt = executeQuery($sql, $conditions);
        $records = $stmt->get_result()->fetch_assoc();
        return $records;
    }

function create($table, $data)
{
    global $conn;
    $sql = "INSERT INTO $table SET ";
      
    $i = 0;
    foreach ($data as $key => $value) {
            if ($i === 0){
                $sql = $sql . " $key=?";
                
            } else {
                $sql = $sql . ", $key=?"; 
            }
            $i++;
        }
    $stmt = executeQuery($sql, $data);
    $id = $stmt->insert_id;
    return $id;
    
}

function update($table, $id, $data)
{
    global $conn;
    $sql = "UPDATE $table SET ";
      
    $i = 0;
    foreach ($data as $key => $value) {
            if ($i === 0){
                $sql = $sql . " $key=?";
                
            } else {
                $sql = $sql . ", $key=?"; 
            }
            $i++;
        }
    
    $sql = $sql . " WHERE id=?";
    $data['id'] = $id;
    $stmt = executeQuery($sql, $data);
    return $stmt->affected_rows;
    
}


function delete($table, $id)
{
    global $conn;
    $sql = "DELETE FROM $table WHERE id=?";
      
    $stmt = executeQuery($sql, ['id' => $id]);
    return $stmt->affected_rows;
    
}

編輯:我沒有錯誤顯示類別中的產品,我想要做的是在他們的類別中專門顯示它們。 例如,我選擇“飲料”類別,我希望它只顯示飲料產品。

目前我碰巧所有產品都顯示在所有類別中,例如在“飲料”類別中顯示所有產品,包括那些不屬於它的產品。

您需要使用連接使用。 mysqli 的例子

文件1.php

<?php
        $db = new mysqli(ip,username,password,db);
        $query = $db->prepare("SELECT * FROM products INNER JOIN categorias ON product.categoria_id = categorias.id WHERE categorias.name = ?");
        $query->bind_param("s",$categoria);
        $query->execute();
        $coll = $query->get_result();
        $query->store_result();
        $elements = [];
        while ($row = $coll->fetch_assoc()){
           $elements[] = $row; // products where categorias.name = $categoria
        }
?>

索引.php

  <?php 
include "file1.php";

foreach ($elements as $element){
echo $element["name"];
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM