-2

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

数据库连接.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;
    }
}
}

检查登录.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)){

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

提前致谢

4

2 回答 2

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;
}
于 2013-10-04T14:22:54.530 回答
0

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

因为您正在打开连接$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;
}

其次,$db->connection->query($sql)为什么不直接在databaseconnect.phpquery()中创建一个方法并从那里调用它,而不是使用 进行查询?它使您的代码更干净。

数据库连接.php:

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

检查登录.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}");
}
于 2013-10-04T15:43:47.130 回答