在php中使用sql连接中的变量

时间:2014-02-15 07:27:09

标签: php sql sqlconnection

我使用此代码连接到PHP中的sql:

public function ffff(){
    $connection = new mysql();
    $connection->connect('127.0.0.1','root','','miscfb');
}

但我想使用变量而不是'miscfb'

例如: $db='miscfb';

,代码为:

$connection->connect('127.0.0.1','root','',$db);   

但它无法连接到数据库!

我应该如何使用变量?

2 个答案:

答案 0 :(得分:0)

如果在$db内宣布ffff(),则应该有效。如果它在函数上方声明,请尝试$this->db。但是,如果这是一个连接错误,而不是一个变量使用问题(很难说),那么你可以解释一个正在返回的错误吗?

旁注:请开始离开mysql_*并开始实施PDO或mysqli。

快速编辑!谢谢:))

答案 1 :(得分:0)

<?php
   //setting CONSTANTS for host, user, password (good practies in development step)
   DEFINE('DB_HOST', 'localhost'); 
   DEFINE('DB_USER', 'root'); 
   DEFINE('DB_PASS', 'root_pwd');  

  //storing the result of the connection (mysqli $link) in a variable 
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASS) or 
                    die('could not connect: '. mysqli_connect_error() );

   //storing the name of the database you want to work with
   $DB_NAME="miscfb";

  //selecting the database
  mysqli_select_db($dbc, DB_NAME) or die('could not select db');

?>

我建议你使用Mysqli o PDO连接。 Mysql“经典”连接将在未来的PHP版本上弃用,它将完全开始面向对象。