PHP OOP Script mit MySQL Datenbank Verbindung aufbauen.
Das ist ein Beispiel Objekt Orientierte PHP Skript, mit dem können Sie ein MySQL Datenbankverbindung aufbauen und eine Abfrage ausführen.
dbconnect.php

<?php
class dbmysql{
  private $connection = NULL;
  private $db = NULL;
  private $dbclose = NULL;
  private $result = NULL;
  private $assoc = NULL;

  public function connect(){
   $numargs = func_num_args();
   $arg_list = func_get_args();
   if($numargs == 4){
    @$this->connection = mysqli_connect(
      $arg_list[0],
      $arg_list[2],
      $arg_list[3]
    );
    if(mysqli_connect_errno()){
     $cerr = "DB Connection error: ".mysqli_connect_error();
    }else{
     $this->db = mysqli_select_db($this->connection, $arg_list[1]);
     if(!$this->db){$cerr = "DB select error: ".mysqli_error($this->connection);}
    }
   }
   elseif($numargs == 3){
    @$this->connection = mysqli_connect(
      $arg_list[0],
      $arg_list[1],
      $arg_list[2]
    );
    if(mysqli_connect_errno()){$cerr = "DB Connection error: ".mysqli_connect_error();}
   }else{
    $cerr = "db connection parameters incorrect";
   }
   if(isset($cerr)){return $cerr;}
  }

  public function disconnect() {
    if($this->connection) {
      $this->dbclose = mysqli_close($this->connection);
    }
  }

  public function query($query){
    if($this->connection && !$this->dbclose){
       $this->result = mysqli_query($this->connection,$query);
       $qerr = mysqli_error($this->connection);
       if($qerr){
        return $qerr;
       }
    }else{return FALSE;}
  }

  public function fetchRow(){
    if($this->result){
      $this->assoc = mysqli_fetch_assoc($this->result);
      if(is_array($this->assoc)){
        return $this->assoc;
      } else {
        return FALSE;
      }
    }
  }

}
?>
    

Kopieren

start.php

<?php
require_once 'dbconnect.php';
$mysql = new dbmysql;
$mysql->connect('hostname', 'dbname', 'username', 'passwort');
$usabf = "SELECT NAME as NM FROM USERS WHERE ID = '1';";
$mysql->query($usabf);
$rs = $conmysql->fetchRow();
echo $rs['NM'];
$mysql->disconnect();
?>
    

Kopieren