phpsqlrecursive-query

How to save a date from php to SQL table?


i have a php file that works OK. That php makes recursive search in a local folder, and calculates the last modification DATE of those files. My question: Every time that i open that php file i want that date to be stored in a SQL table. -i have created a table with 2 columns (ID, date) where ID=1 then go and update the date field.

but how can i call FROM php file to save the date into sql field?

My php file:

<?php
// LAST FILES UPDATE
function getAllFiles($directory, $recursive = true) {
     $result = array();
$handle =  opendir($directory);
     while ($datei = readdir($handle))
     {
          if (($datei != '.') && ($datei != '..'))
          {
               $file = $directory.$datei;
               if (is_dir($file)) {
                    if ($recursive) {
                         $result = array_merge($result, getAllFiles($file.'/'));
                    }
               } else {
                    $result[] = $file;
               }
          }
     }
     closedir($handle);
     return $result;
}

function getHighestFileTimestamp($directory, $recursive = true) {
     $allFiles = getAllFiles($directory, $recursive);
     $highestKnown = 0;
     foreach ($allFiles as $val) {
          $currentValue = filemtime($val);
          if ($currentValue > $highestKnown) $highestKnown = $currentValue;
     }
     return $highestKnown;
}

echo '<div align="center" style=" padding-top:5px; margin-top:5px; border-top:dotted #777; border-width:1px;">Last Update Date:<br>';

date_default_timezone_set('Europe/Athens');
setlocale(LC_ALL, array('el_GR.UTF-8','el_GR@euro','el_GR','greek'));
echo strftime('%d %b %Y, %H:%M:%S', getHighestFileTimestamp('../'));
echo '</div>';

$host="localhost"; // Host name
$username="..."; // Mysql username
$password="..."; // Mysql password
$db_name="..."; // Database name
$tbl_name="..."; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// update data in mysql database
$sql="UPDATE $tbl_name SET date='HUMMMM HERE HOW TO PULL THE VALUE?' WHERE id='1'";
$result=mysql_query($sql);

// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}

?>

Solution

  • Try something like this:

    // use the function to calculate highest timestamp
    $highestdate = getHighestFileTimestamp("../");
    
    // Insert the highest timestamp into the db
    $sql= sprintf("UPDATE $tbl_name SET date='%s' WHERE id='1'",
    $highestdate);
    

    --EDIT-- merged with Hiroto's answer

    You can use these other styles to concatenate string constants with variables

    $sql = "UPDATE {$tbl_name} SET date='{$date}' WHERE id='{$id}';";
    

    Or, you could use concatenation.

    $sql = "UPDATE " . $tbl_name . " SET date='" . $date . "' WHERE id='1';";