图像上传和保存在DB中

My main goal is to save every single uploaded image in folder to have uniqe name. i did that but no matter what uniqe name it have, in DB it still have old original name, how can i save same uniqe name in DB ? My code is:

<?php
     if(isset($_SESSION['username'])){ 
    if(isset($_POST['upload'])) {

$allowed_filetypes = array('.jpg','.jpeg','.png','.gif');
$max_size = "100000"; /// 1 Мегабайт
$max_height = "90000"; /// 300 Килобайта
$max_width = "90000"; /// 300 Килобайта
$upload_path = 'gallery/';
$random = md5(time());
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);

if(!in_array($ext,$allowed_filetypes))
  die('The file you attempted to upload is not allowed.');

if(filesize($_FILES['userfile']['tmp_name']) > $max_size)
  die('Прекалено е тежка снимката.');

if(filesize($_FILES['userfile']['tmp_name']) > $max_height)
  die('Прекалено е голяма снимка във височина.');

if(filesize($_FILES['userfile']['tmp_name']) > $max_width)
  die('Прекалено е голяма снимка във височина.');
if(!is_writable($upload_path))
  die('You cannot upload to the specified directory, please CHMOD it to 777.');

if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path .$random . $filename)) {
$q = mysqli_query($connection,"UPDATE users SET avatar='".$_FILES['userfile']['name']."' WHERE username ='".$_SESSION['username']."'");

echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>"; 


} else {
     echo 'There was an error during the file upload.  Please try again.';
}
}


       echo ' <form action="images.php" method="post" enctype="multipart/form-data"> ';  
       echo ' <input type="file" name="userfile"/>';
       echo ' <input type="submit" name="upload"  value="Качи">';
       echo ' </form>';


 }
 else
 {
echo "<font color='#ec3f8c'>Съжелявам! За да  качиш снимка във профила си, <a href='login.php'><font color='#ec3f8c'><b> трябва да се логнеш</b> </font></a></font>"; 
 }

    ?>

Can someone explain me please, what else i shoud add ?

If I understand the problem, the image is saved in the file system with the correct unique name. that is $upload_path .$random . $filename, but the reference in the database is wrong.

Simply replace the query

UPDATE users SET avatar='".$_FILES['userfile']['name'].

with

UPDATE users SET avatar='".$upload_path .$random . $filename

HTH, Marcello