How to Connect to Database Using PHP

Introduction

You can create databases on 000webhost.com and PHP can be used to connect to those databases. This tutorial explains three different methods how that could be achieved. Most of the websites need to have at least one database and if you are developing a website from the beginning you will have to connect it to a database manually, here you can find how that could be done step by step.

What you’ll need

Before you begin this guide you’ll need the following:

Step 1 — Creating a PHP file

You need to create a PHP file (with .php extension) on your computer and upload it to the server. It’s just a simple new file created on your computer which has a .php extension. Here is a tutorial about doing that on Windows system using Notepad: Creating PHP file.

Step 2 — Uploading the file created

You should navigate to the file manager of 000webhost now and upload the file created. On your control panel press Upload files and then Upload files now.

Once you are redirected to the File Manager press the control buttons and select Upload files as provided in the screenshots below:

Then you need to select the necessary file on your computer and press Upload button:

Step 3 — Editing the PHP file

Now you need to edit the uploaded file. It can be done directly on the File Manager. Press the right mouse button on the uploaded file and select edit:

The file should be edited depending on the connection method. If you are interested in differences between these methods you can read more here

Method 1 — Connecting to the database using PDO (recommended)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    // 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();
    }
?>

Method 2 — Connecting to the database using mysqli (Object-Oriented)

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Method 3 — Connecting to the database using mysqli_connect (Procedural)

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";
?>

Step 4 — Making the necessary changes

On all the methods you need to edit three lines only because 000webhost uses localhost as the servername (servername should not be changed).

  • Username - The username assigned to the database. It can be found on your 000webhost control panel -> Manage database. Username is combined of your
    000webhost username and the name you created.

  • Password - a password which you set for your username of this database.

  • Database - The name of your database. It can be found on your 000webhost control panel -> Manage database. Database name is combined of your 000webhost username and the name of the database you created.

If you are not sure where to find these entries it can be done on your 000webhost.com control panel -> Manage Database:


DB Name and DB User are visible on the page and if you forgot the password it can be changed by clicking the Manage button as provided in the screenshot above.

Step 5 — Testing the PHP connection

Now you can test if there are any errors in the syntax of the file. If your file is uploaded to public_html directory simply enter your website address to the browser and add /filename.php at the end of it. For example yourwebsite.000webhostapp.com/phpconnect.php. If you get a message Connected successfully on the browser it means, that script works just fine and you can use it when connecting your website or a script to a database. If you get Connection failed: an error should appear on the browser which should help you identify the mistake which was made.

Conclusion

These are three simple methods to connect to a database using a PHP file. They can be used to test the connection to the database and if the connection works fine you can start using commands which create, edit or delete entries in your database. It can also help you identify if the issue is on your website or the database of the server when your website can’t connect to the database and gives you an error.

3 Likes
No old cpanel ?where can i find my sql hostname to use in php files to connect to the database
Is there something wrong with mysql host: mysql8.000webhost.com
HTTP 500 ERROR while connecting database for first time
Unable to mysqli_connect()@mysql8 -- mysql8 STILL down?
Need Help in database error..!
Connection failed: SQLSTATE[HY000] [1045] ProxySQL Error: Access denied for user 'id2379720_jhapz'@'2a02:4780:bad:f00d::c' (using password: YES)
Free 000webhostapp database connection
Help getting my code to work
SQL Connection Refused
Mysqli_querry Access Denied
Is there something wrong with mysql host: mysql8.000webhost.com
SQL Connection failed "Warning: mysqli_connect(): (HY000/2002): Connection refused"
Mysql_query() expects parameter
Access denied for user 'root'
Probleme In config.php
SQL database wont receive input
Can,t connnect to database
MySQL Connexion 000WebHost
connectiing to database
What is the Database Connection Code? Please help Thank you
Trying to input text into database
I can't access my database in 000webhost
SIM900 Arduino trying to post to database
Not connected to the database
I want to let my website connect to my own hosted MySQL Database. How do i do that?
Extension connection pdo
Database connectivity issue in codeigniter
How to send data to data base with arduino
Intento insertar desde un formulario en mi BD pero no me funciona ayuda por favor
Can't connect MyPHPadmin to my front page
Mysql connect a6937125
Data cannot insert in to the database
Database Connection Issues
¿como probar la base de datos?
DataBase connection through PhPAdmin;
About the phpmyadmin
Failed Log In to phpMyAdmin
Able to fetch data from the database but wont send any data to database (NO ERROR SHOWN)
You have reached maximus database allowed
Please I'm having issues with redirecting and sql connction
Daxo Question MySQL
Error with set data in database
Config php ini file
Mysql connection plis help
Lmp4ct34 using wrong username for database connection
Como trazer de mysqli para mysql
Database Troubleshooting Guide
Could not connect: error HELP!
I can't connect localhost
Probleme In config.php
How to create a Database with PDO?
What is the phpadmin password/What parameters do I put for my PDO object?
My database shows 0mb
Why can I not access SQL?
No hay conexion con base de datos
Suddenly my sql requests do not work
Сайт не видит базу данных
Ftp_put(): Disk full - please upload later
Encountering connection error while trying to establish mysql connection in a php script.
Database don t save data's
Form to database submit problem
Why img aren't display? And Database not working?
000webhost not displaying data from phpmyadmin
Mysql does not work
Problemas con el archivo php que hace la conexión a la BD
No login en mi aplicacion no trabaja login
I cannot Log into phpMyAdmin
What is hostname?