从不同的文件传递参数到mysql_connect函数

时间:2014-07-01 16:36:56

标签: php mysql

我有两个名为dbcon.phpuser.php的php文件。 这是我的user.php文件

<?php
/* variable needed for the user to connect to the database */
$host = "localhost"; //your database host name
$dbuser = "root"; //your database user name
$dbpassword = "123"; //your database password
$dbase = "mysitedb"; //your database
?>

这是我的dbcon.php文件

<?php
$con = mysql_connect($host,$dbuser,'wecarealways');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db($dbase, $con);

if (!$db_selected)
  {
  die ("Can\'t use test_db : " . mysql_error());
  }
 else {
      echo 'successful';
}

mysql_close($con);

?>

我需要连接到名为mysitedb的数据库,它没有连接。我认为问题在于单独的user.php文件。在这种情况下,我需要知道如何为mysql_connect()提供参数。 谢谢!

4 个答案:

答案 0 :(得分:1)

您需要requireinclude您的user.php文件才能导入该文件的内容。在dbcon.php的顶部,您需要类似于:

的内容
include("user.php");

答案 1 :(得分:1)

dbcon.php应该是

<?php
//include parameters
include("user.php");
//connect to database (using mysqli, mysql is deprecated) or die and print the error
$con = mysqli_connect($host,$dbuser,'yourpassword',$dbase) or die("Error " . mysqli_error($con));
//If it was possible to connect to db, print 'Successful' 
echo 'Successful';
//Close the connection
mysqli_close($con);
?>

答案 2 :(得分:0)

这样做

 mysql_connect ("$host","$dbusername","$dbpassword");

答案 3 :(得分:0)

你的dbcon.php应该是这样的..

<?php

include("user.php");

$con = mysqli_connect($host,$dbuser, $dbpassword);
if (!$con)
  {
  die('Could not connect: ' . mysqli_error());
  }

$db_selected = mysqli_select_db($dbase, $con);

if (!$db_selected)
  {
  die ("Can\'t use test_db : " . mysqli_error());
  }
 else {
      echo 'successful';
}

mysqli_close($con);

?>