I have an array of image file names which i want to compare against a table in my DB, if the filename is not present then i want to insert it. I have started work on the insert statement, so i will come back to this later. What i am looking for is some help with the code which will check if it exists, then leads on to the insert statement? Below is the code used to build the array, would i be best to include the code to check then insert the data in here, or build a foreach loop which takes each item from the array and checks it?
//Create an array of all images that are Jpgs and start with 'n'
if ($dir = opendir($uploads))
{
$images = array();
foreach (glob($uploads."*.{jpg,jpeg,JPG,JPEG}", GLOB_BRACE) as $filename)
{
$f = str_replace($uploads, null, $filename);
if (strtolower($f[0]) == 'n')
{
$images[] = $f;
}
}
}
Thank you for your ongoing support.
Donna
Edit: Thank you @Lodder for your code. I have tried to implement it with my existing code but it seems to fail at the assignment of the $values variable. I have checked and cannot identify a particular syntax error? Can you spot anything? Here is my full code:
<?php
//display errors
error_reporting(E_ALL);
ini_set("display_errors", 1);
//init Joomla Framework
define('_JEXEC', 1);
define('JPATH_BASE', dirname(__FILE__).'/');
define('DS', DIRECTORY_SEPARATOR);
require_once (JPATH_BASE .DS. 'includes' .DS. 'defines.php');
require_once (JPATH_BASE .DS. 'includes' .DS. 'framework.php');
//Tell the code where the product images are
//Use joomla API <-----------------------------------------------------------Needs looking at
$uploads = '/home/#######/public_html/images/stories/virtuemart/product/';
//Create an array of all image sthat are Jpgs and start with 'n'
if ($dir = opendir($uploads))
{
$images = array();
foreach (glob($uploads."*.{jpg,jpeg,JPG,JPEG}", GLOB_BRACE) as $filename)
{
$f = str_replace($uploads, null, $filename);
if (strtolower($f[0]) == 'n')
{
$images[] = $f;
}
}
}
//$images = array('image1.jpg', 'image2.jpg');
//Start comparison
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('file_url'))
->from($db->quoteName('#__virtuemart_medias'));
$db->setQuery($query);
$rows = $db->loadColumn();
$differences = array_diff($rows, $images);
foreach ($differences as $key => $val)
{
$query = $db->getQuery(true);
$query->clear();
$filetitle = substr($f, 0, strrpos($f, '.'));
$filepath = "images/stories/virtuemart/product/".$f.;
$columns = array('virtuemart_vendor_id', 'file_title', 'file_description', 'file_mimetype', 'file_type', 'file_url','published');
$values = array($db->quote('1'), $db->quote($filename), $db->quote($filetitle), $db->quote('images/jpeg'), $db->quote('Product'), $db->quote($filepath), db->quote('1'));
$query->insert($db->quoteName('#__virtuemart_medias'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$db->setQuery($query);
echo $db->replacePrefix((string) $query);
//$db->execute();
}
?>
Thank you.