Home>

I am practicing to output the data obtained from the database by get_results by the number of the obtained data, but if I try to rotate it with a foreach statement, an error occurs.

Code you tried

global $wpdb;
$comments_table = $wpdb->prefix. "comments";
// Get the comment ID of the comment with "100" in the database
$check_user_comment_ID = $wpdb->get_results ("SELECT comment_ID FROM $comments_table WHERE meta_key = 'UserID' AND meta_value = 100");
// By the way, if you look into the contents of $check_user_comment_ID with print_r ();
// Array ([0] =>stdClass Object ([comment_ID] =>1) [1] =>stdClass Object ([comment_ID] =>2) [2] =>stdClass Object ([comment_ID] =>3))
foreach ($check_user_comment_ID as $key =>$value) {
    echo $value;
}
// Result = "Recoverable fatal error: Object of class stdClass could not be converted to string"


In the result of echo $value ;, I would like to output the ID of the comment whose "UserID is 100", but I do not know where to fix it.

If anyone can understand you, I would appreciate it.

  • Answer # 1

    Because it is written as stdClass Object,$valueseems to contain a class instance, soecho $value->comment_ID;You can refer to the property of the instance with the arrow operator like this.