Reputation: 129
Hey, I was following through a tutorial and was trying to simplify it to my needs. I cant get anything to work.. if unsure, some debugging tips would be great!
Here is the class.php file:
class MySQL{
public static function connect($set_host, $set_username, $set_password, $set_database){
mysql_connect("$set_host", "$set_username", "$set_password")or die("cannot connect");
mysql_select_db("$set_database")or die("cannot select DB");
}
}
class Posts {
public $id;
public $title;
function __construct($_id, $_title){
$this->id = $_id;
$this->title = $_title;
}
}
class Generate {
function queryPosts(){
$query = mysql_query("SELECT * FROM posts ORDER BY id DESC");
$postArray = array();
while ($row = mysql_fetch_assoc($query)){
$posts = new Posts($row["id"], $row['title']);
array_push($postArray, $posts);
}
return $postArray;
}
}
and here is the index:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>dev</title>
</head>
<body>
<?php
include ("class.php");
MySQL::connect('localhost', 'test', 'pass', 'table');
$blog = Generate();
foreach ($blog as $post)
{
echo $post->title . "<br/>";
}
?>
</body>
</html>
I really cant get anything to generate with this method. The table/data is there, and I can display them in a procedural manner.. however I am trying to get into oop methods of doing this. Knowing me it's probably a really silly syntax error. Many thanks!
Upvotes: 1
Views: 158
Reputation: 4637
As you may already know, @David's answer solves the problem quite well, however, since you said you were following a tutorial, I want to make you some recomendations so you don't go down into PHP's dark path.
queryPosts
method and not in the index.php fileHope I can help!
Upvotes: 0
Reputation: 100
Another thing why are you putting " before and after the variable. It should be: mysql_connect($set_host, $set_username, $set_password) or die("...");
Upvotes: 0
Reputation: 6798
You're not using the new keyword, and then you're trying to iterate on $blog which is an object. You need to call the object's method, queryPosts, and iterate over it's results.
...
$blog = new Generate();
$posts = $blog->queryPosts();
foreach ($posts as $post) {
...
Upvotes: 4
Reputation: 589
You should be instantiating Generate with new
:
$blog = new Generate;
foreach($blog->queryPosts() as $postArray){
}
Upvotes: 1