2012-10-21 5 views
2

변수로 정의 된 'database_name'이라는 MySQL 데이터베이스에 대한 웹 인터페이스를 만드는 아래 코드를 상속했습니다.PHP 스크립트에서 여러 MySQL 데이터베이스를 반복하는 방법

이 스크립트에 추가 데이터베이스를 추가하여 동일한 인터페이스가이 두 번째 데이터베이스를 만들 수 있도록합니다 (같은 테이블 이름 등으로 첫 번째 데이터베이스와 정확히 동일한 방식으로 설정 됨). 다른 데이터 포함). $database 여러 데이터베이스 이름을 반복 할 수있는 문자열 배열을 만드는 방법이 있습니까?

<?php 

class DatabaseInterface { 

    public $host = "localhost"; //(name or ip address) 
    public $userName = "aksfhah"; 
    public $passWord = "**********"; 
    public $database = 'database_name'; 
    public $tableData = "measurements"; 
    public $tableMinbins = "minbins"; 
    public $tableHourbins = "hourbins"; 
    public $tableDaybins = "daybins"; 
    public $tableDescriptions = "measurementDescriptions"; 
    public $tableSpecs = "experimentDescriptions"; 
    public $connection; 

    public function __construct($databaseName = "database_name") { 
     $this->database = $databaseName; 
     $this->connect(); 
    } 

    public function connect($databaseName = null) { 
     $dbh = mysql_connect($this->host, $this->userName, $this->passWord); 
     if (is_null($databaseName)) { 
      mysql_select_db($this->database); 
     } else { 
      mysql_select_db($databaseName); 
     } 
     $this->connection = $dbh; 
     return $dbh; 
    } 

    public function initializeDatabase() { 

     $this->createDataTable($this->tableData); 

     $query = "create table if not exists $this->tableDescriptions (id int auto_increment primary key,type varchar(255), 
    description varchar(255), experimentname varchar(255), unique Key(description,experimentname)) engine=myisam"; 
     mysql_query($query); //create a table if it does not exist 
     echo mysql_error(); //report error if one occurred 
    } 

    private function createDataTable($tableName) { 

     $query = "CREATE TABLE IF NOT EXISTS $tableName (
       id smallint(5) unsigned NOT NULL, 
       time datetime NOT NULL, 
        measurement float DEFAULT NULL, 
        rebinned tinyint(4) DEFAULT '0', 
        PRIMARY KEY (id,time), 
        KEY (rebinned,id) 
        ) ENGINE=MyISAM"; 
     mysql_query($query); //create a table if it does not exist 
     echo mysql_error(); //report error if one occurred 
    } 

    public function insertByDescription($time, $value, $channelDescription, $experimentDescription, $type = "other") { 

     $sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type); 
     return $this->insertById($time, $value, $sensorID); 
    } 

     public function insertMultipleById($timeArray, $valueArray, $sensorID,$tableName=null) { 
     if(is_null($tableName)){ 
      $tableName= $this->tableData; 
     } 
     if (count($timeArray) == 0) 
      return 0; 
     $query = "insert ignore into $tableName (id,time,measurement) 
      VALUES "; 
     for ($index = 0; $index < count($timeArray); $index++) { 
      $timeString = $timeArray[$index]->format("Y-m-d H:i:s"); 
      $value = $valueArray[$index]; 
      $query = $query . "('$sensorID','$timeString','$value'),"; 
     } 
     $query = substr($query, 0, strlen($query) - 1); //trim final comma 
     $result = mysql_query($query); 
     if (mysql_error()) { 
      echo mysql_error(); 
      return false; 
     } else 
      return mysql_affected_rows(); 
    } 

    public function insertMultipleByDescription($timeArray, $valueArray, $channelDescription, $experimentDescription, $type = "other",$tableName=null) { 
     $sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type); 
     return $this->insertMultipleById($timeArray, $valueArray, $sensorID,$tableName); 
    } 

    public function insertById(DateTime $time, $value, $sensorID) { 
     $timeString = $time->format("Y-m-d H:i:s"); 
     $query = "insert ignore into $this->tableData (id,time,measurement) 
      VALUES ('$sensorID','$timeString','$value')"; 
     $result = mysql_query($query); 
     if (mysql_error()) { 
      echo mysql_error(); 
      return false; 
     } else if (mysql_affected_rows() == 0) { 
      return false; 
     } else { 
      return true; 
     } 
    } 

    public function createIdFromDescription($channelDescription, $experimentDescription, $type) { 
     $sensorId = $this->getIdFromDescription($channelDescription, $experimentDescription); 
     if (!$sensorId) { 
      $query = "insert ignore into $this->tableDescriptions (description,experimentname,type) 
      VALUES ('$channelDescription','$experimentDescription','$type')"; 
      $result = mysql_query($query); 
      $sensorId = mysql_insert_id(); 
     } 
     return $sensorId; 
    } 

    public function getIdFromDescription($measurementDescription, $experimentDescription) { 
     $sensorId = false; 
     $query = "select id from $this->tableDescriptions where description like '$measurementDescription' 
    && experimentname like '$experimentDescription'"; 
     $result = mysql_query($query); 
     if (mysql_error()) { 
      echo mysql_error(); //report error if one occurred 
      return false; 
     } 
     if (mysql_num_rows($result) > 0) { 
      $row = mysql_fetch_array($result); 
      $sensorId = $row['id']; 
     } 
     return $sensorId; 
    } 

    function getDataById($id, $startDate, $endDate, $interval = "") { 
     $data = array(); 
     $startDateString = $startDate->format("Y-m-d H:i:s"); 
     $endDateString = $endDate->format("Y-m-d H:i:s"); 
     $query = "select time,measurement from $this->tableData where id='$id' && time>='$startDateString' && time <='$endDateString' order by time asc " . $interval = "" ? "" : "group by $interval"; 
     $result = mysql_query($query); 
     if (mysql_error()) { 
      echo mysql_error(); //report error if one occurred 
      return false; 
     } 
     while ($row = mysql_fetch_array($result)) { 
      //$time = new DateTime($row['time']); 
      $data[] = array($row['time'], $row['measurement'] * 1); 
     } 
     return $data; 
    } 

    public function getMostRecentData($id, $table) { 
     $query = "select date(max(time)) as time,measurement from $table where id='$id'"; 
     $result = mysql_query($query); 
     if (mysql_error()) { 
      echo mysql_error(); //report error if one occurred 
      return false; 
     } elseif (mysql_num_rows($result) > 0) { 
      $row = mysql_fetch_array($result); 
      return $row; 
     } else { 
      return false; 
     } 
    } 

    public function getExperimentList() { 
     $list = array(); 
     $query = "select distinct experimentname from $this->tableDescriptions"; 
     $result = mysql_query($query); 
     if (mysql_error()) { 
      echo mysql_error(); //report error if one occurred 
      return false; 
     } 
     while ($row = mysql_fetch_array($result)) { 
      $list[] = $row['experimentname']; 
     } 
     return $list; 
    } 

    public function getChannelList($experimentDescription) { 
     $list = array(); 
     $query = "select id,description,type from $this->tableDescriptions where experimentname='$experimentDescription'"; 
     $result = mysql_query($query); 
     if (mysql_error()) { 
      echo mysql_error(); //report error if one occurred 
      return false; 
     } 
     while ($row = mysql_fetch_array($result)) { 
      $list[$row['description']] = array("id" => $row['id'], "type" => $row['type']); 
     } 
     return $list; 
    } 

    public function getDescriptionFromId($id) { 

     $query = "select * from $this->tableDescriptions where id='$id'"; 
     $result = mysql_query($query); 
     if (mysql_error()) { 
      echo mysql_error(); //report error if one occurred 
      return false; 
     } 
     if (mysql_num_fields($result) > 0) { 
      $row = mysql_fetch_array($result); 
      return array($row['type'], $row['description'], $row['experimentname']); 
     } else { 
      return false; 
     } 
    } 

    public function getDisplayName($experimentName) { 
     $query = "select displayName from $this->tableSpecs where experimentName='$experimentName'"; 
     $result = mysql_query($query); 
     echo mysql_error(); 
     $row = mysql_fetch_array($result); 
     if ($row) { 
      return $row['displayName']; 
     } else { 
      return false; 
     } 
    } 

    public function simpleQuery($query) { 
     $result = mysql_query($query); 
     echo mysql_error(); 
     if ($result) { 
      $row = mysql_fetch_array($result); 
      if ($row) { 
       return $row[0]; 
      } else { 

       return FALSE; 
      } 
     } else { 
      return FALSE; 
     } 
    } 

    public function rebin($tableSource, $tableTarget, $numSeconds, $sum = false) { 

     $this->createDataTable($tableTarget); 


     echo "Updating $tableSource to set rebinned from 0 to 2..."; 
     $query = "update $tableSource set rebinned=2 where rebinned =0;"; 
     mysql_query($query); 
     echo mysql_error(); 
     echo "Done.\n"; 

     $numRows = mysql_affected_rows(); 
     echo "Found $numRows records in $tableSource that need rebinning...\n"; 


     $query = "select id,from_unixtime(floor(unix_timestamp(min(time))/$numSeconds)*$numSeconds) as mintime from $tableSource where rebinned=2 group by id;"; 
     $result = mysql_query($query); 
     echo mysql_error(); 

     if ($result) { 
      while ($row = mysql_fetch_array($result)) { 
       $id = $row['id']; 
       $mintime = $row['mintime']; 
       echo $id . "..."; 

       $query = "INSERT INTO $tableTarget (id,time,measurement,rebinned) 
        SELECT id,from_unixtime(floor(unix_timestamp(time)/$numSeconds)*$numSeconds)," . ($sum ? "sum" : "avg") . "(measurement) as measurement,0 
        FROM $tableSource WHERE id=$id && time>='$mintime' 
        GROUP BY id,floor(unix_timestamp(time)/$numSeconds) 
        ON DUPLICATE KEY UPDATE measurement=values(measurement), rebinned=0;"; 
       mysql_query($query); 
       //echo $query; 
       echo mysql_error(); 
       echo "Done.\n"; 
      } 
      echo "Updating $tableSource to set rebinned from 2 to 1..."; 
      $query = "update $tableSource set rebinned=1 where rebinned =2;"; 
      mysql_query($query); 
      echo mysql_error(); 
      echo "Done.\n"; 
     } 
    } 

    public function getDCPower($experimentName, $startDate, $endDate) { 
     $out = array(); 
     $query = $this->buildDCPowerQuery($experimentName, $this->tableMinbins); 
     if ($query) { 
      if ($startDate != "") { 
       $query = $query . " && m0.time>='$startDate' "; 
      } 
      if ($endDate != "") { 
       $query = $query . " && m0.time<='$endDate' "; 
      } 

      echo $query; 
      $result = mysql_query($query); 
      echo mysql_error(); 
      while ($row = mysql_fetch_array($result)) { 
       // echo $row['time'].", ".$row['power']."\n"; 
       $out[] = array($row['time'], $row['power'] + 0); 
      } 

      return $out; 
     } else { 
      return FALSE; 
     } 
    } 

} 

?> 

답변

2

$ 데이터베이스 문자열 배열을 만들 수있는 방법이있는 나는 여러 데이터베이스 이름에 대한 루프를 통해 할 수 있습니까?

아니요, 그렇게 작동하지 않습니다. 당신이 가진 스크립트는 클래스를 정의합니다. 해당 클래스를 사용하는 당신은 파일을 볼 필요가, 어디

등의 일을하고 두 인스턴스를 사용하실 수 있습니다

$interface = new DatabaseInterface("database1"); 

같은이있을 것 두 데이터베이스에 대한 인터페이스

+0

굉장합니다. 고맙습니다. 그건 완벽하게 이해가됩니다. 하나의 질문. 변수'$ database'가 다른 스크립트에서이 클래스로 쉽게 전달 될 수 있도록'DatabaseInterface' 클래스를 어떻게 수정해야합니까? – user1763897

+0

그럴 필요는 없습니다. 이미 치료를 받았습니다. 'new' 선언에서'$ database'의 값을 지정하십시오 (응답 참조). '$ interface [x] -> database'를 사용하여 특정 인스턴스의 데이터베이스 값을 검색하십시오. – LSerni

관련 문제