首页 > 解决方案 > 在 PHP 中什么都不返回时如何解决“$result->property”

问题描述

案子

因此,一旦我以非面向对象的方式学习了 PHP,我就决定转向它。

在进行简单查询时,我得到了查询返回的“行” ,但尝试访问其字段(列)似乎不起作用。

为了更清楚,我有这个PHP代码,我将结果显示在一个表格中:

<?php
    header("Content-Type: text/html;charset=utf-8");
    include 'connectDB.php';

    $connection = openConnection();

    //Query
    $query = "SELECT
                field1,
                field2
              FROM table";

//Check there are results
if($result = $connection->query($query)) {

       //get data
   while($object = $result->fetch_object()) {
   ?>
      <tr>
        <td><?php $object->field1 ?></td>
        <td><?php $object->field2 ?></td>
      </tr>

       <?php
   }

     closeConnection($connection);

  } else {
       echo '<tr><td>No info found.</td></tr>';
  }
?>

其中openConnection()closeConnection()是“connectDB.php”文件中的函数。这些都可以,但如果它是相关的:

function openConnection() {
    $dbhost = "localhost";
    $dbuser = "user1";
    $dbpass = "1234";
    $db = "myDatabase";
    $connection = new mysqli($dbhost, $dbuser, $dbpass,$db) or die(" Error while connecting: %s\n". $connection->error);

    return $connection;
}

function closeConnection($connection) {
    $connection -> close();
}

我试过的

我已经尝试过以下方法:

$object = mysqli_fetch_object($result)
$object = $result->fetch_result("newClass") // and created a new class

在选择字段时:

$object->returnData() //where this is a function that literally does return $this->field1

还检查了许多应该工作的PHP代码,并且与上面提到的第一个代码块相同。

结果:

我得到的结果是 9 行,这是查询应该返回的,但尝试访问<?php $object->field1 ?>只会留下一个空格。

如果我打开Web Inspector,里面实际上什么都没有<td>

截屏

额外:我在其最新版本 7.3.4 和 Bootstrap 4 上使用 XAMPP。

额外2: SQL查询单独工作。

提前致谢!

标签: php

解决方案


你不是在呼应这个价值。尝试这个:

<tr>
    <td><?= $object->field1 ?></td>
    <td><?= $object->field2 ?></td>
</tr>

推荐阅读