PHP代码不在我的foreach循环中

时间:2014-04-23 09:14:55

标签: php foreach unlink

我有以下代码基本上我从使用复选框选择的数据库中删除一行或多行,然后使用PHP的unlink()函数从服务器删除相关图像:

if(isset($_POST["delete"])){

    $checkbox = $_POST['checkbox'];

    foreach($checkbox as $id) {

        print "here 1";

        $wpdb->query("DELETE FROM `gate_options` WHERE `id` = $id LIMIT 1");

        print "here 2 after delete row in db";

    }

    $myrows = $wpdb->get_results("SELECT `image_path` FROM `gate_options` WHERE `id` = $id LIMIT 1");

    print "here 3 after assigining myrows to query";

    $root = realpath($_SERVER['DOCUMENT_ROOT']);

    print "here 4 after assigning root path";

    foreach($myrows as $row) {

        print "in the loop";

        print "$root/wp-content/themes/weld-wide/images/gates/" . $row->image_path;

        unlink("$root/wp-content/themes/weld-wide/images/gates/" . $row->image_path);

    }

}

代码行打印"在循环中#34 ;;这是最后一个foreach内部没有打印到屏幕因此它不会进入循环内,问题是为什么?

提前致谢

2 个答案:

答案 0 :(得分:1)

您正在尝试选择刚删除的行,但这无效。

$root = realpath($_SERVER['DOCUMENT_ROOT']);
foreach($checkbox as $id) {

    $id = intval($id); //protects from sql injection (assuming your ids are integers)

    //First get the row to delete its image :
    $myrows = $wpdb->get_results("SELECT `image_path` FROM `gate_options` WHERE `id` = $id LIMIT 1");

    print "Removing : $root/wp-content/themes/weld-wide/images/gates/" . $myrows[0]->image_path;
    unlink("$root/wp-content/themes/weld-wide/images/gates/" . $myrows[0]->image_path);

    //Then delete the row :
    $wpdb->query("DELETE FROM `gate_options` WHERE `id` = '$id' LIMIT 1");

}

答案 1 :(得分:0)

您要么没有行,要么屏蔽错误,这会过早地结束脚本。

SQL结果:

如果没有可用于调试使用$wpdb->get_results()的结果,并且避免将NULL传递给var_dump($myrows)(期望数组),则

NULL会返回foreach )使用

if ($myrows !== NULL) 
{
    /* foreach in here */
}

或者

if (!empty($myrows))
{
    /* foreach in here */
}

错误报告:

要检查错误,您应该在脚本的开头添加以下内容:

error_reporting(E_ALL);
ini_set('display_errors', true);

最佳方法:

if(isset($_POST["delete"]))
{

    $checkbox = $_POST['checkbox'];

    /* this converts every item to an Integer */
    /* which helps sanitize input, and avoid SQL injection attacs */
    $checkbox = array_map('intval', $checkbox);

    /* select all the rows which will be deleted (before deleting them) */
    $myrows = $wpdb->get_results("
        SELECT `image_path`
            FROM `gate_options`
            WHERE `id` IN ( " . implode(', ', $checkbox) . " )
    ");

    /* delete all the rows in one single query */
    $wpdb->query("
        DELETE
            FROM `gate_options`
            WHERE `id` IN ( " . implode(', ', $checkbox) . " )
    ");


    /* remove attachments for the deleted rows */
    $root = realpath($_SERVER['DOCUMENT_ROOT']);
    foreach($myrows as $row)
    {

        print "$root/wp-content/themes/weld-wide/images/gates/" . $row->image_path;
        unlink("$root/wp-content/themes/weld-wide/images/gates/" . $row->image_path);

    }

}
相关问题