1

When I am echo the $result variable. It display an error msg like this:

Catchable fatal error: Object of class mysqli_result could not be converted to string in D:\Inspiration\server\Table2_yahooData_db.php on line 13

<?php
// connect to the dataBase
$conn = mysqli_connect('localhost', 'root', '', 'yahooData');

//checking Connection.
if (!$conn) {
    die('Error connection failed: ' . mysqli_connect_error($conn));
}

// Creating select query Using sql commands.
$sql = "SELECT * FROM User;" ;
$result = mysqli_query($conn, $sql);

echo $result;

mysqli_close($conn);
?>
Saty
  • 22,443
  • 7
  • 33
  • 51
Hemant Parihar
  • 732
  • 1
  • 6
  • 19

2 Answers2

3

$result is an object.

You cannot print it with string's echo function.

You can rather print it with print_r($result);

echo is for scalar variables (which have single value or are single dimensions) like number, string. For multi-dimensional variables e.g. array, objects we need to use print_r() which prints the whole tree.

Pupil
  • 23,834
  • 6
  • 44
  • 66
  • why i can't print $result variable use echo.? yup print_r function print the $result variable. – Hemant Parihar Jul 23 '15 at 08:38
  • `echo` is for scalar variables (which have single value or are single dimensions) like number, string. For multi-dimensional variables e.g. array, objects we need to use `print_r()` which prints the whole tree). – Pupil Jul 23 '15 at 08:39
1

When using a SELECT query the mysqli_query() function returns a resource, not a string. You need to use mysqli_fetch_assoc() to put the results into an array. Here is an object-oriented example:

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT name FROM User";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        echo $row['name'];
    }

    /* free result set */
    $result->free();
}
HenryTK
  • 1,287
  • 8
  • 11