1

i get an error when im trying to echo the name of the user.

Code for select

public function profile($username){
    $result = mysql_query("SELECT * FROM  " . PFX . "employees WHERE email ='$username'");
    $employee = array();
    while($rows = mysql_fetch_assoc($result)){
        $employee[] = $rows;
    return $employee;
    }
}

On page:

$employee = $user->profile($username);
<?php echo $employee['name']; ?>

I tried to print_r($employee); which outputted the following:

Array ( [0] => Array ( [id] => 4 [name] => Test Person...

So it does get the user from the database, but it cant echo only the name, can someone see where the error are?

I know the code isn't updated..

4 Answers4

2

As you can see on your print_r(), its still nested inside:

Array ( [0] => Array ( [id] => 4 [name] => Test Person...
         ^ another dimension inside.

So in accessing it:

$employee = $user->profile($username);
<?php echo $employee[0]['name']; ?>

Obligatory Note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Ref: https://stackoverflow.com/a/12860140/3859027

I suggest using PDO with prepared statements in this case:

public function profile($username)
{
    $db = new PDO('mysql:host=localhost;dbname=DB_NAME', 'username', 'password');
    $sql = 'SELECT * FROM ' . PFX . 'exmployees WHERE email = :username';
    $select = $db->prepare($sql);
    $select->bindParam(':username', $username);

    return $select->fetch(PDO::FETCH_ASSOC);
}

Then you can do this:

$employee = $user->profile($username);
<?php echo $employee['name']; ?>
Community
  • 1
  • 1
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • It's quite common to miss out the index of the rows. I had the same mistake before :) – Daniel Cheung Nov 23 '14 at 08:03
  • @MichaelWestergaard sure man glad this helped, i urge you to use PDO with prepared statements on this one as mysql is already deprecated and your current code is prone to sql injection since input its directly used inside the query statement. – Kevin Nov 23 '14 at 08:09
  • I know its not that secure etc. but it doesn't really need any security. – Michael Westergaard Nov 23 '14 at 08:12
0

Try this:

$employee[0]['name'];
Developer
  • 560
  • 4
  • 12
0

change your line to this. it will access the first record in $employee and then will print the name for first record

<?php echo $employee[0]['name']; ?>
Zohaib Aslam
  • 585
  • 1
  • 4
  • 15
0

Try this code

<?php echo $employee[0]."<br/>"; ?>
<?php echo $employee[1]."<br/>"; ?> 
<?php echo $employee[2]."<br/>"; ?>