Connecting to MySQL
💻 MySQLConnect from the command line and from PHP, and understand hosts, ports and users.
MySQL is a server. Your application connects to it over a host and port with a username and password, then chooses a database.
- 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 3306Choose 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);Practice
- Connect to the server and list the databases.
- Select a database and show its tables.
- 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
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.
Expected Output
Array ( [ok] => 1 )
Lesson Nav
MySQL Course
0/9 lessons completed
- 1 Connecting to MySQL Tutorial
- 2 Creating Databases and Tables Tutorial
- 3 Data Types and Constraints Tutorial
- 4 Reading and Writing Data Tutorial
- 5 Joins and Relationships in MySQL Tutorial
- 6 Functions, Dates and Text Tutorial
- 7 Views and Stored Procedures Tutorial
- 8 Users, Permissions and Backups Tutorial
- 9 Project: A Small School Database Project