PHP, Mysqli, SQL query to get value and display others

时间:2018-09-18 20:05:16

标签: php mysql sql mysqli

I'm trying to do something fairly complicated but I hope it makes sense in text.

So I have a link on a page which take me to post.php?postid=3

In my database there is a a field which is integer called camp_id. When for example I'm on a post which has the field camp_id with a value of 1, I want to display everything in the table that has the value of 1 in that field.

If I change the URL to post.php?postid=2 and that post has a camp_id of say 4, I would display a list of everything that has a camp_id of 4.

Anyway here is my code below and the current error at the bottom.

Here is my function:

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;
}

Here is the code on the page:

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>

It seems to work with postid=1 but when I change it to something else I get the error below:

Fatal error: Uncaught Error: Call to a member function fetch_assoc() on string in C:\inetpub\wwwroot\local.test.co.uk\blog-example\camp1.php:18 Stack trace: #0 {main} thrown in C:\inetpub\wwwroot\local.test.co.uk\blog-example\camp1.php on line 18

Line: 18:

while ($row = $relatedlinks->fetch_assoc()) {

1 个答案:

答案 0 :(得分:1)

In function getartfromcamp, you are returning $sql string, instead of the connection object, when there is no result.

In this particular case, no result is coming, hence string is being returned. So it throws out error, as you are trying to run fetch_assoc on a string. You should let the function return connection object only, even if there are no rows being returned.

Change to following:

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);

    $this->db->CloseCon();

    return $relatedlinks;
}

SideNote: You should switch to Prepared statements, to prevent SQL injection related issues.