0

I need to check duplicate files from a path and need to insert the file name in a table if it is new and then insert all records of it accordingly into another table. Do not insert or step forward if file already exists.

Here is my code where i can't bring the file path with '/' into the DB. Can anyone assist? Thanks in advance.

File Path with '/' is not passing using $open = fopen('$cont[$x]','r');

<?php

//include ("connection.php");
$conn = new mysqli('localhost','root','','demo');

$path = _DIR_ . DIRECTORY_SEPARATOR ."*.{txt}";
$cont = glob($path, GLOB_BRACE);
//print_r($content);

$arrlength = count($cont);
for($x = 0; $x < $arrlength; $x++){
//    $sql = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";

    $dup = mysqli_query($conn,"SELECT * FROM file_record WHERE file_name = '$cont[$x]' ");

    if(mysqli_num_rows($dup)>0)
    {
        echo "File already Exists";
    }

    else {

            $insert = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
//            $conn->query($insert);
        if (mysqli_query($conn,$insert)) {

            $open = fopen('$cont[$x]','r');

            while (!feof($open))
            {
                $content = fgets($open);
                $carry = explode(",",$content);

                list($name,$city,$postcode,$job_title) = $carry;

                $sql = "INSERT INTO `employee` (`name`, `city`, `postcode`, `job_title`) VALUES ('$name','$city','$postcode','$job_title')";
                $conn->query($sql);
            }

            fclose($open);

            echo 'inserted';
        } else {
            echo 'Not inserted';
        }
    }

    }

?>
RaceTech
  • 71
  • 6
  • 1
    When you use single quotes around `fopen('$cont[$x]'` - this means that the variable will contain `$cont[$x]`. Try removing the quotes. – Nigel Ren Sep 13 '21 at 06:32
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Sep 13 '21 at 12:39

0 Answers0