Help with creating new function

Hello mates! I am new to PHP.

I tried to create a new function. When I launch it, it doesn’t show up anything. This is my code

<?php
//include the code to connect to database
include_once $_SERVER['DOCUMENT_ROOT'] . '\\includes\\db.php';
//create new function
function alljokes()
{    
global $pdo;    
try
 {        
$result = $pdo->query('SELECT joketext FROM joke');   
 }    
catch (PDOException $e)
 {       
 $error = 'Cannot display jokes: '. $e->getMessage();      
  include $_SERVER['DOCUMENT_ROOT'] . '\\includes\\error.php';        
exit();  
  }    
$row = $result->fetch();    
return $row[0];
}
echo 'Here are all jokes: ';
alljokes();

Here’s the output :frowning:

Hi aakashekhar,

Your function alljokes() returns data, so you have to echo the return value from the function to output it to the screen:

echo alljokes();

You must have a error because the line:

echo 'Here are all jokes: ';

should be echoed even if he doesnt echo his function return.

My guess is in the file path to db.php you are using \ instead of /. In php \ indicates a namespace.

Also if you turn on error reporting you should see exactly what is going wrong and where it is happening.


error_reporting( E_ALL );
ini_set( 'display_errors', 'on' );

First of all, never have exit into your functions/methods. Functions are made to do or return stuff.
iamjone, that string is echo(ed), if you click the image.


<?php
function alljokes() {
    global $pdo;
    try {
        $result = $pdo->query('SELECT joketext FROM joke');
        $row = $result->fetch(); 
    } catch (PDOException $e) {
        throw new Exception( $e->getMessage() );
    }
    return $row;
}

echo 'Here are all jokes:<br />';
try{
    echo '<pre>', alljokes(), '</pre>';
} catch(Exception $e) {
    echo 'SQL Error '.$e->getMessage();
}
?>

Even better, you can create a class.

If you look at the screenshot in the OP, it does output ‘Here are all jokes:’

My bad, I never click attachments at work, assumed it was a blank screen.