Page 1 of 1

Showing error to user

Posted: Thu Mar 20, 2014 5:26 am
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
    }

Re: Showing error to user

Posted: Thu Mar 20, 2014 11:57 am
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