【问题标题】:Fetch data from MySQL using OOP使用 OOP 从 MySQL 获取数据
【发布时间】:2011-09-16 21:33:03
【问题描述】:

我是 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];

但我不明白实现这一点的逻辑 请帮忙

谢谢!

【问题讨论】:

  • $this 用于访问对象的变量,而不是局部变量。您还应该看看 MySQLi 和 PDO。
  • 你不应该在课堂上die()。最好向上抛出异常
  • +1 表示 Manhim 对 PDOMysqli 的评论。从这些开始,然后扩展它们,而不是围绕旧的 mysql 扩展构建一些东西。事实上,除非你必须支持旧版本的 PHP,或者需要处理遗留代码,否则你甚至不应该使用 mysql 扩展。

标签: php mysql oop


【解决方案1】:
<?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'];

?>

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 非常感谢,这就是我要找的。非常感谢 :) +100 赞 :)
      • 我有很多类似的问题要问,我需要给你多少才能回答我荒谬的疯狂问题?我不想惹你生气,这就是为什么:)
      • @asker:很高兴这是对您的问题的一个回答,您应该给 Fosco 一个赞成票和答案点(单击复选标记图形),但查看使用 Mysqli 或 PDO 来做你想做的事情。请参阅 My 和 Manhim 对您的问题的回答。
      • 我是新来的,上面写着“投票需要 15 声望”:(
      • @Fosco:如果他真的想学习 OOP,你应该教他如何投掷/尝试/接球,而不是在课堂上使用 die 语句:-)
      【解决方案4】:

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

      您需要return mysql_fetch_array($query); 之类的东西,而不是$result= 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

      【讨论】:

        猜你喜欢
        • 2015-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-29
        • 1970-01-01
        • 2018-11-23
        • 1970-01-01
        相关资源
        最近更新 更多