[英]PHP MYSQLI fetch Errors
在学校里,我的老师告诉我很多有关使用POSTGRES数据库进行PHP编码的知识。 但是,当我开始使用MYSQLI Server时,我无法做很多事情。
首先是功能。 我的老师告诉我要做这种功能
$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方法,我该怎么办?
您可以通过略微调整代码,将数组类型转换为对象。
如果要检索$row->name
形式的对象,则代码将是。
while ($row= $tab->fetch_array()) {
$rows[] = (object)$row;
}
要么
while ($row= $tab->fetch_object()) {
$rows[] = $row;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.