Showing error to user

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
godflesh
Forum Newbie
Posts: 3
Joined: Thu Mar 20, 2014 5:23 am

Showing error to user

Post by godflesh »

I have trying to solve this for some time, even too long and I would really appreciate the help of experienced PHP user.


I have made that user can see the list of the other members on the website but I also want to show error message if something goes wrong.



I did it with try-catch block but I also been wondering if there is an efficient way to do that.


I would also like to know how to make the error to happen because I need to make a print screen for documentation.

Code: Select all

//function that takes username and avatar 
function take_username_avatar()
{
    try{
    $results = array();
    $query = mysql_query("SELECT  username,avatar FROM data WHERE username!='{$_SESSION['username']}'")or die(mysql_error());
    while($row = mysql_fetch_assoc($query))
    {
        $results[] = $row;
    }
        
        return $results;
    }  
    catch (Exception $e){
      die("Error  showing user list");
    }
        
}

Code: Select all

//page that shows user list
$username_avatar = take_username_avatar();


foreach ($username_avatar  as $user_avatar ) {
  
        ?>
        <p><a href='index.php?page=profile& username =<?php echo $user_avatar  [' username ']; ?>'>
        <?php echo $kor_avatar[' username '] ?></a></p>
        <a href='index.php?page=profile&username=<?php echo $ user_avatar ['korisnickoime']; ?>'>
            <img src="avatar/<?php echo $kor_avatar['avatar']; ?>" height='100' width='100' alt='avatar'></a>
        <?php
    }
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Showing error to user

Post by social_experiment »

:idea: use the PHP Code button for php code; formats it way better :)

you are using the try-catch block incorrectly; first you need to create some type of condition, and if that is not met, throw an exception. You also have to use the method $e->getMessage() to display the error message.

Code: Select all

<?php
 try {
   // something happens here
 }
 catch (Exception $e) {
   // something didn't happen
   echo $e->getMessage();
 }
?>
In your function below, ( take_username_avatar() ), the catch statement wouldn't execute in case there is a problem with the query because you are using the die() function. Rather than expose information about the webserver try and use different ways of coping with errors

Might be useful reading
Error handling, Auditing, Logging
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply