j4nk3y: PHP Oop Datenbank Klasse

Beitrag lesen

Hey,

Danke für deine Hinweise.

Ein wenig denke ich konnte ich schon umsetzen, hier nur kurz die einzelnen Methoden:

public function select ( $columns, $tablel, $where, $limit = null ) {
	
	if ( !is_null( $columns ) ) {
		$columns = ['*'];
	}
	
	$columns = implode(", ", $columns);
	
	$query = "SELECT {$columns} FROM {$table}";
	$query .= $this -> whereClause( $where, $limit );
	
	$stmt = self::$instance -> prepare( $query );
	
	if ( is_array( $where[0] ) ) {
		foreach ( $where as $toBind ) {
			if ( !$stmt -> execute( $toBind ) ) {
				return false;
			}
			$result[] =  $stmt -> fetchAll();
		}
	} else {
		if ( !$stmt -> execute( $where ) ) {
				return false;
		}
		$result =  $stmt -> fetchAll();
	}
	return $result;
}

public function insert ( $table, $data ) {
	
	$columns = implode( ", ", array_keys( is_array( $data[0] ) ? $data[0] : $data ) );
	$placeholders = substr ( str_repeat("?, ", count( is_array( $data[0] ) ? $data[0] : $data ) )) , 0, -2 );
	
	$query = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";
	
	$stmt  = self::$instance -> prepare( $query ) );
	
	if ( is_array( $data[0] ) ) {
		foreach ( $data as $toBind ) {
			if ( !$stmt -> execute( $toBind ) ) {
				return false;
			}
		}
	} else {
		if ( !$stmt -> execute( $toBind ) ) {
			return false;
		}
	}
	return true;
}

public function update ( $table, $data, $where ) {
	
	$columns = implode( "=?, ", array_keys( is_array( $data[0] ) ? $data[0] : $data ) );
	
	$query = "UPDATE {$table} SET {$columns}";
	$query .= $this -> whereClause( $where );
	
	$stmt  = self::$instance -> prepare( $query );
	
	if ( is_array( $data[0] ) ) {
		$i = 0;
		foreach ( $data as $value ) {
			foreach ( $value as $val ) {
				$toBind[$i] = $val;
				++$i;
			}
			foreach ( $where as $val ) {
				$toBind[$i] = $val;
				++$i;
			}
			if ( !$stmt -> execute( $toBind ) ) {
				return false;
			}
			$i = 0;
		}
	} else {
		foreach ( $data as $val ) {
			$toBind[$i] = $val;
			++$i;
		}
		foreach ( $where as $val ) {
			$toBind[$i] = $val;
			++$i;
		}
		if ( !$stmt -> execute( $toBind ) ) {
			return false;
		}
	}
	
	return true;
}

public function delete ( $table, $where ) {
	
	$query = "DELETE FROM {$table}";
	
	$query .= $this -> whereClause( $where );
	
	$stmt = self::$instance -> query( $query );
	
	foreach ( $where as $toBind ) {
		if ( !$stmt -> execute( $toBind ) ) {
			return false;
		}
	}
	return true;
}

public function query ( $query ) {
	if (! self::$instance->exec( $query ) ) {
		return false
	}
	return true;
}

private function whereClause ( $where, $limit ) {
	if ( !is_null( $where ) ) {
		$query .= " WHERE ";
		foreach ( $where as $column => $value) {
			$clause .= "{$column} =? AND ";
		}
		
		substr($clause, 0, -5);
		$query .= $clause;
	}
	
	if ( !is_null( $limit ) ) {
		$query .= " LIMIT = {$limit}";
	}
	
	return $query;
}

Gruß
Jo