Line
Skip to main content
< All Topics
Print

How to Connect to MySQL using PHP

We will connect using three different methods: Procedural mysqli, OOP mysqli, and PDO. But before that, let’s get to know MySQL a bit better.

MySQL refers to the MySQL database system, or in this case, it can also refer to MariaDB—whichever you prefer.

mysqli refers to the mysqli extension of PHP, which includes all functions that start with mysqli_.

With that, you probably have some basic understanding already. I believe some of you might be wondering about the differences between PDO and mysqli.

PDO

  • Can use named parameters in prepared statements.
  • Supports lazy binding, allowing parameters to be bound with shorter code.
  • Can only be written in OOP style.
  • Supports connecting to multiple types of databases.

mysqli

  • Can be written in both OOP and procedural styles, making migration from mysql easier.
  • The mysqli code is easier to understand.

 

Methods to connect to a database:

  1. Open XAMPP and click the Admin button on the MySQL row.

2. Go to create a new database, click on “New”.

3. Name the database and select utf8_general_ci.

4 .Open VSCode or any program you use to write PHP, and create a file named connect.php (you can name it whatever you like).

5. Write the database connection code.

If there are no errors, the connection should be successful. To be sure, you can add this piece of code to check the connection.

 

Messenger