将变量传递到包含的PHP文件中以用作MySQL查询

时间:2012-05-07 20:46:39

标签: php mysql variables include

我无法将两个变量传递到包含文件中。

可见页面:

<?php

$sqlCount = "This is a working MySQL query.";
$sqlQuery = "This is also a working MySQL query.";

include("include.php");

?>

include.php:

<?php

$result = mysql_query($sqlCount, $conn) or trigger_error("SQL", E_USER_ERROR);
//$result populates variables to be used in second portion of code
//don't need $result anymore

$result = mysql_query($sqlQuery, $conn) or trigger_error("SQL", E_USER_ERROR);
//rest of my code

?>

当我不包含它时,代码在可查看的PHP页面中工作。当我将$ sqlCount和$ sqlQuery移动到include.php。

时,它也有效

我能找到的唯一真正的解决方案是将它们声明为全局变量,但是当我尝试它时它没有做任何事情。

编辑:我想通了。 $ sqlQuery在查询中包含了直到include.php文件内部才创建的变量。

2 个答案:

答案 0 :(得分:0)

在我看来,更好的方法是将“include.php”中的代码重写为可以从“可查看页面”调用的函数:

include.php

<?php
function included_function($sql_count, $sql_query)
{
    $result = mysql_query($sql_count, $conn) or trigger_error("SQL", E_USER_ERROR);
    //$result populates variables to be used in second portion of code
    //don't need $result anymore

    $result = mysql_query($sql_query, $conn) or trigger_error("SQL", E_USER_ERROR);
    //rest of my code
}
?>

“可见页面”

<?php
include("include.php");

$sqlCount = "This is a working MySQL query.";
$sqlQuery = "This is also a working MySQL query.";

included_function($sqlCount, $sqlQuery);

?>

答案 1 :(得分:0)

你试过

吗?

include.php:

<?php

echo $sqlCount; die();   // just to be sure you have what you expect?
$result = mysql_query($sqlCount, $conn) or trigger_error("SQL", E_USER_ERROR);