Kreation
Kreation

Reputation: 327

Catchable fatal error: Object of class WP_User could not be converted to string in /directory/ on line 139

I'm currently trying to get the username of whomever submitted a form, to be stored in a database along with the value they submitted.

This is line 139 from my function:

$retval = $newdb->query("SELECT * FROM $table WHERE user = '$hf_username' ");

add_action("init", "ref_access");
function ref_access() {

global $error;

if ( is_user_logged_in() ) {


    global $quanid;
    global $newdb;
    $hf_username = wp_get_current_user();
    $inputValue  = isset($_POST['$quanid']);
    $newdb = new wpdb( 'user', 'password', 'db', 'localhost' );
    $retval = $newdb->query("SELECT * FROM $table WHERE user = '$hf_username' ");

if( mysqli_num_rows($retval) > 0) 
{
    $newdb->query("UPDATE table SET user = '$hf_username' "); //If user exists, update
}
else
{
global $table;
global $newdb;
    $newdb->insert( 
        $table, 
        array( 
            'ItemID' => $quanid,
            'Price'  => $inputValue,
            'user'   => $hf_username
        )
    );
}


} else {
     $error = "Error: You must be logged in to submit prices";
     return; 
}

}

Upvotes: 4

Views: 8146

Answers (1)

Mathew Tinsley
Mathew Tinsley

Reputation: 6976

wp_get_current_user returns a WP_User object, not the username as a string. The username is stored in the user_login property of the WP_User object.

$hf_user = wp_get_current_user();
$hf_username = $hf_user->user_login;

That said, there are a couple of things that seem a bit off with your code:

  • You seem to be mixing the WordPress database functions with the built in mysqli_ functions. $newdb->query will already return the number of selected rows, there is no need to call mysqli_num_rows and it will not work the way you expect it.
  • You're declaring a new instance of wpdb instead of using the existing database object via global $wpdb. This is not necessary if you're accessing the same database that WordPress is installed on.

Upvotes: 7

Related Questions