admin.html

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Administração de Produtos</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin: 0;
            padding: 0;
        }
        header {
            width: 100%;
            background-color: #f8f8f8;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        header h1 {
            margin: 0;
            font-size: 24px;
        }
        .form-container, .products-container, .categories-container {
            width: 100%;
            max-width: 800px;
            margin: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            background-color: #fff;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .form-group button {
            background-color: #add8e6;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .form-group button:hover {
            background-color: #87ceeb;
        }
        .product-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #ddd;
        }
        .product-item button {
            background-color: #ff6961;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .product-item button:hover {
            background-color: #ff5c5c;
        }
        .product-item .edit-button {
            background-color: #f0ad4e;
        }
        .product-item .edit-button:hover {
            background-color: #ec971f;
        }
        .product-item img {
            max-width: 50px;
            max-height: 50px;
        }
    </style>
</head>
<body>
    <header>
        <h1>Administração de Produtos</h1>
    </header>
    <div class="form-container">
        <div class="form-group">
            <label for="product-name">Nome do Produto</label>
            <input type="text" id="product-name" required>
        </div>
        <div class="form-group">
            <label for="product-image">Imagem do Produto</label>
            <input type="file" id="product-image" accept="image/*">
            <img id="product-image-preview" style="max-width: 100%; display: none; margin-top: 10px;">
        </div>
        <div class="form-group">
            <label for="product-link">Link do Produto</label>
            <input type="url" id="product-link" required>
        </div>
        <div class="form-group">
            <label for="product-category">Categoria do Produto</label>
            <select id="product-category" required>
                <!-- Options will be dynamically added -->
            </select>
        </div>
        <div class="form-group">
            <button id="add-button" onclick="addProduct()">Adicionar Produto</button>
            <button id="update-button" onclick="updateProduct()" style="display: none;">Atualizar Produto</button>
        </div>
    </div>
    <div class="categories-container">
        <h2>Categorias</h2>
        <button onclick="addCategory()">Adicionar Categoria</button>
        <ul id="category-list"></ul>
    </div>
    <div class="products-container">
        <h2>Produtos</h2>
        <table id="product-table">
            <thead>
                <tr>
                    <th>Nome</th>
                    <th>Imagem</th>
                    <th>Link</th>
                    <th>Categoria</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody id="product-table-body">
                <!-- Product rows will be dynamically added -->
            </tbody>
        </table>
    </div>
    <script src="admin.js"></script>
</body>
</html>

admin.js

let categories = [];
let products = [];

function addCategory() {
    const categoryName = prompt('Digite o nome da nova categoria:');
    if (categoryName) {
        fetch('admin.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'addCategory',
                name: categoryName
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    loadCategories();
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    }
}

function addProduct() {
    const productName = document.getElementById('product-name').value;
    const productImage = document.getElementById('product-image').files[0];
    const productLink = document.getElementById('product-link').value;
    const productCategory = document.getElementById('product-category').value;

    if (productName && productLink && productCategory) {
        const formData = new FormData();
        formData.append('action', 'addProduct');
        formData.append('name', productName);
        if (productImage) {
            formData.append('image', productImage);
        }
        formData.append('link', productLink);
        formData.append('category', productCategory);

        fetch('admin.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    clearForm();
                    loadProducts();
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    } else {
        alert('Por favor, preencha todos os campos obrigatórios.');
    }
}

function clearForm() {
    document.getElementById('product-name').value = '';
    document.getElementById('product-image').value = '';
    document.getElementById('product-image-preview').src = '';
    document.getElementById('product-link').value = '';
    document.getElementById('product-category').selectedIndex = 0;
}

function loadCategories() {
    fetch('admin.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ action: 'getCategories' })
    })
    .then(response => response.json())
    .then(data => {
        categories = data;
        updateCategoryOptions();
    })
    .catch(error => console.error('Erro:', error));
}

function updateCategoryOptions() {
    const categorySelect = document.getElementById('product-category');
    categorySelect.innerHTML = '';
    categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category.name;
        option.textContent = category.name;
        categorySelect.appendChild(option);
    });
}

function loadProducts() {
    fetch('admin.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ action: 'getProducts' })
    })
    .then(response => response.json())
    .then(data => {
        products = data;
        displayProducts();
    })
    .catch(error => console.error('Erro:', error));
}

function displayProducts() {
    const productTableBody = document.getElementById('product-table-body');
    productTableBody.innerHTML = '';
    products.forEach(product => {
        const row = document.createElement('tr');
        row.innerHTML = 
            <td>${product.name}</td>
            <td><img src="${product.image}" alt="${product.name}" class="product-image"></td>
            <td><a href="${product.link}" target="_blank">${product.link}</a></td>
            <td>${product.category}</td>
            <td>
                <button class="edit-button" onclick="editProduct(${product.id})">Editar</button>
                <button class="delete-button" onclick="deleteProduct(${product.id})">Excluir</button>
            </td>
        ;
        productTableBody.appendChild(row);
    });
}

function editProduct(id) {
    const product = products.find(p => p.id === id);
    if (product) {
        document.getElementById('product-name').value = product.name;
        document.getElementById('product-link').value = product.link;
        document.getElementById('product-category').value = product.category;
        document.getElementById('add-button').style.display = 'none';
        document.getElementById('update-button').style.display = 'inline-block';
    }
}

function updateProduct() {
    const productName = document.getElementById('product-name').value;
    const productImage = document.getElementById('product-image').files[0];
    const productLink = document.getElementById('product-link').value;
    const productCategory = document.getElementById('product-category').value;

    if (productName && productLink && productCategory) {
        const formData = new FormData();
        formData.append('action', 'updateProduct');
        formData.append('name', productName);
        if (productImage) {
            formData.append('image', productImage);
        }
        formData.append('link', productLink);
        formData.append('category', productCategory);

        fetch('admin.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    clearForm();
                    document.getElementById('add-button').style.display = 'inline-block';
                    document.getElementById('update-button').style.display = 'none';
                    loadProducts();
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    } else {
        alert('Por favor, preencha todos os campos obrigatórios.');
    }
}

function deleteProduct(id) {
    if (confirm('Tem certeza que deseja excluir este produto?')) {
        fetch('admin.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'deleteProduct',
                id: id
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    loadProducts();
                }
            }
        })
        .catch(error => console.error('Erro:', error));
    }
}

window.onload = function() {
    loadCategories();
    loadProducts();
    const productImageInput = document.getElementById('product-image');
    const productImagePreview = document.getElementById('product-image-preview');
    
    productImageInput.addEventListener('change', function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function() {
                productImagePreview.src = reader.result;
                productImagePreview.style.display = 'block';
            }
            reader.readAsDataURL(file);
        } else {
            productImagePreview.src = '';
            productImagePreview.style.display = 'none';
        }
    });
};

admin.php

<?php
$servername = "127.0.0.1:3306";
$username = "u228248172_negociolegal_u";
$password = "Polara13#";
$dbname = "u228248172_negociolegal_b";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Function to create tables if they do not exist
function createTables($conn) {
    $createCategoriesTable = "CREATE TABLE IF NOT EXISTS categories (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL
    )";

    $createProductsTable = "CREATE TABLE IF NOT EXISTS products (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        image TEXT NOT NULL,
        link VARCHAR(255) NOT NULL,
        category VARCHAR(255) NOT NULL
    )";

    if ($conn->query($createCategoriesTable) === TRUE) {
        //echo "Categories table created or already exists.";
    } else {
        echo "Error creating categories table: " . $conn->error;
    }

    if ($conn->query($createProductsTable) === TRUE) {
        //echo "Products table created or already exists.";
    } else {
        echo "Error creating products table: " . $conn->error;
    }
}

// Call the function to create tables
createTables($conn);

// Process API requests
$input = json_decode(file_get_contents('php://input'), true);

if (isset($input['action'])) {
    $action = $input['action'];

    switch ($action) {
        case 'addProduct':
            $name = $input['name'];
            $image = $input['image'];
            $link = $input['link'];
            $category = $input['category'];

            $stmt = $conn->prepare("INSERT INTO products (name, image, link, category) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $name, $image, $link, $category);

            if ($stmt->execute()) {
                echo json_encode(["message" => "Produto adicionado com sucesso!", "success" => true]);
            } else {
                echo json_encode(["message" => "Erro ao adicionar produto: " . $stmt->error, "success" => false]);
            }

            $stmt->close();
            break;

        case 'addCategory':
            $name = $input['name'];

            $stmt = $conn->prepare("INSERT INTO categories (name) VALUES (?)");
            $stmt->bind_param("s", $name);

            if ($stmt->execute()) {
                echo json_encode(["message" => "Categoria adicionada com sucesso!", "success" => true]);
            } else {
                echo json_encode(["message" => "Erro ao adicionar categoria: " . $stmt->error, "success" => false]);
            }

            $stmt->close();
            break;

        case 'getProducts':
            $result = $conn->query("SELECT * FROM products");

            $products = [];
            while ($row = $result->fetch_assoc()) {
                $products[] = $row;
            }

            echo json_encode($products);
            break;

        case 'getCategories':
            $result = $conn->query("SELECT * FROM categories");

            $categories = [];
            while ($row = $result->fetch_assoc()) {
                $categories[] = $row;
            }

            echo json_encode($categories);
            break;

        case 'updateProduct':
            $id = $input['id'];
            $name = $input['name'];
            $image = $input['image'];
            $link = $input['link'];
            $category = $input['category'];

            $stmt = $conn->prepare("UPDATE products SET name=?, image=?, link=?, category=? WHERE id=?");
            $stmt->bind_param("ssssi", $name, $image, $link, $category, $id);

            if ($stmt->execute()) {
                echo json_encode(["message" => "Produto atualizado com sucesso!", "success" => true]);
            } else {
                echo json_encode(["message" => "Erro ao atualizar produto: " . $stmt->error, "success" => false]);
            }

            $stmt->close();
            break;

        case 'deleteProduct':
            $id = $input['id'];

            $stmt = $conn->prepare("DELETE FROM products WHERE id=?");
            $stmt->bind_param("i", $id);

            if ($stmt->execute()) {
                echo json_encode(["message" => "Produto excluído com sucesso!", "success" => true]);
            } else {
                echo json_encode(["message" => "Erro ao excluir produto: " . $stmt->error, "success" => false]);
            }

            $stmt->close();
            break;

        default:
            echo json_encode(["message" => "Ação inválida."]);
            break;
    }
} else {
    echo json_encode(["message" => "Nenhuma ação fornecida."]);
}

$conn->close();
?>

script.js

const productsPerPage = 20;
let currentPage = 1;
let products = [];
let categories = [];

function loadProductsFromStorage() {
    const storedProducts = localStorage.getItem('products');
    if (storedProducts) {
        products = JSON.parse(storedProducts);
    }
}

function loadCategoriesFromStorage() {
    const storedCategories = localStorage.getItem('categories');
    if (storedCategories) {
        categories = JSON.parse(storedCategories);
    }
}

function loadProducts(page) {
    loadProductsFromStorage();
    const start = (page - 1) * productsPerPage;
    const end = start + productsPerPage;
    const productsToShow = products.slice(start, end);

    const productGrid = document.getElementById("product-grid");
    productGrid.innerHTML = "";

    productsToShow.forEach(product => {
        const productElement = document.createElement("div");
        productElement.className = "product";
        productElement.innerHTML = 
            <img src="${product.image}" alt="${product.name}">
            <h3>${product.name}</h3>
            <button onclick="window.location.href='${product.link}'">Ver Produto</button>
        ;
        productGrid.appendChild(productElement);
    });

    loadPagination(page);
}

function loadProductsByCategory(category) {
    const filteredProducts = products.filter(product => product.category === category);
    const productGrid = document.getElementById("product-grid");
    productGrid.innerHTML = "";

    filteredProducts.forEach(product => {
        const productElement = document.createElement("div");
        productElement.className = "product";
        productElement.innerHTML = 
            <img src="${product.image}" alt="${product.name}">
            <h3>${product.name}</h3>
            <button onclick="window.location.href='${product.link}'">Ver Produto</button>
        ;
        productGrid.appendChild(productElement);
    });
}

function loadPagination(page) {
    const pagination = document.getElementById("pagination");
    pagination.innerHTML = "";

    const totalPages = Math.ceil(products.length / productsPerPage);

    if (page > 1) {
        const prevButton = document.createElement("button");
        prevButton.textContent = "Anterior";
        prevButton.onclick = () => loadProducts(page - 1);
        pagination.appendChild(prevButton);
    }

    if (page < totalPages) {
        const nextButton = document.createElement("button");
        nextButton.textContent = "Próxima";
        nextButton.onclick = () => loadProducts(page + 1);
        pagination.appendChild(nextButton);
    }
}

function loadCategoryList() {
    const categoryList = document.getElementById("category-list");
    categoryList.innerHTML = '';

    categories.forEach(category => {
        const categoryItem = document.createElement('li');
        categoryItem.innerHTML = 
            <a href="#" onclick="loadProductsByCategory('${category}')">${category}</a>
        ;
        categoryList.appendChild(categoryItem);
    });
}

// Inicializa a página com os produtos e categorias
loadProducts(currentPage);
loadCategoriesFromStorage();
loadCategoryList();

index.html

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Minha Loja</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f8f8f8;
        }
        header {
            width: 100%;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        header h1 {
            margin: 0;
        }
        #product-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
            padding: 20px;
            width: 100%;
            max-width: 1200px;
        }
        .product {
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        .product img {
            max-width: 100%;
            height: auto;
        }
        .product h3 {
            margin: 10px 0;
        }
        .product button {
            background-color: #add8e6;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .product button:hover {
            background-color: #87ceeb;
        }
        #pagination {
            margin: 20px;
        }
        #pagination button {
            background-color: #add8e6;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            margin: 0 5px;
        }
        #pagination button:hover {
            background-color: #87ceeb;
        }
        #category-list {
            list-style-type: none;
            padding: 0;
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }
        #category-list li {
            margin: 0 10px;
        }
        #category-list a {
            text-decoration: none;
            color: #333;
            font-weight: bold;
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }
        #category-list a:hover {
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <header>
        <h1>Minha Loja</h1>
    </header>
    <ul id="category-list"></ul>
    <div id="product-grid"></div>
    <div id="pagination"></div>
    <script>
        const productsPerPage = 20;
        let currentPage = 1;
        let products = [];
        let categories = [];

        function loadProducts(page) {
            const url = admin.php;
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ action: 'getProducts' })
            })
            .then(response => response.json())
            .then(data => {
                products = data;
                displayProducts(page);
            })
            .catch(error => console.error('Erro:', error));
        }

        function displayProducts(page) {
            const start = (page - 1) * productsPerPage;
            const end = start + productsPerPage;
            const productsToShow = products.slice(start, end);

            const productGrid = document.getElementById("product-grid");
            productGrid.innerHTML = "";

            productsToShow.forEach(product => {
                const productElement = document.createElement("div");
                productElement.className = "product";
                productElement.innerHTML = 
                    <img src="${product.image}" alt="${product.name}">
                    <h3>${product.name}</h3>
                    <button onclick="window.location.href='${product.link}'">Ver Produto</button>
                ;
                productGrid.appendChild(productElement);
            });

            loadPagination(page);
        }

        function loadPagination(page) {
            const pagination = document.getElementById("pagination");
            pagination.innerHTML = "";

            const totalPages = Math.ceil(products.length / productsPerPage);

            if (page > 1) {
                const prevButton = document.createElement("button");
                prevButton.textContent = "Anterior";
                prevButton.onclick = () => displayProducts(page - 1);
                pagination.appendChild(prevButton);
            }

            if (page < totalPages) {
                const nextButton = document.createElement("button");
                nextButton.textContent = "Próxima";
                nextButton.onclick = () => displayProducts(page + 1);
                pagination.appendChild(nextButton);
            }
        }

        function loadCategoryList() {
            const url = admin.php;
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ action: 'getCategories' })
            })
            .then(response => response.json())
            .then(data => {
                categories = data;
                const categoryList = document.getElementById("category-list");
                categoryList.innerHTML = '';

                categories.forEach(category => {
                    const categoryItem = document.createElement('li');
                    categoryItem.innerHTML = 
                        <a href="#" onclick="loadProductsByCategory('${category.name}')">${category.name}</a>
                    ;
                    categoryList.appendChild(categoryItem);
                });
            })
            .catch(error => console.error('Erro:', error));
        }

        function loadProductsByCategory(categoryName) {
            const filteredProducts = products.filter(product => product.category === categoryName);
            const productGrid = document.getElementById("product-grid");
            productGrid.innerHTML = "";

            filteredProducts.forEach(product => {
                const productElement = document.createElement("div");
                productElement.className = "product";
                productElement.innerHTML = 
                    <img src="${product.image}" alt="${product.name}">
                    <h3>${product.name}</h3>
                    <button onclick="window.location.href='${product.link}'">Ver Produto</button>
                ;
                productGrid.appendChild(productElement);
            });
        }

        // Initialize the page with products and categories
        loadProducts(currentPage);
        loadCategoryList();
    </script>
</body>
</html>

vou chamar esse conjunto de codigo de Loja01

nao esta aparecendo na area de admin  opção para editar o produto excluir ou editar mudar a imagem ou link etc