<?php

function addToDB($prefix, $emailList, $ipAddress) {
    $host = "localhost"; 
    $username = $prefix."_test_usr";
##    $username = "websdem4_test_usr";
    $password = "NovaLozinka123!"; 
    $database = $prefix."_test"; 
##  $database = "websdem4_test"; 

    $conn = new mysqli($host, $username, $password, $database);
    if ($conn->connect_error) {
        throw new Exception("DB Connection failed!");
    }

    date_default_timezone_set('Europe/Zagreb');
    $current_time = date('Y-m-d H:i:s');
    $emailString = implode(';', $emailList);

    $sql = "INSERT INTO $database (created_at, emails, ip_address) VALUES ('$current_time', '$emailString', '$ipAddress')";
    $conn->query($sql);

    $result = $conn->query("SELECT created_at FROM $database WHERE created_at = '$current_time' ORDER BY id DESC LIMIT 1");

    $conn->close();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $last_created_at = $row["created_at"];
        return $last_created_at;
    } else {
        throw new Exception("DB Select empty!");
    }

}
?>
