You should be able to re-factor the code slightly to take advantage of Prepared Statements
by creating the statements before you begin inspecting folders. The following uses an array of years to form the outer loop (mentioned) – and on each iteration of that loop the year changes so what was essentially your original code now operates on a different folder.
I have tested the following and it appears to work OK.
<?php
include('config.php');
# Folders for years of interest to scan
$years=array(2020,2021,2022);
# for the output
$li=array();
# Allowed file extensions
$extensions = array('pdf');
# The various SQL cmds used with placeholders where required for use within prepared statements
$sql=(object)array(
'status' => 'update `pdfs` set `status`=0',
'select' => 'select `name` from `pdfs` where `name`=? limit 1',
'update' => 'update `pdfs` set `status`=1 where `name` = `name`=?',
'insert' => 'insert into `pdfs` ( `name` ) values ( ? )'
);
# The prepared statements
$stmt=(object)array(
'status' => $con->prepare( $sql->status ),
'select' => $con->prepare( $sql->select ),
'update' => $con->prepare( $sql->update ),
'insert' => $con->prepare( $sql->insert )
);
# set all PDF status to zero & bind other statements to $name variable
# in mySQLi this variable does not need exist at this stage, in PDO it does.
$stmt->status->execute();
$stmt->select->bind_param('s',$name);
$stmt->update->bind_param('s',$name);
$stmt->insert->bind_param('s',$name);
# iterate through all the years and construct new folder path to scan
foreach( $years as $year ){
$dir=new DirectoryIterator( sprintf( '%s/pdf_folder/%s', __DIR__, $year ) );
#iterate through the files found
foreach( $dir as $info ){
if( !$info->isDot() ){
# is the file extension OK?
$ext=strtolower( pathinfo( $info->getFilename(), PATHINFO_EXTENSION ) );
if( in_array( $ext, $extensions ) ){
# the $name variable is now populated for the SQL prepared statements to execute.
$name=$info->getFilename();
$stmt->select->execute();
$stmt->select->store_result();
if( $stmt->select->num_rows > 0 ){
$stmt->update->execute();
}else{
$stmt->insert->execute();
}
$li[]=sprintf('<li><a href="/pdf_folder/%2$d/%1$s" target="_blank">%1$s</a></li>', $name, $year );
}
}
}
}
# print the HTML list of hyperlinks
printf('<ul>%s</ul>',implode(PHP_EOL,$li));