PHP MYSQL Connect
The connection to the mySQL database is the basics to php / mySQL. If this fails, all fails. Once you can connect to a database, you can select and alter data. It is like learning to walk.
Whether you plant to create a simple or elaborate PHP / mySQL application, you must connect to a mySQL database. There are many ways to write the code for which to do so, but,two functions will be present for you to do so. The two functions are mysqli_connect() and mysqli_select_db. The function mysqli_connect will appear first for obvious reasons. Doesn't it make sense to first connect to a database then select it?
Normally, there are two methods for which the connection takes place. One technique is to use a function and the other is to just add the code into a page. Using a function is more secure and it saves on code repetition. This might not look like much now, but, an 8,000 word php/mysql application with separate database connection files used on a new server could be a hassle to fix up more than once.
Accessing Database With Function
The code below $db = public_db_connect(); calls the function and returns the $db variable. That variable can be passed into select, update, delete, and insert into queries.
Accessing Database Without a Function
The code below will connect to a database. The $db variable is used in the mysqli_query() function. The output is the same as the example above.