好的,我完全感到困惑。
我正在建立一个OO网站。我有一个定义所有数据库参数的类,如下所示:
$db->host= "localhost";
$db->name= "mydatabase";
$db->user= "user";
$db->pw = "password";
正在实例化该类,并且这些值显示在加载此类之后出现的页面中。
但是,当我尝试从另一个类连接到此数据库时,它不会连接。以下是我的联系方式:
$dbconn = mysql_connect($db->host, $db->user, $db->pw);
mysql_select_db($db->name, $dbconn);
如果我取出用户,pw并将变量和硬代码命名为正确的值,一切正常,但如果使用db构造引用它们中的任何一个,则不会发生任何连接。同样,db构造在其他页面上看起来很好,我看到正确显示变量值。但是,$ db->主机变量始终有效。
以下是我构建db类的方法:
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host = "localhost", $name = "mydatabase", $user = "user", $pw = "password"){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
}
然后我当然做
$db = new database();
提前感谢您的帮助!
答案 0 :(得分:2)
$db
variable scope 如何解决所有问题?
class MyClass {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function doSth() {
$this->db->query('..');
}
}
$db = new PDO('mysql:dbname=mydatabase;host=localhost', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$obj = new MyClass($db);
$obj->doSth();
答案 1 :(得分:0)
我认为在创建初始化数据库类构造函数的对象时,你没有传递参数。
尝试使用
$db=new database("localhost","dbname","user","password");
然后将该类创建为
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host , $name , $user , $pw ){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
如果单独编写,也将此类作为文件包含在内 对于连接你现在可以写
$conn=mysql_connect($db->host,$db->user,$db->pw);
mysql_select_db($db->name,$conn);
希望这有助于:)
答案 2 :(得分:0)
<?php
/*
link.php
Created By Nicholas English
*/
$link = null;
$connection = null;
$servername = "";
$username = "";
$dbname = "";
$pass = "";
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
$type = 3;
if ($type === 1) {
$mysqli = true;
$pdo = false;
$obj = true;
$pr = false;
} else {
if ($type === 2) {
$mysqli = true;
$pdo = false;
$obj = false;
$pr = true;
} else {
if ($type === 3) {
$mysqli = false;
$pdo = true;
$obj = false;
$pr = false;
} else {
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
}
}
}
if ($mysqli === true && $obj === true) {
$link = new mysqli($servername, $username, $pass, $dbname);
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$connection = true;
} else {
if ($mysqli === true && $pr === true) {
$link = mysqli_connect($servername, $username, $pass, $dbname);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
$connection = true;
} else {
if ($pdo === true && $mysqli === false) {
try {
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $pass);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection = true;
}
catch(PDOException $e)
{
$connection = null;
echo "Connection failed: " . $e->getMessage();
}
} else {
$link = null;
$connection = null;
}
}
}
if ($connection == null && $link == null) {
$error = 1;
}
?>
使用mysqli或pdo进行更安全的连接