开发者

Remove row from database if image not on server

I have a mysql database with a table in the following format:

ID: 1

Date: 2010-12-19

Image: 5d61240f-7aca-d34b-19-12-10-15-36.jpg

Caption: Merry Xmas

I want to create a php script which checks through each row in开发者_开发知识库 this table and checks that the image is present in a gallery folder on my server. If the image is not in the gallery folder then I want to delete this row from my database. Some pointers on how to go about doing this would be very much appreciated.

Thanks!


try

<?php

    define ("GALLERY_ROOT", "/path/to/gallery/" );

    $mysqli = new MySQLi ($host, $username, $password, $db);

    $result = $mysqli -> query ("
        SELECT
            id,
            image
        FROM
            table
    ");

    if ( $result ){
        while ($row = $result->fetch_assoc()) {
            if ( !is_file (GALLERY_ROOT . $row['image'] ) ){
                $mysqli -> query ("
                    DELETE FROM
                        table
                    WHERE
                        id = '" . $row['id'] . "'
                    LIMIT 1
                ");

                print "Deleted " . $row['id'] . "<br />";
            }
        }

        $result -> free();
    }

    $mysqli -> close();

    print "Congratz!! All invalid rows has been deleted!";
?>

That was a quick one, i didn't try running it actually.

Also if you have a lot of rows, then you might want to rethink about selecting all the rows at once. But again get back to me on how it works


Ok... use glob() or the DirectoryIterator, file_exists(), the mysql_ or mysqli_ functions, and 'DELETE FROM images WHERE id = ?'. :)

Hope this helps! If you supply some more information, I could give you more detailed advice. What have you tried so far?

EDIT: wait, I misread. You don't need the directory functions, as you already have the filename. dirname(__FILE__) might be useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜