How to access variable from an included page?

2019-08-10 11:43发布

I'm using some "beginner" masterpage-like in PHP, and I connect to the database from one page, but want to access it from an included page as well. I define the database variable above the include call, so there shouldn't be any problem there.

Currently, when including the page and checking if the variable is set, it returns false. How can I accomplish such thing instead of re-connecting in every include?

index.php

$db = new mysqli("HOST", "USERNAME", "PASSWORD", "DB");
include 'page2.php';

page2.php

if(isset($db))
    echo 'set';
else
    echo 'not set'; // this will be called

标签: php
2条回答
仙女界的扛把子
2楼-- · 2019-08-10 12:11

Update your page2.php like this. Hope your code will work fine now.

if(!($db->connect_error))
    echo 'connected';
else
    echo 'Not connected'; 
查看更多
甜甜的少女心
3楼-- · 2019-08-10 12:22

This should come like this

index.php

include 'page2.php';
if(isset($db))
    echo 'set';
else
    echo 'not set'; // this will be called

page2.php

$db = new mysqli("HOST", "USERNAME", "PASSWORD", "DB");

Include in php

查看更多
登录 后发表回答