0

Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\xxx\dash.php on line 20

I am quite fairly new, and being a old-school coder, simply using mysql_result to grab such data, I am unaware of how to go about this. I have a class->function setup.

Line 20 of dash.php contains:

echo $user->GetVar('rank', 'Liam', $mysqli);

While, the function is:

function GetVar($var, $username, $mysqli)
    {
        $result = $mysqli->query("SELECT " . $var . " FROM users WHERE username = '" . $username . "' LIMIT 1");
        return $result;
        $result->close();
    }

Now, to my understanding, I am meant to convert $result into a string, but I am not fully aware of how to do so. I've tried using a few methods, but to no avail. So I've come to the community to hopefully get a answer, I've also looked around but noticed that all other threads are asking for num_rows, while I just want to grab the string from the query select.

Kevin
  • 41,694
  • 12
  • 53
  • 70
Reverb
  • 953
  • 2
  • 12
  • 17
  • 2
    you have to fetch it first, gather the results first then return the way you want, an array, etc. actually its in the php [manual](http://php.net/manual/en/mysqli-stmt.fetch.php) – Kevin Sep 05 '14 at 13:15
  • Exactly. What you are actually trying to return is a (raw?) MySQLi object, which of course cannot be converted as string. Also. $result->close will never be executed; Since you close the connection after the return statement, just mentionning. – Alexandre TryHard Leblanc Sep 05 '14 at 13:24

2 Answers2

3

You have to fetch it first before echoing the results. Rough Example:

function GetVar($var, $username, $mysqli) {
    // make the query
    $query = $mysqli->query("SELECT ".$var." FROM users WHERE username = '".$username."' LIMIT 1");
    $result = $query->fetch_assoc(); // fetch it first
    return $result[$var];
}

Then use your function:

echo $user->GetVar('rank', 'Liam', $mysqli);

Important Note: Since you're starting out, kindly check about prepared statements. Don't directly append user input on your query.

Kevin
  • 41,694
  • 12
  • 53
  • 70
0
if ($result = $mysqli->query($query)) {
    while($row = $result->fetch_object()) {
            echo row['column_name'];
        }
}
$result->close();

where you see 'column_name put the name of the column you want to get the string from.

P Clegg
  • 677
  • 2
  • 5
  • 18
  • My upright most apologies, I mustn't have made the thread clear. I'm using a function to retrieve the data. I've updated what the function is. – Reverb Sep 05 '14 at 13:20
  • $result can not be converted to a string because it is an array – P Clegg Sep 05 '14 at 13:21