💾 Part 2: Connect SQL with PHP

Below is a code for connecting your PHP file to the database and its tables.
Include this code at the top of your file, so it would load before anything else.

$db_host = '';
$db_name = '';
$db_user = '';
$db_pass = '';

// Let's make a connection with the database
$con = mysqli_connect($db_host, $db_user, $db_pass);
		mysqli_set_charset($con, 'utf8');

// Selects which database to connect to
$db = mysqli_select_db($con, $db_name);

Let’s test if we can retrieve any data from our database.
This is the most basic PHP syntax to echo data from the database:

// Make a connection to the table, and select the row from table "blog", where id = 1
$query = mysqli_query($con, "SELECT * FROM blog WHERE id = 1");

// Fetch all the data inside the row with PHP function mysqli_fetch_array
$row = mysqli_fetch_array($query);

// Echo the column "title" from this last fetched row
echo $row['title'];

Independent exercise – echo a full blog post

Write a PHP program which would echo a title and content of your blog post inside HTML tags.
HTML structure is given down below.

<h1>This is the title of blog post</h1>
<p>This is the content of this post</p>
Scroll to Top