2010-07-12 3 views
10

Я пытаюсь получить идентификатор пользователя из базы данных в классе, но у меня очень мало опыта работы с классами, как я могу получить получение uid из базы данных, а затем вернуть uid?Класс подключения базы данных PHP

поэтому в основном что-то вроде этого,

class hello { 
    public function getUid(){ 
     //connect to the db 
     //get all of the users info 
     $array = mysql_fetch_array($result); 
     $uid = $array['uid']; 

     return $uid; 
    } 
} 

Как я уже сказал, я еще новичок в классе, так что любой совет или помощь будет принята с благодарностью!

Thanx заранее!

ответ

31

Сначала построить библиотеку классов MySQL ... устраивающего требования, как в этот образец образца:

<?php 

include '../config/Dbconfig.php'; 

class Mysql extends Dbconfig { 

public $connectionString; 
public $dataSet; 
private $sqlQuery; 

    protected $databaseName; 
    protected $hostName; 
    protected $userName; 
    protected $passCode; 

function Mysql() { 
    $this -> connectionString = NULL; 
    $this -> sqlQuery = NULL; 
    $this -> dataSet = NULL; 

      $dbPara = new Dbconfig(); 
      $this -> databaseName = $dbPara -> dbName; 
      $this -> hostName = $dbPara -> serverName; 
      $this -> userName = $dbPara -> userName; 
      $this -> passCode = $dbPara ->passCode; 
      $dbPara = NULL; 
} 

function dbConnect() { 
    $this -> connectionString = mysql_connect($this -> serverName,$this -> userName,$this -> passCode); 
    mysql_select_db($this -> databaseName,$this -> connectionString); 
    return $this -> connectionString; 
} 

function dbDisconnect() { 
    $this -> connectionString = NULL; 
    $this -> sqlQuery = NULL; 
    $this -> dataSet = NULL; 
      $this -> databaseName = NULL; 
      $this -> hostName = NULL; 
      $this -> userName = NULL; 
      $this -> passCode = NULL; 
} 

function selectAll($tableName) { 
    $this -> sqlQuery = 'SELECT * FROM '.$this -> databaseName.'.'.$tableName; 
    $this -> dataSet = mysql_query($this -> sqlQuery,$this -> connectionString); 
      return $this -> dataSet; 
} 

function selectWhere($tableName,$rowName,$operator,$value,$valueType) { 
    $this -> sqlQuery = 'SELECT * FROM '.$tableName.' WHERE '.$rowName.' '.$operator.' '; 
    if($valueType == 'int') { 
     $this -> sqlQuery .= $value; 
    } 
    else if($valueType == 'char') { 
     $this -> sqlQuery .= "'".$value."'"; 
    } 
    $this -> dataSet = mysql_query($this -> sqlQuery,$this -> connectionString); 
    $this -> sqlQuery = NULL; 
    return $this -> dataSet; 
    #return $this -> sqlQuery; 
} 

function insertInto($tableName,$values) { 
    $i = NULL; 

    $this -> sqlQuery = 'INSERT INTO '.$tableName.' VALUES ('; 
    $i = 0; 
    while($values[$i]["val"] != NULL && $values[$i]["type"] != NULL) { 
     if($values[$i]["type"] == "char") { 
      $this -> sqlQuery .= "'"; 
      $this -> sqlQuery .= $values[$i]["val"]; 
      $this -> sqlQuery .= "'"; 
     } 
     else if($values[$i]["type"] == 'int') { 
      $this -> sqlQuery .= $values[$i]["val"]; 
     } 
     $i++; 
     if($values[$i]["val"] != NULL) { 
      $this -> sqlQuery .= ','; 
     } 
    } 
    $this -> sqlQuery .= ')'; 
      #echo $this -> sqlQuery; 
    mysql_query($this -> sqlQuery,$this ->connectionString); 
      return $this -> sqlQuery; 
    #$this -> sqlQuery = NULL; 
} 

function selectFreeRun($query) { 
    $this -> dataSet = mysql_query($query,$this -> connectionString); 
    return $this -> dataSet; 
} 

function freeRun($query) { 
    return mysql_query($query,$this -> connectionString); 
    } 
} 
?> 

и файл конфигурации ...

<?php 
class Dbconfig { 
    protected $serverName; 
    protected $userName; 
    protected $passCode; 
    protected $dbName; 

    function Dbconfig() { 
     $this -> serverName = 'localhost'; 
     $this -> userName = 'root'; 
     $this -> passCode = 'pass'; 
     $this -> dbName = 'dbase'; 
    } 
} 
?> 
+0

Большое вам спасибо, очень признательны, что вы нашли время, чтобы помочь! – Odyss3us

2
  • Создайте два класса. Один для работы с базой данных, второй для управления данными User или Auth.
  • Для класса SQL создать методы подключения(), запрос(), выборки() и т.д.
  • Для пользователей класса создать методы получения ($ ID) и т.д.
+0

Спасибо за помощь! – Odyss3us

5

Хорошо, один совет:

Сделайте все по причине. Не используйте то, что вы не знаете. Идите и изучите их.

Один может дать вам ответ на этот конкретный вопрос, но до тех пор, пока вы не знаете, что Object Oriented средства и почему есть classes на всех, вы не должны использовать их.

+1

Thanx за советом! На данный момент я учусь, когда я ухожу, поэтому мне нужна была помощь. – Odyss3us

2

Существует проблема с тем, как написан ваш код, а не с классом. Присмотритесь на этой линии:

$array = mysql_fetch_array($result); 

Это первый раз переменная $result появляется на функции. Поэтому невозможно связаться с базой данных.

Возможным псевдо-код будет:

  • подключения к серверу БД
  • запроса базы данных
  • принести результаты
  • Верните uid поле.

Посмотрите соответствующую документацию первой:

+0

Thanx, сделаю! – Odyss3us

2

Попробуйте следующее:

ini_set("display_errors", 'off'); 
    ini_set("error_reporting",E_ALL); 

class myclass { 
    function myclass() {  
     $user = "root"; 
     $pass = ""; 
     $server = "localhost"; 
     $dbase = ""; 

      $conn = mysql_connect($server,$user,$pass); 
      if(!$conn) 
     { 
      $this->error("Connection attempt failed"); 
     } 
     if(!mysql_select_db($dbase,$conn)) 
     { 
      $this->error("Dbase Select failed"); 
     } 
     $this->CONN = $conn; 
     return true; 
    } 
    function close() { 
     $conn = $this->CONN ; 
     $close = mysql_close($conn); 
     if(!$close) 
     { 
      $this->error("Connection close failed"); 
     } 
     return true; 
    }  function sql_query($sql="") {  
     if(empty($sql)) 
     { 
      return false; 
     } 
     if(empty($this->CONN)) 
     { 
      return false; 
     } 
     $conn = $this->CONN; 
     $results = mysql_query($sql,$conn) or die("Query Failed..<hr>" . mysql_error()); 
     if(!$results) 
     { 
      $message = "Bad Query !"; 
      $this->error($message); 
      return false; 
     } 
     if(!(eregi("^select",$sql) || eregi("^show",$sql))) 
     { 
      return true; 
     } 
     else 
     { 
      $count = 0; 
      $data = array(); 
      while($row = mysql_fetch_array($results)) 
      { 
       $data[$count] = $row; 
       $count++; 
      } 
      mysql_free_result($results); 
      return $data; 
     } 
    }  
} 
$obj = new myclass(); 
$obj->sql_query(""); 
0

Вы можете использовать пользовательский класс базы данных.
Код:

<?php 
Class Database 
{ 
    private $user ; 
    private $host; 
    private $pass ; 
    private $db; 

    public function __construct() 
    { 
     $this->user = "root"; 
     $this->host = "localhost"; 
     $this->pass = ""; 
     $this->db = "db_blog"; 
    } 
    public function connect() 
    { 
     $link = mysql_connect($this->user, $this->host, $this->pass, $this->db); 
     return $link; 
    } 
} 
?> 
Смежные вопросы