Kenny Kenny - 4 months ago 8
PHP Question

Can't call a function from another script because of a var is local

I got a problem that is same as the subject, here is the codes.

Script A:

$con = mysqli_connect('localhost', 'root', '', 'mysql');


The above works fine so I exclude the die() clause here for everyone easiler to read.

Script B:

function get_news(){
/* a select query */
$result = mysqli_query($con, $news_sql)
or die(mysqli_error($con);
/* other codes follow */
};


Script C:

require_once "Script B";
get_news();


The above fail and after some testings, I confirmed that the problem lies on the var $con in Script B.

There are at least 2 ways to solve this:

a) replace $con with mysqli_connect();
b) define $con again within the function in Script B

Although this solve my problem but seems that both are not good practice. Should I define the $con as a $_global var? Would you please suggest other better approach.

Thanks a lot!

Original code of Script B:

function get_news(){
$news_sql = "SELECT * from pink_news ORDER BY news_id DESC LIMIT 3";
$result = mysqli_query($con, $news_sql)
or die(mysqli_error($con));
while ($rows = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<div class='news'><ul><li>";
echo "<img src='" . $rows['img'] . "'>";
echo "<h2>" . $rows['headline'] . "</h2>";
echo "<p>" . $rows['content'] . "</p>";
echo "</li></ul></div>";
};
};

Answer

include script A to you page

include 'connection.php';

Then pass $con to your function as

get_news($con);// pass connection to your function

And in script B use it as

function get_news($con){
Comments