php - 在 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查询单独工作。
提前致谢!
解决方案
你不是在呼应这个价值。尝试这个:
<tr>
<td><?= $object->field1 ?></td>
<td><?= $object->field2 ?></td>
</tr>
推荐阅读
- c# - 后面带标点的单词怎么找?
- salesforce - 使用 Docusign 发送 Salesforce 附件
- c# - 对象具有附加属性 ActionContext 等
- android - 存储访问框架 - 无法在使用 ACTION_OPEN_DOCUMENT_TREE (NextCloud) 选择的云文件夹中创建文件
- android - 从应用程序收到错误 -32000:无法在引擎中运行配置。#扑
- amazon-web-services - AWS 网络负载均衡器无法获取客户端 IP
- python - 最后 10 行的列中的最大值
- mysql - MySQL如何创建一个用日期格式化的自定义id列?
- reactjs - 如何使表单输入和按钮避免在移动设备上使用键盘?
- c# - 使用 GIT 丢失 Unity 可编写脚本的对象引用