MySQLi – Connecting to a Database

In order to manipulate the contents of your database dynamically we will use PHP and SQL.

PHP – is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

SQL – is used to communicate with a database. According to ANSI (American National Standards Institute), it is the standard language for relational database management systems.

Connecting to a Database – Your teacher will provide you with localhost, username and password

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
 
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
 
$conn->close();
?>

The above piece of code allows us to connect to the named database. You must always remember to close the connection to database at the end of every script.

We will now try and create a table then insert data into the database using the INSERT INTO statement.