-1

I am writing a custom plugin and calling the plugin functions using short codes on my wordpress page.

global $db_handle;

below declares the handle to the class 'DBController' global.

if (isset($db_handle))

always returns False.Not able to figure out why. I must also clarify that I am calling "[connect_database]" first and then calling "[load_dropdown content='customer']" Any help is appreciated! The full code is below:

global $db_handle;

function vc_connect_to_database()
{
    require_once("dbcontroller.php");       # Instantiate DB COntrolling functions 
    $db_handle = new DBController();
    $connection = $db_handle->connectDB();
    if (!$connection)
    {
        return 'Unable to connect to database';
    } 
    else
    { 
        return '<script>alert("Connected to the database successfully.")</script>';
    #       return '<h6>"Database connect successful. This is where the customers list will appear"</h6>';  
    }   
}

function vc_load_dropdown($atts, $content=null)
{
    $atts = shortcode_atts( array('content' => 'customer'), $atts );
    if ($atts[ 'content' ] == 'customer')
    {
        $query = 'SELECT CustomerID, FirstName, LastName FROM customers ORDER BY FirstName, LastName';
        if (isset($db_handle))
        {
            return 'DB Handle is available';
        }
        else
        {
            return 'DB Handle is NOT available';            
        }
#       $results = $db_handle->runQuery($query);
    } 
}

add_shortcode('load_dropdown', 'vc_load_dropdown');
add_shortcode('connect_database', 'vc_connect_to_database');
  • Added a general wordpress answer about what you are trying to do, but downvoting the question as it is an obvious very basic PHP issue that do not relate in any way to wordpress. – Mark Kaplun Aug 6 '17 at 7:01
1

Your core problem is that you are using two shortcodes. shortcodes are not a programing language and should not be used as such. Shortcode should generate HTML in a consistent self contained way. If a shortcode A can not work without having shortcode B in the content as well, it is a sign you are doing it wrong.

From the coding POV, you should never ever never ever use global variables. If you need to cache some resource, use an accessor function which store the value as a static and initializes it only when needed. In addition you do not use good prefixes to your functions which make collision with core and other plugin a likely eventuality, but really, instead for trying to figure out good prefix, just use name spaces.

  • Thanks Mark. I will make some changes as suggested. Basically... 1. Contain the full functionality in one shortcode 2. Avoid Globals Let me repost when done. – Vivek Aug 6 '17 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.