使用OOP从MySQL获取数据

时间:2011-06-17 04:13:44

标签: php mysql 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];

但我没有得到这种逻辑来实现这一目标 请帮忙

谢谢!

4 个答案:

答案 0 :(得分:11)

您的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
}

也就是说,将整个结果集提取到内存中并不是一个好主意(有些人会说这是一个非常糟糕的主意。)

编辑:看起来你的班级还有其他问题...我必须跑步但明天会回来看看,如果其他人没有按你说话,我会扩大。

Edit2:好的,要在你的课上做一次性尝试并尝试解释一些事情:

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!";
}

我希望这会有所帮助......至少应该让你开始。如果您有更多问题,请单独询问。

答案 1 :(得分:1)

那是因为$ result在Fetch函数中设置。它不会在Fetch函数之外可用。

而不是此行$result= mysql_fetch_array($query);,您需要return mysql_fetch_array($query);

之类的内容

然后在你的代码中

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

另一方面,您的Fetch函数仅适用于返回一行的数据库查询。你必须分开mysql_query&amp;如果要循环查询结果中的行,mysql_fetch_array会调用另一个函数。

另一方面,您不需要将此代码封装到类中。 PHP已经提供了基于OOP的数据库类,称为PDO或PHP数据对象。它有一个学习曲线,但它是最好的做法,并且有助于保护代码免受SQL注入等攻击。

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

答案 2 :(得分:0)

我会创建一个返回对象值的函数。

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

然后在页面中,您希望获取数据,只需启动该类并调用该类中的函数。

$post->returnDate("row name here");

答案 3 :(得分:0)

<?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'];

?>