Creating a simple database with PHP and MySQL

Ok, so we have a digital device, but this digital device has to send data somewhere. This somewhere is what we call a database and this is what we are going to see in this part.

In our case, we want to create a very simple database, this database will hold just the date and the time of each alert.

So what we would like to get is a database accessible through the network with a simple table and two columns, one is the number of the record, the other one is the time of the alert so:

ID | alerttime

1 | 2019-08-31 05:18:01

2 | 2019-08-31 05:18:13

So to create it, we need a MySQL server, and I rather prefer to have PHPMyAdmin as I have a GUI to work on.

In PHPMyAdmin

Create a database, gave the name you want, in my case, I named it then add a table, I named it alert, and add two columns to it:

  • ID: it is an integer and auto-incremented.
  • alerttime: it is a datetime type.

In your PHP page

In your PHP page, your code will look like:

$servername = "localhost";
$username = "ronan";
$password = "rootroot";
$dbname = "motion";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

// Get the time
$date = date('Y/m/d h:i:s', time());

$sql = "INSERT INTO alert (alerttime)
VALUES ('$date')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;


As a result, every connection made to this .php file will record the alert time on the database.

Last modified: Thursday, 6 February 2020, 9:09 PM