Skip to main content

Overview

This guide will walk you through setting up Mis Compras on your local development environment. The platform consists of:
  • Database Layer: MySQL/MariaDB for data persistence
  • Backend: PHP scripts for API endpoints and business logic
  • Node.js Backend: Express.js API server (optional modern API layer)
  • Frontend: HTML/CSS/JavaScript for the user interface
The platform supports both PHP and Node.js backends. The PHP backend is the primary implementation, while the Node.js backend provides a modern alternative API layer.

Prerequisites

Before you begin, ensure you have the following installed:

PHP

Version: 8.0 or higher
  • mysqli extension
  • bcrypt support
  • fileinfo extension (for image uploads)

MySQL/MariaDB

Version: MySQL 8.0+ or MariaDB 10.5+
  • Root or administrative access
  • Default port: 3306 (or custom port 522)

Node.js (Optional)

Version: 16.x or higher
  • npm package manager
  • For the Express.js backend

Web Server

Options:
  • Apache with mod_php
  • XAMPP/WAMP/MAMP
  • PHP built-in server

Installation Steps

1

Clone the Repository

Get the source code for Mis Compras:
git clone https://github.com/your-org/miscompras.git
cd miscompras
Your project structure should look like this:
miscompras/
├── php/                    # PHP API endpoints
│   ├── registro.php
│   ├── login.php
│   ├── vender.php
│   ├── checkout.php
│   └── ...
├── bakend/                 # Node.js backend (optional)
│   ├── server.js
│   ├── db.js
│   ├── routes/
│   └── package.json
├── imagenes/               # Product image uploads
├── conexion.php           # Database connection config
├── index.html
└── tienda_online (1).sql  # Database schema
2

Configure Database Connection

For PHP Backend

Edit the conexion.php file with your database credentials:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";          // Your MySQL password
$database = "tienda_online";
$port = 3306;           // Default MySQL port (or 522 if custom)

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

// Check connection
if ($conn->connect_error) {
    die("Error de conexión: " . $conn->connect_error);
}
?>
Never commit database credentials to version control. Use environment variables or a .env file for production deployments.

For Node.js Backend (Optional)

Edit bakend/db.js to configure the connection pool:
import mysql from "mysql2/promise";

export const db = await mysql.createPool({
  host: "localhost",
  user: "root",
  password: "",              // Your MySQL password
  database: "tienda_online",
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});
3

Set Up the Database

Create the Database

Import the provided SQL schema to set up all required tables:
mysql -u root -p < "tienda_online (1).sql"
Or using phpMyAdmin:
  1. Create a new database named tienda_online
  2. Import the tienda_online (1).sql file

Database Schema

The import creates the following tables:Core Tables:
  • usuarios - User accounts with hashed passwords
  • productos - Product listings with vendor relationships
  • categorias - Product categories (Laptops, Smartphones, etc.)
  • pedidos - Customer orders
  • detalle_pedido - Order line items
  • carrito - Shopping carts
  • detalle_carrito - Cart items
Relationships:
-- Products belong to users (vendors)
ALTER TABLE productos
  ADD CONSTRAINT fk_vendedor 
  FOREIGN KEY (id_vendedor) 
  REFERENCES usuarios(id_usuario) 
  ON DELETE CASCADE;

-- Products belong to categories
ALTER TABLE productos
  ADD CONSTRAINT productos_ibfk_2
  FOREIGN KEY (id_categoria) 
  REFERENCES categorias(id_categoria);

-- Orders belong to users
ALTER TABLE pedidos
  ADD CONSTRAINT pedidos_ibfk_1
  FOREIGN KEY (id_usuario) 
  REFERENCES usuarios(id_usuario) 
  ON DELETE SET NULL;

Verify Installation

Check that all tables were created:
USE tienda_online;
SHOW TABLES;
You should see:
  • carrito
  • categorias
  • detalle_carrito
  • detalle_pedido
  • pedidos
  • productos
  • usuarios
4

Configure File Uploads

Create the directory for product images and set proper permissions:
mkdir -p imagenes
chmod 755 imagenes

Image Upload Configuration

The platform stores product images with unique filenames to prevent collisions:
// From php/vender.php
$originalName = $_FILES['imagen']['name'];
$ext = pathinfo($originalName, PATHINFO_EXTENSION);
$uniqueName = time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
$rutaDestino = "../imagenes/" . $uniqueName;

move_uploaded_file($_FILES['imagen']['tmp_name'], $rutaDestino);
Images are named using a timestamp and random hexadecimal string to ensure uniqueness across all uploads.

PHP Configuration

Ensure your php.ini allows file uploads:
file_uploads = On
upload_max_filesize = 10M
post_max_size = 10M
5

Start the PHP Server

Option 1: PHP Built-in Server (Development)

Navigate to your project directory and start the server:
php -S localhost:8000
Your application will be available at http://localhost:8000

Option 2: Apache/XAMPP (Production-like)

  1. Copy the project to your web server directory:
    • XAMPP: C:\xampp\htdocs\miscompras\
    • MAMP: /Applications/MAMP/htdocs/miscompras/
    • Linux: /var/www/html/miscompras/
  2. Configure Apache virtual host (optional):
<VirtualHost *:80>
    ServerName miscompras.local
    DocumentRoot "/path/to/miscompras"
    
    <Directory "/path/to/miscompras">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
  1. Add to /etc/hosts:
127.0.0.1 miscompras.local
  1. Access at http://miscompras.local
6

Start the Node.js Backend (Optional)

If you want to use the modern Express.js API layer:

Install Dependencies

cd bakend
npm install
Expected dependencies from package.json:
  • express
  • cors
  • body-parser
  • mysql2
  • bcrypt

Start the Server

# Development mode with auto-reload
npm run dev

# Production mode
npm start
The Node.js server will run on http://localhost:4000 by default.

Available Routes

From bakend/server.js:
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
import productosRoutes from "./routes/productos.js";
import pedidosRoutes from "./routes/pedidos.js";
import usuariosRoutes from "./routes/usuarios.js";

const app = express();
const PORT = 4000;

app.use(cors());
app.use(bodyParser.json());

// Main routes
app.use("/api/productos", productosRoutes);
app.use("/api/pedidos", pedidosRoutes);
app.use("/api/usuarios", usuariosRoutes);
API Endpoints:
  • GET /api/productos - Get all products
  • POST /api/usuarios/registro - Register new user
  • POST /api/pedidos - Create new order
The Node.js backend provides a modern REST API alternative to the PHP endpoints. You can use either or both depending on your needs.
7

Verify Installation

Test Database Connection

Create a test PHP file to verify database connectivity:
<?php
// test.php
include 'conexion.php';

if ($conn->connect_error) {
    echo "❌ Database connection failed: " . $conn->connect_error;
} else {
    echo "✅ Database connected successfully!<br>";
    
    // Test query
    $result = $conn->query("SELECT COUNT(*) as count FROM usuarios");
    $row = $result->fetch_assoc();
    echo "Users in database: " . $row['count'];
}
?>

Test User Registration

Use curl or Postman to test the registration endpoint:
curl -X POST http://localhost:8000/php/registro.php \
  -F "nombre=Test User" \
  -F "[email protected]" \
  -F "contrasena=securepassword123"
Expected response:
{
  "success": true,
  "message": "🎉 ¡Registro exitoso!"
}

Test Product Retrieval

curl http://localhost:8000/php/obtener_productos_por_categoria.php
Should return categories with products in JSON format.

Configuration Options

Database Connection Pooling (Node.js)

The Node.js backend uses connection pooling for better performance:
// bakend/db.js
export const db = await mysql.createPool({
  host: "localhost",
  user: "root",
  password: "",
  database: "tienda_online",
  waitForConnections: true,
  connectionLimit: 10,      // Max concurrent connections
  queueLimit: 0,            // Unlimited queue
});

CORS Configuration

Both backends support CORS for cross-origin requests: PHP (in each endpoint):
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
Node.js:
import cors from "cors";
app.use(cors());

Common Issues and Solutions

Solution: Check your MySQL credentials in conexion.php or bakend/db.js. Ensure the MySQL user has proper permissions:
GRANT ALL PRIVILEGES ON tienda_online.* TO 'root'@'localhost';
FLUSH PRIVILEGES;
Solution: Set proper permissions on the images directory:
chmod -R 755 imagenes
chown -R www-data:www-data imagenes  # Linux/Apache
Solution: Enable error display in your PHP configuration:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Or add to php.ini:
display_errors = On
error_reporting = E_ALL
Solution: Install dependencies in the backend directory:
cd bakend
npm install express cors body-parser mysql2 bcrypt
Solution: Verify MySQL is running on the custom port:
netstat -an | grep 522
Update both conexion.php and bakend/db.js with the correct port number.

Security Best Practices

Before deploying to production, implement these security measures:

Password Hashing

The platform uses secure password hashing: PHP:
// Registration - php/registro.php
$hash = password_hash($contrasena, PASSWORD_DEFAULT);

// Login - php/login.php
if (password_verify($contrasena, $usuario["contrasena"])) {
    // Password is correct
}
Node.js:
// Registration - bakend/routes/usuarios.js
import bcrypt from "bcrypt";
const hash = await bcrypt.hash(contraseña, 10);

SQL Injection Prevention

Always use prepared statements:
// Good - Prepared statement
$stmt = $conn->prepare("SELECT * FROM usuarios WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();

// Bad - Direct concatenation (NEVER DO THIS)
$sql = "SELECT * FROM usuarios WHERE email = '$email'";

File Upload Validation

// Validate file type
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$ext = strtolower(pathinfo($_FILES['imagen']['name'], PATHINFO_EXTENSION));

if (!in_array($ext, $allowed)) {
    die("Invalid file type");
}

// Validate file size (10MB max)
if ($_FILES['imagen']['size'] > 10485760) {
    die("File too large");
}

Next Steps

Quickstart Guide

Learn how to use the platform - registration, purchases, and listings

API Documentation

Explore all available API endpoints in detail

Database Schema

Understand the complete database structure

Configuration

Configure PHP and Node.js backends

Getting Help

If you encounter issues during installation:
  1. Check the Common Issues section above
  2. Verify all prerequisites are installed correctly
  3. Review PHP and MySQL error logs
  4. Ensure file permissions are set correctly
  5. Test database connectivity independently
For development questions, refer to the API documentation and quickstart guide.

Build docs developers (and LLMs) love