PHP and MySQL Database Connection

  • Hello, dear Jetto Net Followers!

    In this tutorial, you will learn how to connect to MySQL database using PHP and run a simple query! First of all, we are preparing this tutorial assuming that you have PHP and MySQL on your computer! You can set up a PHP and MySQL server with XAMPP!

    First of all, you need to have a database on the MySQL server. You can create a database and a table in the database with the following SQL codes in PhpMyAdmin or MySQL command line:

    Yes, when we run the code above, we will have a database and a table with three fields in the database. Now we can move on to creating the connection with PHP:

    The PHP code above connects to the database_name database on the localhost server with the root user. If the connection is successful, the message “Connection successful!” is displayed. Otherwise, an error message is displayed.

    We have made a database connection with PHP. Now you can perform any operation you want through the $conn connection variable. In this article, I will only show you how to retrieve the data stored in the database. You can easily do it for other queries (SQL knowledge required).

    Now let's pull the saved data from the table in the database:

    The PHP code above pulls the data from the id, name and email columns in the users table and prints it to the screen.

    In this tutorial, you learned how to connect to a MySQL database using PHP and how to perform a simple data extraction query. With this basic knowledge, you can start developing dynamic web applications. You can also ask your questions in the comments!

    Happy coding!

Participate now!

Don’t have an account yet? Register yourself now and be a part of our community!