简体   繁体   中英

How to avoid adding redundant data in SQLite table using php?

I am working on a php code as shown below which lists all the mp4 files present in a $src_dir .

$src_dir = ('\\\ABCD-ST-001\Audio_Test\podcast\incoming_folder'); 

$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir));

print_r(array_values($mp4_files));  // LineA

Here is the O/P obtained from Line#A :

Array ( [0] => 36031P.mp4 [1] => hello.mp4 )

Now, I have used the following script in my php code in order to insert those mp4 files in Podcast_Export table.

    foreach ($mp4_files as $value) {
        $db->exec(SELECT COUNT(*) FROM Podcast_Export WHERE House# = '".$value."' AND status = 'GO');
        $db->exec("INSERT INTO Podcast_Export ('House_number', 'Status') VALUES ('".$value."', 'Go')");    // Line B
    }

The above script add the following data inside Podcast_Export table:

36031.mp4 Go
hello.mp4 Go

Problem Statement:

The issue which I am facing right now is when I refresh the page, the script at LineB is run again and mp4 files present in a $src_dir is added again inside Podcast_Export table as shown below:

36031.mp4 Go
hello.mp4 Go
36031.mp4 Go
hello.mp4 Go

It should work in a way that once new file comes up inside $src_dir then it should add inside Podcast_Export table. Let us suppose the new file is hxz210.mp4 then the content inside Podcast_Export table should be:

36031.mp4  Go
hello.mp4  Go
hxz210.mp4 Go

Your selection is fine, but you need to store result into an variable like:

$count = $db->querySingle("SELECT COUNT(*) as count FROM Podcast_Export WHERE House_number = '".$value."'"); 
if($count <= 0){ 
    $db->exec("INSERT INTO Podcast_Export (House_number,Status) 
               VALUES ('".$value."', 'Go')");
}

Using querySingle to get the no of rows in SQLite.

note that, i have chanaged the House# to House_number here and removed AND status = 'GO' clause as all of them having GO status.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM