Backend & Languages

PHP MySQLi Setup & Deployment Guide

Connect PHP to MySQL safely with MySQLi prepared statements – local setup, a CRUD example, and deployment on a VPS or shared hosting.

Updated Official documentation ↗

1. Introduction & use cases

MySQLi (MySQL improved) is PHP’s built-in extension for working with MySQL and MariaDB databases. It supports prepared statements, which keep user input separate from SQL and prevent SQL injection, plus transactions and both object-oriented and procedural styles.

PHP + MySQL remains one of the most common stacks on the web and runs on almost every hosting plan. (PDO is an alternative that supports several databases; MySQLi is MySQL-specific.)

Where it is used

  • Websites and admin panels on shared hosting
  • Small business apps: enquiries, bookings, inventory
  • Custom APIs for mobile apps
  • Plugins and extensions for PHP CMSs

2. Prerequisites

You needVersion / notes
PHPA supported 8.x version with the mysqli extension
MySQL / MariaDBMySQL 8 or MariaDB 10.6+
Local stack (easiest)XAMPP, Laragon (Windows) or MAMP (macOS) – or install packages on Linux
ToolsphpMyAdmin, MySQL Workbench or the mysql client

3. Local setup

  1. 1Install PHP and MySQL

    Windows/macOS: install XAMPP/Laragon/MAMP – they include Apache, PHP, MySQL/MariaDB and phpMyAdmin. Ubuntu: install the packages.

    BASH
    sudo apt install -y php php-mysql php-cli mysql-server
    php -v
    php -m | grep mysqli
  2. 2Create a database and user

    Never let the app use the MySQL root account.

    SQL
    sudo mysql
    CREATE DATABASE shop CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    CREATE USER 'shop'@'localhost' IDENTIFIED BY 'strong-password';
    GRANT ALL PRIVILEGES ON shop.* TO 'shop'@'localhost';
    FLUSH PRIVILEGES;
  3. 3Create a table

    Run this in phpMyAdmin or the mysql client.

    SQL
    USE shop;
    CREATE TABLE products (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(120) NOT NULL,
      price DECIMAL(10,2) NOT NULL,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );

4. Create & run a project

  1. 1Connection file

    Keep credentials in a config file outside the web root. Since PHP 8.1 MySQLi throws exceptions on errors by default; setting it explicitly makes that clear.

    config/db.php
    <?php
    // config/db.php
    $config = require __DIR__ . '/config.php';
    
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $db = new mysqli($config['host'], $config['user'], $config['pass'], $config['name']);
    $db->set_charset('utf8mb4');
    return $db;
  2. 2Insert with a prepared statement

    ? placeholders and bind_param keep data separate from SQL. Types: s string, i integer, d double.

    public/add.php
    <?php
    $db = require __DIR__ . '/../config/db.php';
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $name  = trim($_POST['name'] ?? '');
        $price = (float) ($_POST['price'] ?? 0);
    
        $stmt = $db->prepare('INSERT INTO products (name, price) VALUES (?, ?)');
        $stmt->bind_param('sd', $name, $price);
        $stmt->execute();
        header('Location: /');
        exit;
    }
  3. 3Read rows safely

    Use prepared statements for every query that includes user input, and escape output with htmlspecialchars.

    public/index.php
    <?php
    $db = require __DIR__ . '/../config/db.php';
    
    $min = (float) ($_GET['min'] ?? 0);
    $stmt = $db->prepare('SELECT id, name, price FROM products WHERE price >= ? ORDER BY id DESC');
    $stmt->bind_param('d', $min);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    foreach ($rows as $p) {
        echo htmlspecialchars($p['name']) . ' – ₹' . number_format($p['price'], 2) . '<br>';
    }
  4. 4Run with PHP’s built-in server

    Point it at the public folder (with XAMPP, put the project in htdocs instead).

    BASH
    php -S localhost:8000 -t public

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Store database credentials in a PHP config file (or environment variables) that sits outside public/ and is not committed to Git.

config/config.php
<?php
// config/config.php – not in Git, not inside public/
return [
    'host' => '127.0.0.1',
    'user' => 'shop',
    'pass' => 'strong-password',
    'name' => 'shop',
];

Key dependencies

Package / toolUsed for
mysqli extensionMySQL access (enabled by php-mysql / in php.ini)
MySQL / MariaDBDatabase server
phpMyAdmin / WorkbenchManage tables and data
Composer (optional)PHP package manager for libraries

Folder structure

project structure
shop/
├── config/
│   ├── config.php     # credentials (outside web root)
│   └── db.php
├── public/            # web root – only this is reachable
│   ├── index.php
│   └── add.php
└── sql/schema.sql

Essential commands

CommandWhat it does
php -S localhost:8000 -t publicBuilt-in dev server
php -m | grep mysqliCheck the extension is loaded
mysql -u shop -p shopOpen the database
mysqldump -u shop -p shop > backup.sqlBack up the database
php -l file.phpSyntax check

6. Production deployment

Choose shared hosting (cPanel/hPanel: upload files, create the database in the panel, done) or a VPS with Nginx + PHP-FPM + MySQL for full control. Both are shown below.

Server & hosting requirements

RequirementRecommendation
HostingShared hosting with PHP 8.x + MySQL, or an Ubuntu VPS
Web serverApache or Nginx + PHP-FPM
DatabaseMySQL 8 / MariaDB with a dedicated user
Domain + SSLPanel’s free SSL or Let’s Encrypt

Deployment steps

  1. 1Shared hosting (cPanel / hPanel)

    Create the database and user in the panel’s MySQL Databases section, import schema.sql in phpMyAdmin, upload the project with the File Manager or FTP so that the contents of public/ are in public_html/ and config/ is one level above it, update config.php, and enable the free SSL in the panel.

  2. 2Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  3. 3VPS: install Nginx, PHP-FPM and MySQL

    Then secure MySQL and create the database/user as in section 3.

    BASH
    sudo apt install -y nginx php-fpm php-mysql mysql-server
    sudo mysql_secure_installation
    php -v
  4. 4Upload the code

    Only public/ will be web-accessible.

    BASH
    sudo mkdir -p /var/www/shop && sudo chown deploy:www-data /var/www/shop
    rsync -avz --exclude config/config.php ./ deploy@YOUR_SERVER_IP:/var/www/shop/
    # create config/config.php on the server with production credentials
  5. 5Nginx server block with PHP-FPM

    Check the socket name for your PHP version with ls /run/php/.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
        root /var/www/shop/public;
        index index.php;
    
        location / { try_files $uri $uri/ /index.php?$query_string; }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        }
    
        location ~ /\. { deny all; }
    }
  6. 6Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  7. 7Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  8. 8Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  9. 9Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  10. 10Production PHP settings

    Hide errors from visitors and log them instead.

    /etc/php/8.3/fpm/conf.d/99-production.ini
    display_errors = Off
    log_errors = On
    expose_php = Off

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ php -S localhost:8000 -t public[Fri Dec 4 10:20:11 2026] PHP 8.x Development Server (http://localhost:8000) started[Fri Dec 4 10:20:15 2026] 127.0.0.1:51432 Accepted[Fri Dec 4 10:20:15 2026] 127.0.0.1:51432 [200]: GET /[Fri Dec 4 10:20:22 2026] 127.0.0.1:51436 [302]: POST /add.php
Figure 1: terminal output of the sample PHP MySQLi project (section 4).
1PHP + prepared SQL2Upload (FTP /rsync)3Nginx/Apache +PHP-FPM4MySQL user per app5HTTPS site
Figure 2: production deployment flow (section 6).
shop/├── config/│ ├── config.php # credentials (outside web root)│ └── db.php├── public/ # web root – only this is reachable│ ├── index.php│ └── add.php└── sql/schema.sql
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Fatal error: Uncaught Error: Class "mysqli" not found

The extension is not installed/enabled. Install php-mysql (Linux) or enable extension=mysqli in php.ini (XAMPP), then restart the web server/PHP-FPM.

mysqli_sql_exception: Access denied for user

Wrong user/password/host, or the user lacks privileges on that database. Check the GRANT and use 127.0.0.1 vs localhost consistently.

Connection refused / No such file or directory

MySQL is not running or listens elsewhere. sudo systemctl status mysql; on shared hosting use the DB host the panel shows.

Hindi/emoji text shows as ????

Use utf8mb4 for the database/tables and call $db->set_charset('utf8mb4').

Commands out of sync; you can't run this command now

A previous result set was not consumed. Fetch all rows or call $stmt->close() / $result->free() before the next query.

Blank page in production

Errors are hidden (correctly). Check the PHP-FPM/Nginx error log: sudo tail -f /var/log/nginx/error.log.

Best practices

  • Always use prepared statements for user input – never concatenate SQL.
  • Escape output with htmlspecialchars to prevent XSS.
  • Give each app its own MySQL user with only the rights it needs.
  • Keep config and credentials outside the web root.
  • Back up with mysqldump (or panel backups) and test restores.