函数PHP中的Mysqli连接

时间:2015-06-08 14:21:51

标签: php mysqli

我遇到了PHP问题。我在网上搜索过但无法找到答案。到目前为止,这是我的代码:

<?php
   $db_host = 'db_host';
   $db_user = 'db_user';
   $db_password = 'db_password';
   $db_name = 'db_name';
   //not showing you the real db login ofcourse

   $conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
   if($conn) {
      echo 'We are connected!';
   }

到此为止,一切顺利。建立连接并且“我们已经连接!”#39;出现在屏幕上。

function login($username, $password, $conn) {
   $result = $conn->query("SELECT * FROM users");
   echo mysqli_errno($conn) . mysqli_error($conn);
} 

但是,当我运行此功能时,会弹出mysqli错误&#39;没有选择数据库。所以我在函数之前和函数中添加了以下代码片段,因此总代码变为:

<?php
   $db_host = 'db_host';
   $db_user = 'db_user';
   $db_password = 'db_password';
   $db_name = 'db_name';
   //not showing you the real db login ofcourse

   $conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
   if($conn) {
      echo 'We are connected!';
   }

   if (!mysqli_select_db($conn, $db_name)) {
      die("1st time failed");
   }

   function login($username, $password, $conn, $db_name) {
      if (!mysqli_select_db($conn, $db_name)) {
         die("2nd time failed");
      }
      $result = $conn->query("SELECT * FROM users");
      echo mysqli_errno($conn) . mysqli_error($conn);
   } 

   $username = 'test';
   $password = 'test';
   login($username, $password, $conn, $db_name);
?>

第一次添加数据库名称工作正常,但是,它不起作用的功能。我也试过在函数中使用全局$ conn,但这也没有用。将mysqli_connect()更改为新的mysqli()也没有任何效果。

提前致谢!

1 个答案:

答案 0 :(得分:1)

请注意,此代码会根据您的代码进行重构,并且不建议使用登录逻辑。请尝试使用此代码并进行您认为需要的更改。

确保您的数据库信息也根据需要进行更新。

MyDB Class

Class MyDB {

protected $_DB_HOST = 'localhost';
protected $_DB_USER = 'user';
protected $_DB_PASS = 'password';
protected $_DB_NAME = 'table_name';
protected $_conn;

public function __construct() {
    $this->_conn = mysqli_connect($this->_DB_HOST, $this->_DB_USER, $this->_DB_PASS);
    if($this->_conn) {
        echo 'We are connected!<br>';
    }
}

public function connect() {
    if(!mysqli_select_db($this->_conn, $this->_DB_NAME)) {
        die("1st time failed<br>");
    }

    return $this->_conn;
}

}

登录类

Class Login {

protected $_conn;

public function __construct() {
    $db = new MyDB();
    $this->_conn = $db->connect();
}

//This is a HORRIBLE way to check your login. Please change your logic here. I am just kind of re-using what you got
public function login($username, $password) {
    $result = $this->_conn->query("SELECT * FROM user WHERE username ='$username' AND password='$password'");

    if(!$result) {
        echo mysqli_errno($this->_conn) . mysqli_error($this->_conn);
        return false;
    }

    return $result->fetch_row() > 0;
}

}

用法

$login = new Login();
$logged = $login->login('username', 'password');

if ($logged) {
    echo "yeah!! you are IN";
} else {
    echo "boo!! . Wrong username and password";
}