0

I created a simple function that needs to display some information.

Some of this information comes from the database.

But, the database handler is not recognized within this function, therefor, I get the following errors:

Notice: Undefined variable: db in censored\controller\edit_mails.php on line 82

Fatal error: Call to a member function get_results() on null in censored\controller\edit_mails.php on line 82

I'm using the ezSQL database handler

The function:

function MessageSelector() {
$emails = $db->get_results("SELECT * FROM settings_emails WHERE cat = '$edit_type'" );
if(empty($emails)) {
//There are no messages to select
        } 
else { 
        //Create an option for each message
        foreach ($emails as $email):  
            echo "<option value=\"", $email->title , "\" onclick=\"location.href='edit_emails.php?x=", $edit_type , "&mail=",$email->id,"';\">", $email->title , "</option>";
        endforeach;
        ";}  
}

Database Handler:

require_once ADMIN_DB_DIR . '/ez_sql_core.php';
require_once ADMIN_DB_DIR . '/ez_sql_mysql.php';
global $db;
$db = new ezSQL_mysql($dbuser, $dbpassword, $dbname, $dbhost);

1 Answers1

1

Pass in $db as a parameter into your function for it to be used in the scope of the function.

Also, you have some weirdness in your foreach. Concatenate normally and don't forget to define $edit_type

function MessageSelector($db) {
     $emails = $db->get_results("SELECT * FROM settings_emails WHERE cat = '$edit_type'" );
     if(empty($emails)) {
           //There are no messages to select
     } else { 
        //Create an option for each message
        foreach ($emails as $email) {  
            echo "<option value=\"". $email->title . "\" onclick=\"location.href='edit_emails.php?x=". $edit_type . "&mail=" . $email->id . "';\">". $email->title . "</option>";
        }
     }  
}
David Wyly
  • 1,671
  • 1
  • 11
  • 19
  • i added: global $db; global $edit_type; that solved the problem –  Apr 29 '16 at 23:35
  • @HiddeKat Using globals is what's considered to be a "code smell"; or in other words, a powerful indicator that something is seriously wrong. If I were you, I would *always* pass what you need, as you need it. Globals are extremely difficult to debug in a large application and can quickly grow out of control, creating a maintenance nightmare. You want your code to be as modular and as loosely coupled as possible, every time, no exceptions, and capable of working regardless of external influences. Consider yourself warned. – David Wyly Apr 30 '16 at 14:14