【发布时间】:2018-09-18 20:05:15
【问题描述】:
我正在尝试做一些相当复杂的事情,但我希望它在文本中有意义。
所以我在一个页面上有一个链接可以带我到post.php?postid=3
在我的数据库中有一个名为camp_id 的整数字段。例如,当我的帖子中的字段 camp_id 的值为 1 时,我想显示该字段中值为 1 的表中的所有内容。
如果我将 URL 更改为 post.php?postid=2 并且该帖子的 camp_id 为 4,我将显示 camp_id 为 4 的所有内容的列表。
下面是我的代码和底部的当前错误。
这是我的功能:
public function getartfromcamp($campid)
{
$con = $this->db->OpenCon();
$campid = $con->real_escape_string($campid);
$stmt = "SELECT * from post WHERE camp_id = '$campid'";
$relatedlinks = $con->query($stmt);
if ($relatedlinks->num_rows > 1) {
$sql = $relatedlinks;
} else {
$sql = "No article";
echo "";
}
$this->db->CloseCon();
return $sql;
}
这是页面上的代码:
include 'postclass.php';
$postid = $_GET['postid'];
$article = new Post();
$relatedlinks = $article->getartfromcamp($postid);
?>
<div class='row'>
<?php
while ($row = $relatedlinks->fetch_assoc()) {
?>
<ul>
<ul>
<li><a href="postview.php?postid=<?php echo $row['article_id'];?>"><?php echo $row['article_name'];?></a></li>
</ul>
它似乎与 postid=1 一起使用,但是当我将其更改为其他内容时,我收到以下错误:
致命错误:未捕获错误:调用成员函数 fetch_assoc() 在字符串中 C:\inetpub\wwwroot\local.test.co.uk\blog-example\camp1.php:18 堆栈 跟踪:#0 {main} 投入 C:\inetpub\wwwroot\local.test.co.uk\blog-example\camp1.php 第 18 行
第 18 行:
while ($row = $relatedlinks->fetch_assoc()) {
【问题讨论】:
-
在函数 getartfromcamp 中,当没有结果时,您将返回 $sql 字符串,而不是 db 链接。在这种特殊情况下,没有结果,因此返回字符串。所以它会抛出错误,因为你试图在一个字符串上运行 fetch_assoc
-
????:“看起来您正在编写自己的 ORM。您是否考虑过使用已经编写、测试和广泛支持的 ORM,例如 RedBeanPHP、Doctrine、@987654323 @ 或Eloquent?”
-
警告:使用
mysqli时,您应该使用parameterized queries 和bind_param将用户数据添加到您的查询中。 请勿使用手动转义和字符串插值或连接来完成此操作,因为您将创建严重的SQL injection bugs。意外未转义的数据是一个严重的风险。使用绑定参数不那么冗长,并且更容易检查以检查您是否正确执行。