php 当返回的行为 0 时,为什么 Wordpress $wpdb->query() 响应为 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2989845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:20:30  来源:igfitidea点击:

Why is Wordpress $wpdb->query() response 1 when the rows returned is 0

phpwordpress

提问by codecowboy

I'm doing the following in a custom function:

我在自定义函数中执行以下操作:

    $exists = $wpdb->query($wpdb->prepare('
    SELECT COUNT(*)
    FROM wp_%d_gdsr_data_article
    WHERE post_id = %d

', $blog_id, $post_id));

$exists evaluates to 1 even if no rows are returned by the query. Also, var_dump($wpdb->queries) yields a NULL. Anyone know what is going on here?

即使查询没有返回任何行,$exists 也会计算为 1。此外, var_dump($wpdb->queries) 产生一个 NULL。有谁知道这里发生了什么?

thanks,

谢谢,

回答by thetaiko

From the documentation:

文档

The function returns an integer corresponding to the number of rows affected/selected. If there is a MySQL error, the function will return FALSE. (Note: since both 0 and FALSE can be returned, make sure you use the correct comparison operator: equality == vs. identicality ===).

该函数返回一个与受影响/选择的行数相对应的整数。如果出现 MySQL 错误,该函数将返回 FALSE。(注意:由于 0 和 FALSE 都可以返回,请确保使用正确的比较运算符:相等 == 与相同 ===)。

The query returns 1 row so the query()function returns 1- and will always return 1for the query that you post in your question, even if the number of rows selected by the COUNTis 0. Use get_var, get_row, or get_resultsas suggested by TheDeadMedic to get the actual result of the query, which might be 0, 1, 2, etc.

查询返回1行,以便在query()函数返回1-而总是返回1的查询,你在你的问题后,即使行被选择的号码COUNT是0。使用get_varget_rowget_results通过TheDeadMedic的建议获得的实际结果查询,这可能是012,等。

回答by TheDeadMedic

Use $wpdb->get_var($query)instead.

使用$wpdb->get_var($query)来代替。

Accordingly, use $wpdb->get_row()to retrieve a single row as a single object (or array), and $wpdb->get_results()to get a result set.

因此,用于$wpdb->get_row()检索单个行作为单个对象(或数组),并$wpdb->get_results()获取结果集。