在学校,我的老师告诉我很多关于使用POSTGRES DATABASE进行PHP编码的事情。 但是当我开始使用MYSQLI服务器时,我无法做很多事情。
首先是功能。 我的老师告诉我要做这种功能
$rows = getBuildings();
if (count($elenco) == 0) {
print "<hr> No buildings here </hr>";
} else {
?>
<thead>
<tr>
<th>address</th>
<th>town</th>
<th>Manager</th>
</tr>
</thead>
<tbody>
<?php
foreach ($elenco as $riga) {
?>
<tr>
<td> <?= $row->address ?></td>
<td> <?= $row->town ?></td>
<td> <?= $row->name ?> <?= $riga->surname ?> </td>
</tr>
<?php
}
?>
</tbody>
</table>
</tbody>
</table>
<?php
}
?>
</body>
</html>
<?php
function getBuldings() {
global $db;
$sql = "select * from buildings, boss
where boss.codBo=buildings.codBu";
$rows = array();
if (!DB::isError($tab = $db->query($sql))) {
while ($row = $tab->fetchRow(DB_FETCHMODE_OBJECT)) {
$rows[] = $row;
}
} else {
die("ErrorSQL:" . $tab->getMessage());
}
return $rows;
}
?>
但要让它在MYSQL中工作,我必须做很多改变。实际上在!BD :: isError中有一个错误。我不得不从这一个
更改connection.php<?php
Session_Start();
require_once("DB.php");
$db = DB::connect("pgsql:etc....");
if (DB::isError($db)) {
die("Error: " . $db->getMessage());
}
?>
到这个
<?php
$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test";
// Create connection
$db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$a = mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "Connected successfully " . $a . " ";
?>
为了显示查询结果,我的代码变成了这样:
<body>
<?php
$rows = getBoss();
if (count($rows) == 0) {
print "<h2>No Boss here</h2>";
} else {
foreach ($rows as $row) {
print "<p>" . $row['name'] . "</p>";
print "<p>" . $row['surname'] . "</p>";
}
}
?>
<?php
function getBoss() {
global $db;
$sql = "select *
from test_boss
order by name, surname";
$rows = array();
if ($tab = $db->query($sql)) {
while ($row = $tab->fetch_array()) {
$rows[] = $row;
}
return $elenco;
} else {
die("Errore sql: " . $tab->getMessage() . ":" . $sql);
}
}
?>
</body>
</html>
实际情况相当不错,但我不得不将FETCH_ROW更改为FETCH_ARRAY。 我再也无法使用从$ rows值发布数据的方法。
<?= $row->name ?>
因为有错误
注意:尝试获取非对象的属性
但我不得不使用
print "<p>".$row['name']."</p>";
如何正确使用FETCH_ROW方法?
答案 0 :(得分:0)
您可以通过稍微调整代码来将数组类型转换为对象。
如果你想以$row->name
的形式检索一个对象,那么你的代码就是。
while ($row= $tab->fetch_array()) {
$rows[] = (object)$row;
}
OR
while ($row= $tab->fetch_object()) {
$rows[] = $row;
}