【问题标题】:Passing variables into an included PHP file to be used as MySQL queries将变量传递到包含的 PHP 文件中以用作 MySQL 查询
【发布时间】:2012-05-16 08:42:57
【问题描述】:

我在将两个变量传递到包含文件时遇到问题。

可见页面:

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

【问题讨论】:

  • 到底发生了什么?你说它不起作用,但你得到什么错误?
  • @Hamish 这是一个未定义的变量错误。
  • 听上去,这些变量可能不在范围内。这可能有很多原因。包含的文件是 AJAX 函数的一部分吗?包含的文件中$result 的深度是多少? $result 是否在可能在运行时解析的函数中?我会尝试在该包含文件的开头var_dump()ing 这些变量。
  • @jaypea07 出于好奇,尝试使用... include(dirname(__FILE__) . "/include.php");
  • @showerhead 不涉及 AJAX。第一个 $result 在 mysql_fetch_row() 中使用,第二个在 mysql_fetch_assoc() 中使用。

标签: php mysql variables include


【解决方案1】:

你试过了吗

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);

【讨论】:

    【解决方案2】:

    在我看来,更好的方法是将“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);
    
    ?>
    

    【讨论】:

    • 这不是真的。 PHP manual 说:“当一个文件被包含时,它包含的代码继承了包含发生的行的变量范围。调用文件中该行中可用的任何变量都将在被调用文件中可用,从指向前方。但是,包含文件中定义的所有函数和类都具有全局范围。"
    • 我的错,谢谢指出,我会马上修正我的答案
    猜你喜欢
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    相关资源
    最近更新 更多