33

I am getting the error:

Object of class mysqli_result could not be converted to string

This is my code:

$result = mysqli_query($con, "SELECT classtype FROM learn_users WHERE username='abcde'");

echo "my result <a href='data/$result.php'>My account</a>";
TylerH
  • 20,799
  • 66
  • 75
  • 101
Chinmay Chandak
  • 455
  • 1
  • 8
  • 14
  • 1
    Check out the reference for [mysqli_result](http://php.net/mysqli_result) and it will give you an idea of how to use the object you got back from `mysqli::query()`. – drew010 Oct 22 '12 at 21:39
  • 2
    you need to FETCH a row of data first: http://php.net/mysqli_fetch_row – Marc B Oct 22 '12 at 21:40

5 Answers5

58

The mysqli_query() method returns an object resource to your $result variable, not a string.

You need to loop it up and then access the records. You just can't directly use it as your $result variable.

while ($row = $result->fetch_assoc()) {
    echo $row['classtype']."<br>";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • 9
    You could also do if ($row = $result->fetch_assoc()) {...} instead of while, if you know it is only 1 row. – Andrew Sep 22 '14 at 00:24
9

Before using the $result variable, you should use $row = mysqli_fetch_array($result) or mysqli_fetch_assoc() functions.

Like this:

$row = mysqli_fetch_array($result);

and use the $row array as you need.

Dharman
  • 30,962
  • 25
  • 85
  • 135
5

mysqli:query() returns a mysqli_result object, which cannot be serialized into a string.

You need to fetch the results from the object. Here's how to do it.

If you need a single value.

Fetch a single row from the result and then access column index 0 or using an associative key. Use the null-coalescing operator in case no rows are present in the result.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

$tourresult = $result->fetch_array()[0] ?? '';
// OR
$tourresult = $result->fetch_array()['roomprice'] ?? '';

echo '<strong>Per room amount:  </strong>'.$tourresult;

If you need multiple values.

Use foreach loop to iterate over the result and fetch each row one by one. You can access each column using the column name as an array index.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

foreach($result as $row) {
    echo '<strong>Per room amount:  </strong>'.$row['roomprice'];
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
2

The query() function returns an object, you'll want fetch a record from what's returned from that function. Look at the examples on this page to learn how to print data from mysql

Dharman
  • 30,962
  • 25
  • 85
  • 135
Landon
  • 4,088
  • 3
  • 28
  • 42
0

Try with:

$row = mysqli_fetch_assoc($result);
echo "my result <a href='data/" . htmlentities($row['classtype'], ENT_QUOTES, 'UTF-8') . ".php'>My account</a>";
Dharman
  • 30,962
  • 25
  • 85
  • 135
hsz
  • 148,279
  • 62
  • 259
  • 315