当前位置: 动力学知识库 > 问答 > 编程问答 >

php - 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>";

};

};

网友答案:

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){
网友答案:

Add require_once "Script A" to script B.. that should solve the problem

分享给朋友:
您可能感兴趣的文章:
随机阅读: