New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› MySQL› Connecting to MySQL

Connecting to MySQL

💻 MySQL

Connect from the command line and from PHP, and understand hosts, ports and users.

Lesson 1 of 9 Tutorial
0 of 9 completed

MySQL is a server. Your application connects to it over a host and port with a username and password, then chooses a database.

By the end of this lesson you can:
  • Connect with the mysql client.
  • Explain host, port, user and database.
  • Connect from PHP with PDO.

The Command Line

The client is usually installed with the server. Use -u for the user and -p to be prompted for a password.

mysql -u root -p
mysql -u root -p -h 127.0.0.1 -P 3306

Choose a Database

After connecting, list databases and select one.

SHOW DATABASES;
USE courselordfusion;
SELECT DATABASE();

Connect from PHP

PDO gives one interface for MySQL and other databases. Always set the error mode to exceptions so failures are not silent.

<?php

$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=courselordfusion;charset=utf8mb4';
$pdo = new PDO($dsn, 'root', '', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$rows = $pdo->query('SELECT id, name FROM students')->fetchAll();
print_r($rows);
Warning Never connect to production as root. Create a user that only has the permissions the application needs.

Practice

  1. Connect to the server and list the databases.
  2. Select a database and show its tables.
  3. Connect from PHP and print one row.

Hands-on exercise

Write a PHP script that:
1. Connects to a database named school with charset utf8mb4.
2. Throws exceptions on error.
3. Runs SELECT 1 AS ok and prints the result.

Recap

MySQL is a server. A connection needs a host, port, user, password and database, and PDO should always throw exceptions.

Example

mysql -u root -p
mysql -u root -p -h 127.0.0.1 -P 3306

Exercises

Exercise 1. First connection Easy
Write a PHP script that:
1. Connects to a database named school with charset utf8mb4.
2. Throws exceptions on error.
3. Runs SELECT 1 AS ok and prints the result.
MySQL exercise-1.txt
Expected Output
Array ( [ok] => 1 )

Lesson Nav

Lesson sections