I am trying to use Class with Public Function and my query is coming back with following error:
"Notice: Undefined variable: articles in C:\xampp\htdocs\CMS\index.php on line 21"
I have done a print_r to show the result from class and everything looks correct.
"Array ( [0] => Array ( [article_id] => 1 [article_title] => Title [article_content] => Content [article_timestamp] => 2019-02-02 13:33:03 ) )"
On my class function, I have tried placing the query into variable then return that variable out of class, but error message.
If I bypass the class function, and place the query result into $Articles
then it works.
line 1-6 /Index.php
<?php
include_once('includes/article.php');
$Article = new Article;
$Articles = $Article->fetch_all();
print_r($Articles)
?>
line 17-21 /Index.php
<?php foreach ($articles as $article) { ?>
<ol>
<li><a href="article.php?id=<?php echo $article['article_id']; ?>"><?php echo $article['article_title']; ?></a> - <small><?php echo date('l F jS, Y', strtotime($article['article_timestamp'])); ?></small></li>
</ol>
<?php } ?>
line 5-8 /includes.php
class Article {
public function fetch_all() {
return DB_query("SELECT * FROM articles");
}
}
line 51-70 /includes.php
function DB_query($query, $params = []) {
$conn = DB_connect();
if ($params)
{
$stmt = $conn->prepare($query);
$types = str_repeat('s', count($params));
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = mysqli_query($conn, $query);
}
if ($result)
{
$result = mysqli_fetch_all($result,MYSQLI_ASSOC);
return $result;
} else {
return mysqli_affected_rows($conn);
}
}
The Result should be echo $article['article_id']
will return ID, echo $article['article_title']
will return title and finally echo date('l F jS, Y', strtotime($article['article_timestamp']))
will return date.