Wordpress wpdb->更新多个 "WHERE" ID

Wordpress wpdb->update multiple "WHERE" ID's

PHP菜鸟在此:

我需要使用 $wpdb->update 用当前日期时间更新所有值为“NULL”的数据库行。

这是我直接插入 PHPMyAdmin

时可用的 MySQL
UPDATE `mytable`
SET `expired` = CURRENT_TIMESTAMP()
WHERE (`id` > 1 AND `expired` IS NULL)

使用 $wpdb 我发现我需要像这样获取所有需要过期的 ID:

$get_ids = $wpdb->get_results("
    SELECT id
    FROM $database
    WHERE (`id` > 1 AND `expired` IS NULL)
");

所以现在我有一个 ID 数组,我的想法是将它们放在 $wpdb->update 中,就像这样

foreach($get_ids as $key => $value){
    $data = array('expired' => $currentTime);
    $where = array('id' => $value);

    $wpdb->update(
        $database,
        $data,
        $where,
    );

    print_r( $where );
}

print_r returns

 "Array
(
    [id] => stdClass Object
        (
            [id] => 34
        )

)
Array
(
    [id] => stdClass Object
        (
            [id] => 38
        )

)

但是reading the docs我相信它需要更像这样

array(
'id' => $value
)

此外,这是我的错误日志中的PHP错误

[30-Jul-2020 03:42:50 UTC] PHP Notice: wpdb::prepare was called incorrectly. Unsupported value type (object). Please see Debugging in WordPress for more information. (This message was added in version 4.8.2.) in /Applications/MAMP/htdocs/myproject/wp-includes/functions.php on line 5167

[30-Jul-2020 03:42:50 UTC] PHP Warning: mysqli_real_escape_string() expects parameter 2 to be string, object given in /Applications/MAMP/htdocs/myproject/wp-includes/wp-db.php on line 1158

[30-Jul-2020 03:42:50 UTC] PHP Notice: wpdb::prepare was called incorrectly. Unsupported value type (object). Please see Debugging in WordPress for more information. (This message was added in version 4.8.2.) in /Applications/MAMP/htdocs/myproject/wp-includes/functions.php on line 5167

[30-Jul-2020 03:42:50 UTC] PHP Warning: mysqli_real_escape_string() expects parameter 2 to be string, object given in /Applications/MAMP/htdocs/myproject/wp-includes/wp-db.php on line 1158

抱歉,它很长,但我想清楚地展示我的尝试,并清楚地说明我在做什么。

您想要 $wpdb->get_col() 而不是 $wpdb->get_results()。同样的事情,但 get_col returns 一个简单的值数组(因为我们知道你只得到一列),其中 get_results returns 和对象数组,因为你可以获得多列。

或者你可以这样做:

$where = array('id' => $value->id);
// - or -
$where = (array) $value;

但在这种情况下使用:

$get_ids = $wpdb->get_col("
    SELECT id
    FROM $database
    WHERE (`id` > 1 AND `expired` IS NULL)
");

是正确的做法。

参见:https://codex.wordpress.org/Class_Reference/wpdb

我认为您的 mysql 准备错误是由于您将错误的值传递给 where 子句并且无法为准备函数正确解析。