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 need | Version / notes |
|---|---|
| PHP | A supported 8.x version with the mysqli extension |
| MySQL / MariaDB | MySQL 8 or MariaDB 10.6+ |
| Local stack (easiest) | XAMPP, Laragon (Windows) or MAMP (macOS) – or install packages on Linux |
| Tools | phpMyAdmin, MySQL Workbench or the mysql client |
3. Local setup
1Install PHP and MySQL
Windows/macOS: install XAMPP/Laragon/MAMP – they include Apache, PHP, MySQL/MariaDB and phpMyAdmin. Ubuntu: install the packages.
BASHsudo apt install -y php php-mysql php-cli mysql-server php -v php -m | grep mysqli2Create a database and user
Never let the app use the MySQL root account.
SQLsudo 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;3Create a table
Run this in phpMyAdmin or the
mysqlclient.SQLUSE 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
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;2Insert with a prepared statement
?placeholders andbind_paramkeep data separate from SQL. Types:sstring,iinteger,ddouble.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; }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>'; }4Run with PHP’s built-in server
Point it at the
publicfolder (with XAMPP, put the project inhtdocsinstead).BASHphp -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.
<?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 / tool | Used for |
|---|---|
mysqli extension | MySQL access (enabled by php-mysql / in php.ini) |
MySQL / MariaDB | Database server |
phpMyAdmin / Workbench | Manage tables and data |
Composer (optional) | PHP package manager for libraries |
Folder structure
shop/
├── config/
│ ├── config.php # credentials (outside web root)
│ └── db.php
├── public/ # web root – only this is reachable
│ ├── index.php
│ └── add.php
└── sql/schema.sqlEssential commands
| Command | What it does |
|---|---|
php -S localhost:8000 -t public | Built-in dev server |
php -m | grep mysqli | Check the extension is loaded |
mysql -u shop -p shop | Open the database |
mysqldump -u shop -p shop > backup.sql | Back up the database |
php -l file.php | Syntax 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
| Requirement | Recommendation |
|---|---|
| Hosting | Shared hosting with PHP 8.x + MySQL, or an Ubuntu VPS |
| Web server | Apache or Nginx + PHP-FPM |
| Database | MySQL 8 / MariaDB with a dedicated user |
| Domain + SSL | Panel’s free SSL or Let’s Encrypt |
Deployment steps
1Shared hosting (cPanel / hPanel)
Create the database and user in the panel’s MySQL Databases section, import
schema.sqlin phpMyAdmin, upload the project with the File Manager or FTP so that the contents ofpublic/are inpublic_html/andconfig/is one level above it, updateconfig.php, and enable the free SSL in the panel.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.
BASHssh 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_IP3VPS: install Nginx, PHP-FPM and MySQL
Then secure MySQL and create the database/user as in section 3.
BASHsudo apt install -y nginx php-fpm php-mysql mysql-server sudo mysql_secure_installation php -v4Upload the code
Only
public/will be web-accessible.BASHsudo 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 credentials5Nginx server block with PHP-FPM
Check the socket name for your PHP version with
ls /run/php/./etc/nginx/sites-available/example.comserver { 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; } }6Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx7Open 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.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status8Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor 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.com9Add 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.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run10Production PHP settings
Hide errors from visitors and log them instead.
/etc/php/8.3/fpm/conf.d/99-production.inidisplay_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.
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
htmlspecialcharsto 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.