As I do not know the progress of the project, I will assume that you have not yet developed the connection part of the database.
To use MySQL PHP , you must use the PDO or MySQLi .
In this example I will use MySQL.
// Aqui abrimos uma conexão com o banco de dados
$db = new mysqli("localhost", "root", "123456", "teste");
// Aqui nós utilizamos a função AVG para obter a média dos valores
$result = $db->query("SELECT AVG('nivel') AS media FROM (SELECT m.'nivel' FROM nivel_agua m ORDER BY m.id DESC LIMIT 2) nivel_agua;");
// Exibimos o resultado
echo "Media: " . $result->fetch_assoc()["media"];
// Fechamos a conexão
$result->close();
$db->close();
Structure of the table I used for testing
+-------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| nivel | float | NO | | NULL | |
| data | timestamp | NO | | NULL | |
+-------+-----------+------+-----+---------+----------------+