W3docs

Introduction to PHP and MySQL

PHP and MySQL are two of the most popular technologies used for web development. They are both open-source technologies and are widely used for building dynamic

PHP and MySQL are two of the most popular technologies for web development, and they are designed to work together. PHP runs on the server and generates the HTML your visitors see; MySQL stores the data those pages need — users, posts, orders, comments. Almost every dynamic site you use (a blog, a forum, an online store) is built on this pairing or one very much like it.

This page explains what each technology does, the two ways PHP talks to MySQL, and a complete, runnable workflow: connect, create a table, insert data, and read it back. By the end you will know which tools to reach for and where to go next for each operation.

What is PHP?

PHP stands for PHP: Hypertext Preprocessor and is a server-side scripting language. "Server-side" means the code runs on the web server before anything is sent to the browser — the visitor never sees the PHP, only the HTML it produces. Because PHP can read user input, talk to a database, and build a different page on every request, it is used for e-commerce sites, forums, blogs, and any application that changes based on data.

What is MySQL?

MySQL is a relational database management system (RDBMS). "Relational" means data lives in tables made of rows and columns — a users table, a products table — and tables can reference each other. PHP sends commands to MySQL using SQL (Structured Query Language), the standard language for asking a database to store or return data. MySQL keeps the data safe on disk between requests, so information entered today is still there next week.

Why use PHP and MySQL together?

  • Free and open-source. Both are free to use and distribute, so you can build and host a complete application at no licensing cost.
  • Scalable. The same stack runs a personal blog or a high-traffic site — you add resources as the data and traffic grow.
  • Easy to learn and well documented. PHP has a gentle learning curve, MySQL is everywhere, and the huge community means most problems you hit are already answered online.
  • Widely supported. Nearly every web host offers PHP and MySQL out of the box, and large companies rely on the combination in production.

Two ways to connect: MySQLi vs. PDO

PHP ships with two modern database extensions. You should pick one and stick with it for a project:

MySQLiPDO
Works withMySQL only12+ databases (MySQL, PostgreSQL, SQLite…)
API stylesProcedural and object-orientedObject-oriented only
Prepared statementsYesYes
Best whenYou are sure you'll only use MySQLYou may switch databases later

Avoid the old mysql_* functions you may find in old tutorials. They were removed in PHP 7 and are insecure. Use MySQLi or PDO.

Both extensions support prepared statements, which is the single most important security feature here — they stop SQL injection attacks. See MySQL Prepared Statements for the full explanation.

Connecting to a MySQL database

A connection needs four things: the host, a username, a password, and the database name. The example below uses the MySQLi procedural style and checks for errors before continuing.

<?php
   $host     = 'localhost';
   $user     = 'username';
   $password = 'password';
   $dbname   = 'database_name';

   // Create connection
   $conn = mysqli_connect($host, $user, $password, $dbname);

   // Always check the connection before doing anything else
   if (!$conn) {
       die("Connection failed: " . mysqli_connect_error());
   }
   echo "Connected successfully";
?>

For the object-oriented MySQLi style, a full PDO example, and connection troubleshooting, see Connecting PHP to MySQL and PHP MySQLi.

The typical workflow

Once you are connected, almost everything you do with a database is one of four operations, often called CRUD — Create, Read, Update, Delete. Each maps to an SQL statement and has its own chapter:

  1. Create a table to define where data lives — see Create a MySQL Table.
  2. Insert rows of data — see Insert Data into MySQL.
  3. Read (select) data back out — see Select Data from MySQL.
  4. Update existing rows — see Update Data in MySQL.
  5. Delete rows you no longer need — see Delete Data in MySQL.

You usually narrow results with a WHERE clause and sort them with ORDER BY.

A complete mini example

This script connects, creates a users table if it does not exist, inserts one row, then reads everything back. It uses a prepared statement for the insert so user-supplied values cannot break the query.

<?php
   $conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
   if (!$conn) {
       die("Connection failed: " . mysqli_connect_error());
   }

   // 1. Create a table
   mysqli_query($conn, "
       CREATE TABLE IF NOT EXISTS users (
           id    INT AUTO_INCREMENT PRIMARY KEY,
           name  VARCHAR(50),
           email VARCHAR(100)
       )
   ");

   // 2. Insert a row safely with a prepared statement
   $stmt = mysqli_prepare($conn, "INSERT INTO users (name, email) VALUES (?, ?)");
   mysqli_stmt_bind_param($stmt, "ss", $name, $email);
   $name  = "Ada Lovelace";
   $email = "[email protected]";
   mysqli_stmt_execute($stmt);

   // 3. Read the data back
   $result = mysqli_query($conn, "SELECT id, name, email FROM users");
   while ($row = mysqli_fetch_assoc($result)) {
       echo $row['id'] . ": " . $row['name'] . " (" . $row['email'] . ")\n";
   }

   mysqli_close($conn);
?>

The "ss" argument tells MySQL both bound values are strings. Because the values are bound separately from the SQL text, an attacker cannot inject malicious SQL through the name or email field.

Common pitfalls

  • Forgetting to check the connection. If credentials or the host are wrong, every later call fails silently. Always die() or handle the error right after connecting.
  • Building queries with string concatenation. Putting user input directly into an SQL string invites SQL injection. Use prepared statements instead.
  • Leaving database errors visible to users. In production, log errors rather than printing mysqli_connect_error() to the page — it can leak server details.

Conclusion

PHP and MySQL let you build dynamic, data-driven websites with free, well-supported tools. Connect with MySQLi or PDO, always use prepared statements for user input, and remember that nearly every database task is just one of the four CRUD operations. From here, follow the workflow links above to learn each operation in depth.

Practice

Practice
What functionality do PHP MySQL functions provide?
What functionality do PHP MySQL functions provide?
Was this page helpful?