Q:

How do you connect to MySQL with PHP?

A:

Quick Answer

The PHP server-side programming language has many extensions that allow access to MySQL databases. A couple of options are mysqli and PDO. These object-oriented extensions allow programmers to access databases quickly without the need to write a large amount of code. However, these extensions must be activated before use.

Continue Reading

Full Answer

  1. Find and open the php.ini file

    While newer versions of PHP typically have these MySQL extensions installed by default, you may need to activate them manually. To do this, locate the php.ini file and open it. The location of this file can be found by running a PHP script that outputs the php_ini_loaded_file() function.

  2. Enable PHP database extensions

    If you are using Windows, add the line "extension=php_pdo.dll" or "extension=php_mysqli.dll" to the php.ini file (without the quotes). If you are using Linux, these extensions are commonly enabled by installing their corresponding packages; however, "extension=pdo.so" or "extension=mysqli.so" occasionally need to be added. Save the file and restart your web server so the changes take effect.

  3. Connect to your database

    In order to connect to a MySQL database using either mysqli or PDO, you must create a new object using the corresponding class. Use this script to connect using mysqli: $connect = new mysqli("localhost", "username", "password", "database_name"); Use this script to connect using PDO: $connect = new PDO("mysql:host=localhost;dbname=database_name", "username", "password"); The $connect object can now be used to access your database.

Learn more about Computer Programming
Sources:

Related Questions

Explore