簡體   English   中英

使用OOP從MySQL獲取數據

[英]Fetch data from MySQL using OOP

我是OOP PHP的初學者。 我正在嘗試創建一個連接,查詢和獲取數據的類,我完成了以下編碼

class MySQL {

    private $set_host;
    private $set_username;
    private $set_password;
    private $set_database;

     public function __Construct($set_host, $set_username, $set_password){
        $this->host = $set_host;
        $this->username = $set_username;
        $this->password = $set_password;
        $con= mysql_connect($this->host, $this->username, $this->password);
        if(!$con){ die("Couldn't connect"); }
    }


    public function Database($set_database)
    {   
        $this->database=$set_database;
        mysql_select_db($this->database)or die("cannot select Dataabase");
    }

    public function Fetch($set_table_name){
        $this->table_name=$set_table_name;
        $query=mysql_query("SELECT * FROM ".$this->table_name); 
    $result= mysql_fetch_array($query);
    }
}

$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');

我想要實現的是這個

$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');

我想用這樣的格式獲取數據

echo $result[0];

但我沒有得到這種邏輯來實現這一點,請幫助

謝謝!

您的Fetch函數只從數據庫中拉出一行,而您沒有返回結果...

該方法不是最好的,但為了實現您想要做的事情:

public function Fetch($set_table_name){
    $query=mysql_query("SELECT * FROM ".$set_table_name); 
    $result = array();
    while ($record = mysql_fetch_array($query)) {
         $result[] = $record;
    }
    return $result;
}

這將使每行成為$ result的一部分,但您必須像這樣訪問它:

您可以像這樣調用fetch函數:

$result = $connect->Fetch('posts');

echo $result[0]['columnName'];  // for row 0;

或者循環:

for ($x = 0; $x < count($result); $x++) {
   echo $result[$x][0] . "<BR>";  // outputs the first column from every row
}

也就是說,將整個結果集提取到內存中並不是一個好主意(有人會說這是一個非常糟糕的主意。)

編輯:看起來你的班級還有其他問題...我必須跑,但明天會回來查看,如果其他人沒有按你說話,我會擴展。

編輯2:好的,要在你的課上做一次性嘗試並嘗試解釋一些事情:

class MySQL {

  //declaring the private variables that you will access through $this->variable;
  private $host;  
  private $username;
  private $password;
  private $database;
  private $conn;  // Adding the connection, more on this later.

  public function __Construct($set_host, $set_username, $set_password){
    $this->host = $set_host;
    $this->username = $set_username;
    $this->password = $set_password;
    // Combining the connection & connection check using 'or'
    // Notice that I removed the semi-colon after the mysql_connect function
    $this->conn = mysql_connect($this->host, $this->username, $this->password)
                  or die("Couldn't connect");
  }

  public function Database($set_database)
  {   
    $this->database=$set_database;
    // Adding the connection to the function allows you to have multiple 
    // different connections at the same time.  Without it, it would use
    // the most recent connection.
    mysql_select_db($this->database, $this->conn) or die("cannot select Dataabase");
  }

  public function Fetch($table_name){
    // Adding the connection to the function and return the result object instead
    return mysql_query("SELECT * FROM ".$table_name, $this->conn);         
  }

}

$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$posts = $connect->Fetch('posts');

if ($posts && mysql_num_rows($posts) > 0) {
     echo "Here is some post data:<BR>";
     while ($record = mysql_fetch_array($posts)) {
         echo $record[0];  // or a quoted string column name instead of numerical index.
     }
} else {
     echo "No posts!";
}

我希望這有幫助......至少應該讓你開始。 如果您有更多問題,請分別詢問。

那是因為$ result在Fetch函數中設置。 它在Fetch函數之外不可用。

而不是這行$result= mysql_fetch_array($query); ,你會想要像return mysql_fetch_array($query);

然后在你的代碼中

$row = $connect->Fetch('posts');
// do something with $row

另外,您的Fetch函數僅適用於返回一行的數據庫查詢。 如果要循環查詢結果中的行,則必須將mysql_query和mysql_fetch_array調用分隔為另一個函數。

另外,您不需要將此代碼封裝到類中。 PHP已經提供了基於OOP的數據庫類,稱為PDO或PHP數據對象。 它有一個學習曲線,但這是最好的做法,並有助於保護您的代碼免受SQL注入等事情的影響。

這是一個非常好的教程: http//www.giantflyingsaucer.com/blog/? p = 2478

我會創建一個返回對象值的函數。

public function returnData($data){
  return $this->$data;
}

然后在頁面中,您希望獲取數據,只需啟動該類並調用該類中的函數。

$post->returnDate("row name here");
<?php   
 //database.php  
 class Databases{  
      public $con;  
      public function __construct()  
      {  
           $this->con = mysqli_connect("localhost", "root", "", "giit");  
           if(!$this->con)  
           {  
                echo 'Database Connection Error ' . mysqli_connect_error($this->con);  
           }  
      }  
      public function insert($table_name, $data)  
      {  
           $string = "INSERT INTO ".$table_name." (";            
           $string .= implode(",", array_keys($data)) . ') VALUES (';            
           $string .= "'" . implode("','", array_values($data)) . "')";  
           if(mysqli_query($this->con, $string))  
           {  
                return true;  
           }  
           else  
           {  
                echo mysqli_error($this->con);  
           }  
      }  
      public function selectmulti($selecttype,$table_name)  
      {  
           $array = array();  
           $query = "SELECT ".$selecttype." FROM ".$table_name."";  
           $result = mysqli_query($this->con, $query);  
           while($row = mysqli_fetch_assoc($result))  
           {  
                $array[] = $row;  
           }  
           return $array;  
      } 
     public function selectsingle($selecttype,$table_name)  
      {   
           $query = "SELECT ".$selecttype." FROM ".$table_name."";  
           $result = mysqli_query($this->con, $query);  
           $row = mysqli_fetch_assoc($result);

           return $row;  
      }  
 } 

 ?>  

<?php
$data = new Databases;  
$post_data = $data->selectmulti('*','centerdetail');  

$n = 1;
foreach($post_data as $post)  
{ 
    echo $n.'.'.$post['CenterCode'].'___';
    $n += 1;
}

echo '<br>';


$post_data = $data->selectsingle('*','centerdetail');  

echo $post_data['CenterCode'];

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM