Connect PHP to MySQL database
Subject: Web development using PHP and MySQL
After setting up the database the next thing is to connect our PHP pages to the database.
PHP primary database is MySQL, so it support several MySQL function, compare to any other RDBM.
PHP function or syntax to connect to MySQL RDBMS is:
mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
Now to connect to our BGdb database, I suppled the right value for the parameters by defining them as constant.
define ('DB_USER', 'root');
define ('DB_PASSWORD', 'onuorah12');
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'BGdb');
Because we are accessing the site on a local sever; the value for some of these parameters remains the same, such as:
DB_USER: root (root is a default MySQL username when you are on a local server, this will definitely change when you deploy to a hosting company server)
DB_PASSWORD: On localhost the password could be empty but I have created a password for it when setting up XAMPP. You will however use a more unique and secure password when deploy to production or to hosting company.
DB_HOST: localhost (though most online server most especially Linux/cpanel hosting I’ve used also leave the hostname as localhost, except for some windows hosting I’ve use; nevertheless if your hosting company use another hostname other that localhost you will be informed. )
DB_NAME: refers to the database name you want to connect to e.g BGdb
To actually use the connection string, programmers prefer putting this important setting into separate file because severally pages will be using it, so that you with have just one file (For example, conn.php) to modify (instead of several pages) when moving the website from a localhost to an internet host.
So create a new page name it conn.php and put the connection string, as we have below.
conn.php
?>
In subsequent lessons we will be using this connection string file to insert, select, update and delete record on FeedBack table in the BGdb.
By:
Benjamin Onuorah
Login to comment or ask question on this topic
Previous Topic Next Topic