I’m working on a forum software currently.
I have a class called User, within that class I have a method called GetUserGroup to determine what group the user is in.
I am running the query and assoc the same way I’ve been doing with all my other queries, I’m not sure what I’m doing wrong, I’ve looked over the query for syntax errors but just don’t see any.
Catchable fatal error: Object of class User could not be converted to string in C:\xampp\htdocs\forums\index.php on line 22
Here’s the whole page:
<?php
include_once('connect.php');
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
class User {
public $usergroup;
public $user;
function __construct() {
if (isset($_SESSION['username'])) {
$this->user = $_SESSION['username'];
}
}
public function GetUserGroup() {
$find_group = "SELECT group FROM users WHERE username='$this->user'";
$run_find_group = mysql_query($find_group);
$find_group_assoc = mysql_fetch_assoc($run_find_group);
$this->usergroup = $find_group_assoc['group'];
}
}
class Forum {
function __construct() {
}
public function DisplayForums() {
$find = "SELECT id,name,description FROM forums";
$run_find = mysql_query($find);
while ($is = mysql_fetch_assoc($run_find)) {
$forum_id = $is['id'];
$forum_name = $is['name'];
$forum_description = $is['description'];
echo "<div style='background:#FF6699;width:1000px;'>";
echo "Forum: <a href='topics.php?t='$forum_id'>".$forum_name."</a><br/>".$forum_description."<br/><hr>";
echo "</div>";
}
}
}
$forum = new Forum();
if (isset($_SESSION['username'])) {
$_SESSION['username'] = new User();
$_SESSION['username']->GetUserGroup();
}
?>
<html>
<head>
<title>Home</title>
</head>
<body>
<?php
if (isset($_SESSION['username'])) {
echo "Welcome, " . $username . "!";
if ($_SESSION['username']->usergroup==admin) {
echo "<span align='right'><a href='/admin/index.php'>Admin CP</a></span>";
}
$forum->DisplayForums();
} else {
$forum->DisplayForums();
echo "
<form action='login.php' method='post'>
<table>
<tr>
<td>Username: </td>
<td><input type='text' name='username' /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type='text' name='password' /></td>
</tr>
<tr>
<td><input type='submit' name='login_submit' value='Login' /></td>
</tr>
</table>
</form>";
}
?>
</body>
</html>
Your problem is here:
You’re assigning a
Userobject to the$_SESSION['username']. So, when$_SESSION['username']->GetUserGroup()is called$this->useris a User object.You need to either set
$_SESSION['username']to the username, and not an object. Or make a method to get the username from the object. You should add agetUsernamemethod or something toUser.You can also use PHP’s
__toStringmethod.If you use
__toString, then:will work.