Php mysqli result to string

Object of class mysqli_result could not be converted to String

Basically, the error Object of class [Class name] could not be converted to string will raise whenever we try to use an object as a string.

For example, Suppose we have stdclass as below

$student = new stdClass(); $student->name = "John"; $student->id = 123;

Now we are going to treat the object $student as a string. Therefore let’s say we print as below

Result: Object of class stdClass could not be converted to a string

And the same issue occurred once we try to use mysqli_query returned result as a string rather than an object

Let’s see the following code

$servername = "localhost"; // Specify your server Host/IP address here if not localhost $username = "username"; // Replace your Database username here $password = "db_pwd"; // Replace your Database password here $db= "demo"; //Replace your database name here $mysqli = new mysqli($servername,$username,$password,$db); // Check connection if ($mysqli -> connect_errno) < echo "Failed to connect Database: " . $mysqli ->connect_error; exit(); > $resultSet = mysqli_query($mysqli, "SELECT * FROM tbl_employee"); echo "Employee:". $resultSet;

Result: PHP Catchable fatal error: Object of class mysqli_result could not be converted to string

Explanation:

  • Here function mysqli_query is used to perform a specified query to the database.
  • As per mysqli_query definition, it will return FALSE on failure
    and mysqli_result object on the success of SELECT Query.
  • In our case, it returns a result object and we have tried to print this result object therefore it complains.

Now let’s understand how to fetch database records and use them as strings. Find following Mysqli functions demonstrating for extracting data purpose.

Scroll for More Useful Information and Relevant FAQs

Источник

Object of class mysqli_result could not be converted to String

Basically, the error Object of class [Class name] could not be converted to string will raise whenever we try to use an object as a string.

Читайте также:  Run python script in python command line

For example, Suppose we have stdclass as below

$student = new stdClass(); $student->name = "John"; $student->id = 123;

Now we are going to treat the object $student as a string. Therefore let’s say we print as below

Result: Object of class stdClass could not be converted to a string

And the same issue occurred once we try to use mysqli_query returned result as a string rather than an object

Let’s see the following code

$servername = "localhost"; // Specify your server Host/IP address here if not localhost $username = "username"; // Replace your Database username here $password = "db_pwd"; // Replace your Database password here $db= "demo"; //Replace your database name here $mysqli = new mysqli($servername,$username,$password,$db); // Check connection if ($mysqli -> connect_errno) < echo "Failed to connect Database: " . $mysqli ->connect_error; exit(); > $resultSet = mysqli_query($mysqli, "SELECT * FROM tbl_employee"); echo "Employee:". $resultSet;

Result: PHP Catchable fatal error: Object of class mysqli_result could not be converted to string

Explanation:

  • Here function mysqli_query is used to perform a specified query to the database.
  • As per mysqli_query definition, it will return FALSE on failure
    and mysqli_result object on the success of SELECT Query.
  • In our case, it returns a result object and we have tried to print this result object therefore it complains.

Now let’s understand how to fetch database records and use them as strings. Find following Mysqli functions demonstrating for extracting data purpose.

Scroll for More Useful Information and Relevant FAQs

Источник

Ошибка PHP / MYSQL: объект класса mysqli_result не может быть преобразован в строку

Я только начал изучать MySQL вместе с PHP (основы), и я застрял на 2 дня с этой ошибкой.
У меня есть HTML-код:

Я просто пытаюсь получить имя пользователя из базы данных, используя этот код:

query("SELECT Name FROM users WHERE >Это то, что я получаю в результате в веб-браузере.
Username: Recoverable fatal error: Object of class mysqli_result could not be converted to string in /storage/ssd3/749/7441749/public_html/index.php on line 7 

Теперь после того, как результат, который я получаю — это Object, но я не знаю, как преобразовать его в строку, используя PHP.
Кто-нибудь знает, как это исправить? Чтобы преобразовать объект в строку.

Читайте также:  Сортировка внутри foreach php

Я попытался использовать функцию print_r, но у меня ничего не вышло. Я нашел очень мало информации об этом. Кроме того, это моя структура базы данных, если вам нужна какая-то информация (думаю, это может оказать влияние, не знаю ): http://prntscr.com/l5xu9n

Решение

$var в вашем коде на самом деле объект типа mysqli_result ,

На самом деле это дескриптор набора результатов, и вы должны выгружать результаты из этого дескриптора, используя какой-то вид fetch ,

query("SELECT Name FROM users WHERE now get the result row $row = $result->fetch_assoc(); // row will be an array ?> 

Теперь в вашем HTML вы можете сделать это

Другие решения

Вы должны получить свой результат следующим образом:

query("SELECT Name FROM users WHERE < $var = $result->fetch_object(); $result->close(); > ?> 

Источник

Класс mysqli_result

Представляет результирующий набор, полученный из запроса в базу данных.

Обзор классов

public fetch_object ( string $class = «stdClass» , array $constructor_args = [] ): object | null | false

Свойства

Сохраняет буферизованный или небуферизованный результат в виде целого числа ( int ) ( MYSQLI_STORE_RESULT или MYSQLI_USE_RESULT соответственно).

Список изменений

Версия Описание
8.0.0 Класс mysqli_result теперь реализует интерфейс IteratorAggregate . Ранее вместо него был реализован интерфейс Traversable .

User Contributed Notes 7 notes

Converting an old project from using the mysql extension to the mysqli extension, I found the most annoying change to be the lack of a corresponding mysql_result function in mysqli. While mysql_result is a generally terrible function, it was useful for fetching a single result field *value* from a result set (for example, if looking up a user’s ID).

The behavior of mysql_result is approximated here, though you may want to name it something other than mysqli_result so as to avoid thinking it’s an actual, built-in function.

function mysqli_result ( $res , $row , $field = 0 ) <
$res -> data_seek ( $row );
$datarow = $res -> fetch_array ();
return $datarow [ $field ];
>
?>

Implementing it via the OO interface is left as an exercise to the reader.

Читайте также:  Php session data directory

Switching from Php5 to Php7, especially if you have worked on an ongoing, long term project, it is unfortunate that there is no mysqli_result function.

So, this may be helpfull and you can call this function as you wish. I assume you do restricted search (searching for single row or few rows only).

function mysqli_result($search, $row, $field)$i=0; while($results=mysqli_fetch_array($search))if ($i==$row)
$i++;>
return $result;>

$search=mysqli_query($connection, «select name from table_name where «);
$name=mysqli_result($search, 0, «id»);

An «mysqli_result» function where $field can be like table_name.field_name with alias or not.
function mysqli_result ( $result , $row , $field = 0 ) if ( $result === false ) return false ;
if ( $row >= mysqli_num_rows ( $result )) return false ;
if ( is_string ( $field ) && !( strpos ( $field , «.» )=== false )) $t_field = explode ( «.» , $field );
$field =- 1 ;
$t_fields = mysqli_fetch_fields ( $result );
for ( $id = 0 ; $id < mysqli_num_fields ( $result ); $id ++) if ( $t_fields [ $id ]-> table == $t_field [ 0 ] && $t_fields [ $id ]-> name == $t_field [ 1 ]) $field = $id ;
break;
>
>
if ( $field ==- 1 ) return false ;
>
mysqli_data_seek ( $result , $row );
$line = mysqli_fetch_array ( $result );
return isset( $line [ $field ])? $line [ $field ]: false ;
>
?>

Generally, it appears Mysqli OO vs Procedural style has no significant difference in speed, at least with the more generally used functions and methods (connect, close, query, free, etc).

With the fetch_* family of functions and methods dealing with result rows, however, Procedural wins out. Averaging over a hundred or so tests with a result set of 180,000 records, and using mysqli_fetch_*() functions vs. their mysqli_result::fetch_*() counterpart object methods to read and iterate over all records, all of the mysqli_fetch_*() functions win by ~0.1 seconds less.

This is interesting considering we’re dealing with the same result object in both styles.

This was using Vistax64, PHP5.3.2, Mysql 5.1.45, using a bit of this code:

// procedural — takes 0.1 seconds less than OO here
$stopwatch = microtime ( true );
while( $row = mysqli_fetch_assoc ( $result )) ++ $z ;
>
echo microtime ( true ) — $stopwatch ;

// OO
$stopwatch = microtime ( true );
while( $row = $result -> fetch_assoc ()) ++ $z ;
>
echo microtime ( true ) — $stopwatch ;

Источник

Оцените статью