如何在类中实现使用mysqli的函数?

时间:2013-11-22 07:52:20

标签: php

我创建了包含函数的类,该函数使用的是mysqli。但是当我打电话使用它时,它不起作用。

这是我的代码

连接

dbconfig.php

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'xxxx');
define('DB_DATABASE', 'sample_db');
define('PORT', '80');
define('SOCKET', '/var/lib/mysql/mysql.sock');
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE, PORT, SOCKET) or die("Error " . mysqli_error($connection));
mysqli_set_charset($connection, "utf8");

班级用户

class.php

include('dbconfig.php');
class User{
  function checkUser($ID, $U_Name){
    $query = mysqli_query($connection, "SELECT * FROM user WHERE ID = '$ID'")
             or die(mysqli_error($connection));
    $result = mysqli_fetch_array($query, MYSQLI_ASSOC);

    if (!empty($result)) {
      # User is already present
      $query = mysqli_query($connection, "UPDATE user SET U_Name = '$U_Name' 
               WHERE ID = '$ID'") or die(mysqli_error($connection));
      $query = mysqli_query($connection, "SELECT * FROM user WHERE ID = '$ID'");
      $result = mysqli_fetch_array($query, MYSQLI_ASSOC);
      return $result;
    }
    else{
      #user not present. Insert a new Record
    }

  return $result;
  }
}

致电代码

include('dbconfig.php');
include('class.php');
$uid = $user_info->id; //1280
$user_name = $user_info->name; //Mr. AAAA

$user = new User();
if($uid != "" && $uid != null){
  $userdata = $user->checkUser($uid, $user_name);
  if(!empty($userdata)){
    //do something
  }
}

你能帮我解决这个问题吗?

提前感谢!

2 个答案:

答案 0 :(得分:0)

这将解决此问题:通过global在此范围内访问变量。

class User{
  function checkUser($ID, $U_Name){
    global $connection;
    // ...
  }
}

在此处阅读更多内容:http://php.net/manual/en/language.variables.scope.php

答案 1 :(得分:0)

在每个要使用的函数中重新声明连接变量,如

     function checkUser($ID, $U_Name){
            global $connection;
              $query = mysqli_query($connection, "SELECT * FROM user WHERE ID = '$ID'")
             or die(mysqli_error($connection));
    $result = mysqli_fetch_array($query, MYSQLI_ASSOC);

    if (!empty($result)) {
      # User is already present
      $query = mysqli_query($connection, "UPDATE user SET U_Name = '$U_Name' 
               WHERE ID = '$ID'") or die(mysqli_error($connection));
      $query = mysqli_query($connection, "SELECT * FROM user WHERE ID = '$ID'");
      $result = mysqli_fetch_array($query, MYSQLI_ASSOC);
      return $result;
    }
    else{
      #user not present. Insert a new Record
    }

  return $result;
            }