fetch_assoc returning garbage

Hi everyone,

I’ve built an upload system, so when the administrator uploads a PDF file it gets listed on a page in the backoffice.

However, when I upload the PDF file I get weird results.

Page where I’m listing PDF’s and calling function:


...
$pdfs = $queries->getList();
if(is_array($pdfs)){
    foreach($pdfs as $pdf){
        echo "<span class=\\"alertgray\\"><strong>Title:</strong></span><span>".$pdf['title']."</span>";
}
}

Queries.class.php file - getList function:


public function getList() {
    $populate = new Populate();
		
    $query = "SELECT *
		FROM pdfs
		ORDER by date DESC LIMIT 5";
				
    return $populate->pullListContent($query);
}

Populate.class.php file - pullListContent function:


function pullListContent($query){
    $result = $this->db->query($query);
    if($result)
        return $result->fetch_assoc();
    else
        return false;		
}

Output:
Title:3
Title:F
Title:0
Title:2
Title:M
Title:/

I only have one PDF on my database.

Everything worked great with:


return $result->fetch_all(MYSQLI_ASSOC);

But I can’t use that way because mysqli_result::fetch_all() function requires the MySQL native drivers and I can’t have it on my online server.

Any suggestions?

Thank you in advance!

Best regards.

Yeah, it’s kinda obvious you’ve switched from fetch all.

Fetch_Assoc pulls -1- entry.

So, your function returns 1 entry. The first entry. It’s an array of length 6 based on your output, because you’re pulling all fields of the table in your query.

Your code then takes that one array, and says “Foreach item in this array, define it as $pdf”. So each field you set as $pdf. Each field is NOT an array.

You then try to say $pdf[‘title’]. $pdf isnt an array. But it’s a string. PHP can interpret a string as an array. What character is at the numerical equivilant of ‘title’? Probably the first one, because a string converted to a number evaluates as 0.

So take a look at your table. I’m guessing the top entry when sorted by date has 6 fields. And those fields start with 3, F, 0, 2, M, and /, respectively.

Thank you for your help.

You were totally right.

I replaced my pullListContent function with:


...
while($row = $result->fetch_array()){
    $rows[] = $row;
}
return $rows;

it’s working.

Thank you