[英]Fail in establishing connection : PHP
I created php script called functions.php in which i've written following codes. 我创建了一个名为functions.php的php脚本,在其中编写了以下代码。 It's working fine when i've written " $conn = mysql_connect('localhost','root','pass'); " this line.
当我写了“ $ conn = mysql_connect('localhost','root','pass'); “这一行时,它工作正常。 But i want to store these credentials in config file so that it becomes quite easy for me to edit details while working with db.
但是我想将这些凭据存储在配置文件中,这样我就可以在使用数据库时轻松编辑详细信息。 So i created config.php and have written following codes :
所以我创建了config.php并编写了以下代码:
<?php
// this is config.php
$config = array(
'host'=> 'localhost'
'username' => 'root' ,
'password' => 'pass' ,
'database' => 'sample'
);
?>
This is functions.php 这是functions.php
<?php
include 'config.php';
function connect($config) {
$conn = mysql_connect($config['host'],$config['username'],$config['password']);
return $conn;
}
$con = connect();
if(!$con) die ('problem in connection');
But when i did this then its not working. 但是当我这样做时,它不起作用。 How can i fix this?
我怎样才能解决这个问题? Plzz hlp
Plzz HLP
Your syntax is incorrect, try this: 您的语法不正确,请尝试以下操作:
<?php
// this is config.php
$config = array(
'host'=> 'localhost', // Missing comma
'username' => 'root' ,
'password' => 'pass' ,
'database' => 'sample'
);
?>
Also, you don't need to pass $config
to function, it will be available globally. 另外,您无需传递
$config
即可起作用,它将在全球范围内可用。
Why did you add the $config
parameter to the connect
function? 为什么将
$config
参数添加到connect
函数? You are not passing any parameter, so $config
is always null
in your function. 您没有传递任何参数,因此
$config
在您的函数中始终为null
。 Adding the parameter to your call should solve the problem. 将参数添加到您的调用应该可以解决问题。
$con = connect($config);
Change your config.php to: 将您的config.php更改为:
<?php
// this is config.php
$config = array(
'host'=> 'localhost', // comma was missing
'username' => 'root' ,
'password' => 'pass' ,
'database' => 'sample'
);
?>
And functions.php to: 和functions.php一起使用:
<?php
include 'config.php';
function connect($config) {
$conn = mysql_connect($config['host'],$config['username'],$config['password']);
return $conn;
}
$con = connect($config); // You need to pass $config variable when calling function
if(!$con) die ('problem in connection');
I like to suggest the below code. 我想建议以下代码。 Instead of array values, I would define variables in config.php and use it functions.php
而不是数组值,我将在config.php中定义变量并使用functions.php
config.php config.php
<?php
define("DB_HOST", "localhost");
define("DB_USERNAME", "root");
define("DB_PASSWORD", "pass");
define("DB_NAME", "sample");
?>
In functions.php 在functions.php中
include('config.php');
$conn = mysql_connect(DB_HOST,DB_USERNAME,DB_PASSWORD);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.