2

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

可见页面:

<?php

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

include("include.php");

?>

包括.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 文件中才被创建。

4

2 回答 2

0

你试过了吗

包括.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);
于 2012-05-07T21:36:02.707 回答
0

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

包含.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);

?>
于 2012-05-07T21:16:16.573 回答