Most of the websites I create, if not all, use a sql database to store website data of sorts. You might want to use a database to store user data like, usernames and passwords. You might also use a database to store products, categories, reviews and anyother bit of information you can think of.
Most people have a wordpress website nowdays, or have had one at some point. The articles, comments, user details, images, categories, menu items, plugins etc are all stored in a sql database. Ok, plugins will generally have files associated with them, but the config and settings for the plugins will be stored in your database.
If you create your own websites then at some point you will create yourself a database and will want to add or query data stored within it. Before you can do any other that you will need to create a connection string and store it to a variable.
When I create websites, I generally create a folder called inc, and store things like my DB connection file, style sheets and various other bits in there. Like below:
The PHP and MySQLi Connection String
Here is the string I use.
<?php
//Fill this information
$host = "localhost"; // Database Host
$user = "Site_uname"; // Database Username
$password = "password@"; // Database's user Password
$database = "Site_DB"; // Database Name
//------------------------------------------------------------
$connect = mysqli_connect($host, $user, $password, $database);
// Checking Connection
if (mysqli_connect_errno()) {
echo "Failed to connect with MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($connect, "utf8");
?>
You put the above connection string into its own file, I tend to call this file dbconfig.php, but you can call it anything you like. You need to make sure you include the dbconfig file into all your pages that interact with your database.
Here is an example of how to include the dbcnfig file and how to run your first query:
<?php include 'inc/dbconfig.php' ;
$data = mysqli_query($connect,"SELECT * FROM track WHERE id='1' ");
$rowu = mysqli_fetch_assoc($data);
$time = $rowu['datetime'];
Leave a comment if you have a questions or found this post useful