Object can't be converted to a string in MySQL

2019-03-06 11:08发布

问题:

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.

回答1:

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.



回答2:

Read this tutorial. it explain how to read and display data from a dataabse

Select Data From a Database Table



回答3:

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.



标签: php mysql mysqli