如果包含在另一个对象中,则无法使用mysqli :: __构造?

时间:2013-10-04 13:43:10

标签: php mysql mysqli

我创建了两个文件:
 1. databaseconnect.php
 2. checklogin.php

databaseconnect.php:

class DatabaseConnection{
public $connected;
public $connection;

public function __construct($host="localhost", $username="abc", $password="def", $dbname="ghi") {
    $tbl_name="login"; // Table name 
    $this->connection = new mysqli($host, $username, $password, $db_name);
    /* check connection */
    if ($mysqli->connect_error){
        $this->connected=false;
    }
    else{
        $this->connected=true;
    }
}
}

checklogin.php:

<?php
include 'databaseconnect.php';
if($_POST){
$db = new DatabaseConnection;
if($db->connected){
    //code flow enters here
    $tbl_name = "login";
    $myusername=$_POST['myusername'];
    $mypassword=$_POST['mypassword']; 
    $myusername = htmlspecialchars($myusername);
    $mypassword = htmlspecialchars($mypassword);
    $sql="SELECT user_id FROM $tbl_name WHERE user_id='$myusername' or primary_mail='$myusername'";
    if($result=$db->connection->query($sql)){
    //do something
    //not coming in this loop
    }
}
?>

我在行中出现错误

if($result=$db->connection->query($sql)){

错误是什么,使用它的正确语法是什么?

提前致谢

2 个答案:

答案 0 :(得分:1)

我不是MySQLi的专家,但是:

if ($mysqli->connect_error){
   $this->connected=false;
}

这看起来不对,请尝试正确地解决错误:

if ($this->connection->connect_error){
    die('Connect Error: ' . $this->connection->connect_error);
}
else{
    $this->connected=true;
}

答案 1 :(得分:0)

您的文件 databaseconnect.php 中的变量$mysqli未定义。

由于您正在使用$this->connection = new mysqli($host, $username, $password, $db_name);打开连接,因此该连接将存储在$this->connection而不是$mysql中。所以你要替换它:

if ($mysqli->connect_error){
   $this->connected=false;
}

有了这个:

if ($this->connection->connect_error){
   $this->connected=false;
}

其次,为什么不在{strong> databaseconnect.php 中创建一个$db->connection->query($sql)方法,而不是用query()进行查询?它使您的代码更清晰。

databaseconnect.php:

public function query ($sql)
{
   return $this->connection->query ($sql);
}

checklogin.php:

$sql="SELECT user_id FROM $tbl_name WHERE user_id='$myusername' or primary_mail='$myusername'";
if($result=$db->query($sql)){
   //do something
}

如果您正在调试查询未执行的原因,可以向databaseconnect.php添加调试文本:

public function query ($sql)
{
   return $this->connection->query ($sql) or die ("MySQLi error: '" . $this->connection->error . "' for query: {$sql}");
}