Alex
Alex

Reputation: 169

Mysqli - OOP implementation

[SOLVED]

I have two classes: DB class which is a Mysqli implementation and Users class.

User class have 2 functions: get user and get users.

public function get_user_data($email){
$query="SELECT * FROM users WHERE email='$email'";
$result= $this->mydb->runQuery($query);
return $result->fetch_array();
}

this function works with no problem. I call it like this:

$userData   = $users->get_user_data($email]);
$username = $userData['nickname'];

The problem is in the second function that gets all users:

public function get_users(){
$query="SELECT * FROM users ORDER BY time";
$result= $this->mydb->runQuery($query);
return $result->fetch_all();}

I use it like this:

$members = $users->get_users(); 
foreach ($members as $member) {
echo '<p>' . $member[1] . ' with email ' . $member[8]. '</p>';}

I want to call $members like in the first example, as members['email'] and not by order of the columns and i have read that fetch_all produce assosiative array but it doesnt work and i get an error. How should i change it so i can use it with the column names?

ANSWER: What i needed to do is just to explicitly write:

return $result->fetch_all(MYSQLI_ASSOC);

and then it works great,

Upvotes: 0

Views: 107

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157839

Instead of writing your own OOP implementation, first try to use a ready-made one.

Say, with my safeMysql class you will get the desired result with cleaner and safer code:

public function get_user_data($email)
{
    $query = "SELECT * FROM users WHERE email=?s";
    return $this->mydb->getRow($query, $email);
}

public function get_users()
{
    return $this->mydb->getAll("SELECT * FROM users ORDER BY time");
}

Upvotes: 1

Related Questions