【问题标题】:require_once not working to external filerequire_once 不适用于外部文件
【发布时间】:2015-03-11 19:57:23
【问题描述】:

我有一个页面,我正试图从 msqsql 数据库中提取数据。我让它与这个网站上的一些人一起工作。我试图将连接变量的位置更改为 tp 指向配置文件。\,我什至没有收到错误消息。我有另一个文件使用 require_once 指向同一个配置文件,它工作正常,但它是一个更复杂的字符串。我以为我可以复制 require_once 以在我的页面上设置它,但我错过了一些东西。

我的页面示例有效,但我不希望在此页面上直接连接字符串。

/*连接链接*/

<?php

$link = mysqli_connect("xxx.xxx.xxx.xxx", "un", "pw", "db");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$type = "mixers";

/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT record_number, Base_Price FROM Products
WHERE Unit_Product='u'")) {

/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $type);

/* execute query */
mysqli_stmt_execute($stmt);

/* bind result variables */
mysqli_stmt_bind_result($stmt, $product, $price);

/* fetch value */
while(mysqli_stmt_fetch($stmt)) {     
$products[$product] = $price;    }



/* close statement */
mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);

?>

<?php echo $products['1014']; ?>

以下是使用 require_once 的零件页面示例。我试图复制整个代码,然后我将其配对,但我什至没有收到错误。

        <?php

ini_set('display_errors',1); 
error_reporting(E_ALL);
require_once('./inc/functions.php');

if(isset($_REQUEST['catid']) && is_numeric($_REQUEST['catid'])) {
$cat_rn = $_REQUEST['catid'];
display_category($cat_rn);
} else {
echo 'Invalid catid provided. <a href="/">Return Home</a> try something like 
<a href="'.$_SERVER['PHP_SELF'].'?catid=140">'.$_SERVER['PHP_SELF'].'?catid=140</a>';

}

function display_category($cat_rn) {
    require_once('./inc/db_config.php');
    require_once('./inc/functions.php');
    $con = mysql_connect($catdb['host'],$catdb['user'],$catdb['pass']);
    if (!is_resource($con))
    {
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db($catdb['dbname'], $con);

任何帮助将不胜感激。我知道 php,但我学到了很多东西。 -迈克尔

【问题讨论】:

  • 您可能应该通过编辑您的问题来添加文件的所有路径。

标签: php require-once


【解决方案1】:

您正在使用require_once()。 “一次”的范围是 UNIVERSAL。只要您在脚本中的任何位置require_once() 该文件,同一文件的所有其他 require_once() 都将变为无 OPS 并跳过该文件:

inc.php:

<?php
echo 'hello';

script.php:

<?php
require_once('inc.php');   // runs, prints "hello";

function foo() {
   require_once('inc.php'); // require SKIPPED because file already included
}

foo();

上面的代码只会打印一次hello

如果您想多次包含/要求该文件,则不能使用 _once() 变体。

【讨论】:

  • 还可能值得注意的是,对于像function.php 这样的文件,在全局范围内以及在其他地方包括该文件都会导致致命错误,因为函数已经定义并且不能重新-defined 这就是为什么通常使用 require_once 的原因。
猜你喜欢
  • 2013-06-15
  • 1970-01-01
  • 2019-05-27
  • 2020-05-15
  • 2023-03-29
  • 2015-12-16
  • 2017-03-02
  • 2012-10-27
  • 1970-01-01
相关资源
最近更新 更多