Javascript required
Skip to content Skip to sidebar Skip to footer

How to Create Mysql Database in Php

php connect to mysql

MySQL is a highly popular database management system that can power projects of all sizes. Its ability to handle huge volumes of data without breaking a sweat is one of its biggest selling points. Connect MySQL with PHP code, you can make use of one of three methodologies.

There are three types of methods in PHP to connect MySQL database through backend:

  • MySQL
  • MySQLi
  • PDO

mysql() is now obsolete because of security issues like SQL injection etc, but the other two are being actively used.

MySQLi

MySQLi is an API used as a connector function to link the backend of the PHP app to the MySQL database. It works just like the previous version, but it is safer and faster, and provides a better set of functions and extensions. MySQLi was introduced with PHP 5.0.0 and the drivers were installed in 5.3.0. The API was designed to support MySQL from version 4.1.13 to newer ones.

PDO

PHP Data Objects (PDO) extension is a Database Abstraction Layer. It is like an interface for the backend to interact with the MySQL database and make changes without making any change in the PHP code. It also gives you the freedom to work with multiple databases. The major advantage of using PDO is that your code stays simple and portable.

In this article, I'll discuss how to connect MySQL Database on different servers and I'll also give you an overview of connecting Database using PDO.

  1. Connect MySQL using Localhost Server
  2. Connect MySQL using Cloudways Server
  3. Connect MySQL using PDO
  4. Connect MySQL using Remote MySQL
  1. Create MySQL Database at the Localhost
    1. Create Database
    2. Create a Folder in htdocs
    3. Create Database Connection File In PHP
    4. Create new php file to check your database connection
    5. Run it
  2. Create MySQL Database at Cloudways Server
    1. Create Database Connection
    2. MySQLi Procedural Query
    3. Connect MySQL Database with PHP Using PDO
    4. Check Connection
  3. Remote MySQL
  4. Top MySQL Management tools
    1. MySQL Workbench
    2. Navicat For MySQL
    3. MySQL Yog
    4. Cloudways MySQL Database Manager
  5. Conclusion

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Create MySQL Database at the Localhost

Before you start building PHP connection to MySQL database you need to know what PHPMyAdmin is. It's a control panel from where you can manage the database that you've created. Open your browser and go to localhost/PHPMyAdmin or click "Admin" in XAMPP UI.

When you first installed XAMPP, it only created the username for it to be accessed, you now have to add a password to it by yourself. For this, you have to go to User account where the user is the same as the one shown in this picture:

change password database

Now click Edit privileges and go to Change Admin password, type your password there and save it. Remember this password as it will be used to connect to your Database.

change password database

Note: It is not necessary to change the password to access databases on the localhost. It is a good practice and that is why we have used a password.

Create Database

Now return to the homepage of PHPMyAdmin. Click theNew button to create a new database.

phpmyadmin

In the new window, name your database as per your need, I am naming it " practice ". Now select Collation as utf8_general_ci, as we are using it for learning purposes and it will handle all of our queries and data that will be covered in this tutorial series. Now click on Create and your database will be created.

create database

The newly created database will be empty now, as there are no tables in it. I will be covering that in the upcoming series where we will learn how to create tables and insert data in it. In this tutorial, we are going to connect this database to localhost using PHP

tables in database

Create a Folder in htdocs

Now, locate the folder where you installed XAMPP and open the htdocs folder (usually c:/xampp). Create a new folder inside c:/xampp/htdocs/ and name it "practice" we will place web files in this folder. Why we have created a folder in htdocs? XAMPP uses folders in htdocs to execute and run your PHP sites.

Note: If you are using WAMP, then add your practice folder in c:/wamp/www folder.

Create Database Connection File In PHP

Create a new PHP file and name it db_connnection.php and save it. Why am I creating a separate database connection file? Because if you have created multiple files in which you want to insert data or select data from the databases, you don't need to write the code for database connection every time.

<?php  function OpenCon()  {  $dbhost = "localhost";  $dbuser = "root";  $dbpass = "1234";  $db = "example";    $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);     return $conn;  }   function CloseCon($conn)  {  $conn -> close();  }     ?>

Here is the explanation of the variable that we have used in our db_connection file:

  1. $dbhost will be the host where your server is running it is usually localhost.
  2. $dbuser will be the username i.e. root and $dbpass will be the password which is the same that you used to access your PHPMyAdmin.
  3. $dbname will be the name of your database which we have created in this tutorial.

You just have to include it by using PHP custom function include (include 'connection.php') on the top of your code and call its function and use it. It also helps when you are moving your project location from one PC to another and you have to change the values on the single file and all the changes will be applied to all the other files automatically.

Create a new PHP file to check your database connection

Create a new PHP file to connect to your database. Name it index.php and add this code in this file.

<?php include 'db_connection.php';  $conn = OpenCon();  echo "Connected Successfully";  CloseCon($conn);  ?>

Run it!

Now open your browser and goto localhost/practice/index.php and you should see this screen:

connection successfully

Confirmation Message

Congratulations! You've successfully connected your database with your localhost! If you are not able to see this screen, then check if you have done everything right in your db_connection.php file.

Create MySQL Database at Cloudways Server

For the purpose of this tutorial, I assume that you have a PHP application installed on a web server. My setup is:

  • PHP 7.3
  • MySQL

I decided to host my PHP application on Cloudways managed servers because I get a highly optimized hosting stack and no server management hassles. You can try out Cloudways for free by signing for an account and then following this simple GIF for setting up the server and the PHP application. Check out Cloudways hosting plans for AWS, Google Compute Engine, Vultr, Linode and Digital Ocean to find the right fit for you.

server-launch

After successfully launching a PHP Application on Cloudways go in the application tab and check the details of the database and also click on the button to launch database manager .

php connect to mysql

Connect to MySQL Database

To set up a connection to the database use the mysql_connect function. This function returns a pointer (also known as a database handle) to the database connection. This handle will be used in the code later on. Once you have the handle, remember to add your database credentials.

  • Create a new PHP file and name it db_connnection.php and save it.

Why am I creating a separate database connection file? Because if you have created multiple files in which you want to insert data or select data from the databases, you don't need to write the code for database connection every time. You just have to include it by using PHP custom function include (include 'connection.php') on the top of your code and call its function and use it.

At this point you have the option of either using MySQLi procedural connection query or PHP PDO based database connection:

MySQLi Procedural Query

<?php  $servername = "localhost";  $username = "username";  $password = "password";  $db = "dbname";    // Create connection  $conn = mysqli_connect($servername, $username, $password,$db);    // Check connection  if (!$conn) {     die("Connection failed: " . mysqli_connect_error());  }  echo "Connected successfully";  ?>

Connect MySQL Database with PHP Using PDO

<?php  $servername = "localhost";  $username = "username";  $password = "password";  $db = "dbname";    try {     $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password, $db);     // set the PDO error mode to exception     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     echo "Connected successfully";     }  catch(PDOException $e)     {     echo "Connection failed: " . $e->getMessage();     }  ?>

Check Connection

<?php  include 'db_connection.php';     echo "Connected Successfully";  mysqli_close($conn);  ?>        

For PDO Close the Connection like this

$conn = null;

php connect to mysql database

Remote MySQL

For Remote PHP MySQL connection Log into the Cloudways Platform with your credentials. Click on "Servers" in the top menu bar. Then, click on your target server from the list.

  • Next, go to the Security menu option in the left menu, and then click the MySQL tab.
  • Add the IP address to the "Add IP to Whitelist" text area and click the "Add" button.
  • If you have multiple IP addresses, repeat the process.
  • Once you are done, click the "Save Changes" button to finalize the changes

how to connect php to mysql

After successfully, set the IP Whitelisting set the IP address in connection and run the query.

Top MySQL Management tools

MySQL Workbench

MySQL Workbench is a visual tool for database designers, developers, and DBAs. MySQL Workbench gives information modeling, SQL advancement, and comprehensive organization devices for server arrangement, client organization, reinforcement, and much more. MySQL Workbench is accessible on Windows, Linux and Mac OS X.

MySQL Workbench is a very popular MySQL database manager for developers. It provides handy administration tools like server configuration, user management, and many others.It is available for MAC OS, Linux, and Windows operating systems.

We advise all those budding developers who want to learn database administration to use it to their advantage. The management features will help them in mastering database administration in full.

Pros

  1. It saves SQL statements
  2. Provides offline access to remote DBs
  3. Stores multiple connections in one location
  4. Visual schema and query builder available

Cons

  1. It is more complex as compared to PHPMyAdmin.
  2. Users often report software crashes.

Navicat is a series of graphical database administration and software development. It could be a single application that permits you to associate to PHP MySQL connection and MariaDB databases at the same time. Consistent with cloud databases like Amazon RDS, Amazon Aurora, Oracle Cloud, Google Cloud, and Microsoft Azure.

Navicat for MySQL provides all the advanced tools that a developer requires to fully manage his database operations. Its compatibility with cloud databases makes it handy to use while managing a cloud-based application. Some of its main features are:

Pros:

  1. Intuitive, easy-to-use UI.
  2. Provides easy connection to MySQL database via SSH terminal.
  3. Schedule database jobs – backup, restore, run reports, and more.
  4. Import and export data from ODBC, Excel, Access, DBF, TXT, CSV, XML, JSON.
  5. Visual schema and query builders available.
  6. Compatible with Windows, Linux, and MAC operating systems.
  7. Team collaboration feature available

Cons:

  1. The professional version is expensive
  2. Execution on Linux requires Wine, which slows down the IDE.
  3. Time-consuming process management

MySQL Yog

This MySQL management tool has three packages available i.e Professional, Enterprise, and Pro. You can choose any one of them after testing out.

The MySQL administrators can easily work with this platform and can handle their database tasks with efficiency. It is available for Windows operating systems only.

PROS

  1. Smooth query designer tool available
  2. Offers advanced features that help in learning database administration.

CONS

  1. The pro version is heavy on pocket
  2. Users often report occasional software crashes
  3. Doesn't support any databases except MySQL
  4. No native support for Linux and MAC operating systems.
  5. No drag and drop support between multiple tabs.

Cloudways MySQL Database Manager

Cloudways MySQL database manager is by far one of the handiest and useful MySQL management tools for developers. It is very easy to use because of its user-friendly UI and provides all the required MySQL administration tools a database manager should have:

Pros:

  1. Offers user-friendly and customizable UI with advanced features.
  2. Designs the schema tables, constraints, and queries visually.
  3. Easy connection to MySQL database using SSH terminal.

Cons

  1. No drag and drop support available for multiple tabs.
  2. Lack of support for databases other than MariaDB, MySQL.

Q: How do I check if MySQL is running or not?

A: To check to see if MySQL is running, provided its installed as a service you can go to Start -> Control Panel -> Administrative Tools -> Services and look for MySQL on that list. Check if it is running or not.

Q: How do I find my localhost port for MySQL?

A: If you are using MySQL Workbench, look in the Session tab in the Information pane on the sidebar. If you are using phpMyAdmin, click on Home, then Variables on the top menu. Look for the port setting on the page. The set value is your MySQL port number.

Q: What is my localhost MySQL username and password?

A: Check out http://php.net/manual/en/function.mysql-connect.php. $servername = "localhost"; $username = "root"; $password = ""; This would likely to work for new users and do not forget to create the database before connecting to it.

Q: What is the standard PHP function for connecting to a MySQL database?

A: One of the reasons why PHP works so well with MySQL is the mysql_connect function that opens a database connection. This function takes five arguments.

Conclusion

A good database structure is the backbone of any application. Whether it's a CMS or an online task tracking platform, you need a MySQL database(s) to keep track of app and user information and server data to the application processes.

In this tutorial, we have learned two things:

  • How to create a new database
  • How to connect MySQL database with PHP

Both MySQLi and PDO have their preferences. However, before starting off one should keep in mind that MySQL is only used to connect MySQL with PHP, if you need to migrate to another database, you'll get to modify the whole code. On the other hand, PDO works with 12 diverse databases, which makes the migration much less demanding.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

"Cloudways hosting has one of the best customer service and hosting speed"

Sanjit C [Website Developer]

Inshal Ali

Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.

How to Create Mysql Database in Php

Source: https://www.cloudways.com/blog/connect-mysql-with-php/