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('Error:', error));
    }
}

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

    if (productName && productImage && productLink && productCategory) {
        fetch('admin.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'addProduct',
                name: productName,
                image: productImage,
                link: productLink,
                category: productCategory
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                if (data.success) {
                    loadProducts();
                }
            }
        })
        .catch(error => console.error('Error:', error));
    } else {
        alert('Por favor, preencha todos os campos.');
    }
}

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('Error:', 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('Error:', 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}" width="50" /></td>
            <td><a href="${product.link}" target="_blank">${product.link}</a></td>
            <td>${product.category}</td>
        `;
        productTableBody.appendChild(row);
    });
}

window.onload = function() {
    loadProducts();
    loadCategories();
};


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: 600px;
            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;
        }
    </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: block; 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>
        <div id="product-list"></div>
    </div>
    <script src="admin.js"></script>
</body>
</html>

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();

config.php

<?php
// config.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);
}
?>


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>Loja de Produtos</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 src="script.js"></script>
</body>
</html>

esse conjuto de codigos nas pagina vou chamar de Loja01

preciso que arrume pois apos adicionar um produto ele nao esta aparecendo na parte de produtos em admin onde é possivel editar ou excluir o produto adicionado e tambem nao esta aparecendo na pagina inicial da loja o produto apos adicionado e verifique se esta correto a adição da imagem do produto pois percebi que no banco de dados esta mostrando a imagem com o caminho C:fakepath/
eu nao sei oque seria esse fakepath

corrija e me entregue os codigos alterados de forma completa pois sou programador iniciane leigo