简体   繁体   English

如何从config.php获取值?

[英]how to get values from config.php?

Can I put a function in the file config.php ? 我可以在config.php文件中放置一个函数吗?

config.php : config.php:

<?php

$dbhost="localhost";  
$dbusername="user1"; 
$dbpassword="123456";
$dbname="dbname1"; 

$table_name="table1";

$db=mysql_connect($dbhost,$dbusername,$dbpassword) or die (mysql_error());
@mysql_select_db($dbname) or die (mysql_error());


function next_auto_increment(){
    $Result_auto_increment= mysql_query("SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$dbname' AND TABLE_NAME = '$table_name' ");
    $row_auto_increment=mysql_fetch_array($Result_auto_increment);
    $auto_increment = $row_auto_increment['AUTO_INCREMENT']; 
    return $auto_increment;
}

?>

then I call the func from other php like this : 然后我从其他php调用func,如下所示:

require_once "config.php";
$the_next_auto_increment = next_auto_increment();

but the function does not work ! 但是该功能不起作用!

if i put the function in the same php file, it works but in config.php not 如果我将功能放在相同的php文件中,则可以工作,但在config.php中不能

The $dbname and $table_name variables are not within the scope of the next_auto_increment function block. $ dbname和$ table_name变量不在next_auto_increment功能块的范围内。

You can pass them in as arguments: 您可以将它们作为参数传递:

function next_auto_increment($dbname, $table_name){
    ...
}    

Or you can use global to pull them into the scope: 或者,您可以使用global将它们拉入范围:

function next_auto_increment(){
    global $dbname;
    global $table_name;

    ...
}

I also need to state the obligatory, "you should be using PDO and not mysql_connect"! 我还需要说明强制性,“您应该使用PDO而不是mysql_connect”!

For one thing all the mysql_* functions are deprecated. 一方面,不建议使用所有mysql_ *函数。 I wouldn't use the mysqli_* functions either. 我也不会使用mysqli_ *函数。 Just PDO -- it is much safer to use and you don't have to worry about it being deprecated for many years to come. 只是PDO-使用起来更加安全,您不必担心它会在未来很多年内被弃用。

But, the point is, this alone can cause your script to fail and do nothing. 但是,重点是,仅此一项就可能导致脚本失败并且什么也不做。 If your php.ini is not set to show you errors it may not be obvious if this is happening. 如果未将php.ini设置为向您显示错误,则可能不会很明显。

Try changing all the mysql_* functions to mysqli_* -- they are mostly equivalent except in a few places. 尝试将所有mysql_ *函数更改为mysqli_ *,除了少数地方,它们几乎是等效的。 mysql_select_db needs ... to be mysqli_select_db($db,$dbname). mysql_select_db需要...成为mysqli_select_db($ db,$ dbname)。 So would mysqli_query. mysqli_query也是如此。

And also, globals. 还有,全局变量。 There are several variables in your next_auto_increment function that are defined globally that would not be accessible from your function. next_auto_increment函数中有几个全局定义的变量,这些变量无法从函数中访问。 Something like: 就像是:

global $db;
global $dbname;
global $table_name;

See the following to get errors to show up for you while developing. 请参阅以下内容,以获取在开发过程中出现的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM