• Jetzt anmelden. Es dauert nur 2 Minuten und ist kostenlos!

Datenbankabfrage mit PDO geht nicht

xXxPeterPanxXx

Neues Mitglied
Hallo,

ich programmiere gerade das erstemal objektorientiert. Ich habe mich dazu entschieden die PDO-Klasse zu benutzen, leider gibt es dabei aber Probleme. Die Verbindung zur MySQL-Datenbank kriege ich aufgebaut, nur bekomme ich mit einer einfachen Abfrage keine Ergebnisse.

Das hier ist die Database-Klasse
PHP:
<?php
class Database {


private $DBName = 'xxxxxxx';
private $DBUser = 'xxxxxxxx';
private $DBPass = 'xxxxxxxx';
private $SelectedDatabase;

function __construct() {
    try {
        $this->SelectedDatabase = new PDO($this->DBName, $this->DBUser, $this->DBPass);
    } catch (Exception $e){
        header("HTTP/1.0 404 Not Found");
        exit();
    }
}

//SELECT
public function getData($DBQuery, array $BindVariables) {
    $PreparedQuery = $this->SelectedDatabase->prepare($DBQuery);
    for($i = 0; count($BindVariables) > $i; $i++) {
          $PreparedQuery ->bindParam($BindVariables[$i][0], $BindVariables[$i][1]);
    }
    $PreparedQuery ->execute();
    $result = $PreparedQuery->fetchAll(PDO::FETCH_ASSOC);
    return $result;
}

public function checkConnection() {
    $prepare = $this->SelectedDatabase->prepare('SELECT * FROM `countries`');
    $prepare->execute();
    $dbresult = $prepare->fetchAll(PDO::FETCH_ASSOC);
    return $dbresult;
}

}

?>
Die eigentliche Methode getData() liefert keine Ergebnisse, die zu Testzwecken geschriebene Methode checkConnection() hingegen schon.

Hiermit rufe ich getData() auf:
PHP:
class Countries {

public function getCountries($DatabaseObject) {
    $query ='SELECT * FROM `countries`';
    $countries = $DatabaseObject->getData($query, array());
    return $countries;
}

}
Und als letztes noch der Codeauschnitt, mit dem ich getCountries() aufrufe:
PHP:
$allcountries = new Countries();
$allcountries->getCountries($DB);
print_r($allcountries);
Fehler oder Warnungen gibt es keine.

Ich würde mich freuen, Ihr euch den Code mal anschauen könntet und mir sagt, wieso getData() nicht funktioniert.

Gruß xXxPeterPanxXx
 
Werbung:
PHP:
//SELECT
public function getData($DBQuery, array $BindVariables) {
    $PreparedQuery = $this->SelectedDatabase->prepare($DBQuery);
    for($i = 0; count($BindVariables) > $i; $i++) {
          $PreparedQuery ->bindParam($BindVariables[$i][0], $BindVariables[$i][1]);
    }
    $PreparedQuery ->execute();
    $result = $PreparedQuery->fetchAll(PDO::FETCH_ASSOC);
    return $result;
}
Erstmal würde ich die Leerzeichen wegmachen, wobei ich mir netmal sicher bin, dass es damit was zu tun hat. Abgesehen davon hab ich noch nie bindParam gebraucht.

Anbei stelle ich dir meine DB Klasse zur Verfügung. Vielleicht klappts damit besser. Da werden auch noch diverse Unterscheidungen gemacht. Wenn du damit Probleme hast einfach nochmal fragen.

PHP:
<?php

class DB {

  protected $dbh = null;

  /**
   * Constructor initializes connection, sets some attributes and character encoding
   * @param object $config
   * @param string $charset
   */
  public function __construct($config, $charset = 'utf8') {
    try {
      $this->dbh = new PDO('mysql:dbname=' . $config->db_name . ';host=' . $config->db_host, $config->db_username, $config->db_password);
      #set error handling to built in PDOExceptions
      $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      #set connection charset
      $this->dbh->exec('SET NAMES ' . $charset);
      $this->dbh->exec('SET CHARACTER SET ' . $charset);
    } catch (PDOException $e) {
      throw new Exception($e->getMessage() . ' ' . __METHOD__);
    }
  }
  
  /** 
   * returns first row of the result of a given statement as a data object
   * @param string $sql
   * @param array $params
   * @return object 
   */
  public function get_row($sql, $params = array()) {
    try {
      $stm = $this->dbh->prepare($sql);
      $stm->execute(array_values($params));
      return $stm->fetchObject();
    } catch (PDOException $e) {
      throw new Exception($e->getMessage() . ' ' . __METHOD__);
    }
  }

  /**
   * returns result of a given statement as an array of data objects
   * @param string $sql
   * @param array $params
   * @return array
   */
  public function get_rows($sql, $params = array()) {
    try {
      $stm = $this->dbh->prepare($sql);
      $stm->execute(array_values($params));
      $result = array();
      while ($row = $stm->fetchObject()) {
        $result[] = $row;
      }
      return $result;
    } catch (PDOException $e) {
      throw new Exception($e->getMessage() . ' ' . __METHOD__);
    }
  }
  
  /** 
   * executes a sql statement and returns the last inserted ID for insert-statements or the number of affected rows for other statements
   * @param string $sql
   * @param array $params
   * @return mixed
   */
  public function command($sql, $params = array()) {
    try {
      if (count($params)){
        $stm = $this->dbh->prepare($sql);
        $rows = $stm->execute(array_values($params));
      } else {
        $this->dbh->query($cl_sql);
        $stm = $this->dbh->query($sql);
      }

      if (stripos($sql,'insert') !== false) {
            return $this->dbh->lastInsertId();
      } else {
            return $stm->rowCount();
      }
    } catch (PDOException $e) {
      throw new Exception($e->getMessage() . ' ' . __METHOD__);
    }
  }

  /**
   * Wrapper for PDO::quote
   * @param string $value
   * @return string 
   */
  public function quote($value) {
    return $this->dbh->quote($value);
  }
  
}
?>
 
Werbung:
Danke für eure Hilfe!

Ich konnte das Problem selbst lösen. Ich habe gedacht, der Thread wird nicht wieder ausgegraben und deshalb nichts geschrieben :S
 
achtelpetit: Das ist der zweite Parameter der Funktion. Beim Funktionsaufruf wird ein leeres Array übergeben.

xXxPeterPanxXx: Was war das Problem?
 
Zurück
Oben