Jump to content

Getting my while function to loop dynamically from my switch statement.


Clandestinex337

Recommended Posts

Ok, so I have my function that shows all the rows in my db

 

	public function showAll()
	{
		$query = mysql_query("SELECT `username`, `password` FROM `user` ORDER BY `id` DESC");


		$arr = array(); 
		while($result = mysql_fetch_assoc($query)) 
		{ 
			$arr[] = $result;
			echo $result['username'] . '<br/>';
			echo $result['password'];
		}
	}

 

but with that I believe its going to be a pain and the wrong way to add a href= to them when I want to add links for them so I thought this way would work

 

	public function showAll()
	{
		$query = mysql_query("SELECT `username`, `password` FROM `user` ORDER BY `id` DESC");


		$arr = array(); 
		while($result = mysql_fetch_assoc($query)) 
		{ 
			$arr[] = $result;
			$this->username = $result['username'];
			$this->password = $result['password'];
		}
	}

 

but in my switch when I call everything

 

	case index:
		$user = new User($connect);
		$user->showAll();
		echo $user->getUsername() . '<br/>';
		echo $user->getPassword() . '<br/>';
	break;

 

it only shows the first row in the database..

 

Any idea on how I could make this work?

 

Thanks

 

The reason you only get two output is because you overwrite the value of $this->username and $this->password in every iteration of the loop.

 

I'm unsure of what exactly you want the links to be. Can you explain that a little better?

sorry, that makes sense.

 

I want to make it so that I am able to add links to the rows, and I thought it was bad practice to add html to functions. So I don't want t to add href's to the while loop and have to go into the function every time to change the links..

 

So I want to be able to call the rows through my switch similar to something like this

 

	case index:
		$user = new User($connect);
		$user->showAll();
		echo  '<a href="#">' . $user->getUsername() . '<a/>' . '<br/>';
		echo '<a href="#">' . $user->getPassword() . '<a/>' . '<br/>';
	break;

 

Thanks

You need to do something like this:

 

class User {

    public $users = array();

    public function getAll() {
        $query = mysql_query("SELECT `username`, `password` FROM `user` ORDER BY `id` DESC");

        while($result = mysql_fetch_assoc($query)) {
            $this->users[] = $result;
        }
    }

    // the rest of your User class code

}

 

and then in your switch:

 

case index:
    $user = new User($connect);
    $user->getAll();

    foreach ($user->users as $userInfo) {
        echo echo '<a href="#">' . $userInfo['username'] . '<a/><br/>';
        echo echo '<a href="#">' . $userInfo['password'] . '<a/><br/>';
    }	
break;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.