Taka prościutka klasa może się komuś przyda. Co sądzicie o tej klasie, czy jest dobrze zrobiona czy jakoś ulepszyć !
include_once basename('databaseClass.php'); /**
* PHP 5.1
*/
/**
* createtableclass
* Class is responsible for adding and removing,
* tables and queries mysql opomocÄ… PDO library.
* Klasa odpowiada za dodawanie
* i usuwanie tabel i zapytań mysql za opomocą biblioteki PDO.
* @version 1.00
* @license free, Noncommercial — You may not use this work for commercial purposes.
* @author Adam Berger <ber34@o2.pl>
* @Site www.joomla-cms.com.pl
*/
class createtableclass{
private $db;
public $error = false;
public function __construct(){
$this->db = new databaseClass(); // połączenie z bazą z autoload
$this->error;
}
public function error_table(){
if($this->error !== false){
return $this->error;
}
}
public function drop_table($table){
$sql4 ='DROP TABLE IF EXISTS '.$table; // szukamy tabeli
if($this->db->exec($sql4) !== false){
$this->error= 'Usunięto Tabelę.';
} else {
$this->error= 'Nie Usunięto Tabeli .'.$table;
}
}else{$this->error="Podaj nazwę tabeli do usunięcia";}
}
public function create_table($table, $sql2, $insert=null, $insert_execute=null){
try {
/* Sprawdzamy niezaleĹźnie od podania parametru IF NOT EXISTS
poniewaş dostaniemy odpowiedź i wyświetlimy ją sobie na ekranie */
$sql ='SHOW TABLES LIKE :table'; // szukamy tabeli
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':table', $table, PDO::PARAM_STR);
$stmt->execute();
if($stmt->fetch() > 0){
$this->error ='Tabela istnieje.';
}else{
if($this->db->exec($sql2) !== false){
$this->error= 'Tabela utworzona pomyślnie.';
// return 1;
} else {
$this->error= 'Nie utworzona tabeli .'.$table;
// return 0;
}
// po utworzeniu tabeli moşemy przypisać insert
$q = $this->db->prepare($insert);
$q->execute($insert_execute);
}
}
}else{
$this->error="Podaj nazwÄ™ tabeli lub zapytanie";
}
}catch(PDOException $e){
echo 'Połączenie nie mogło zostać utw.<br />'.$e->getMessage(); }
}
}
index.php
include_once basename('create-table-class-pdo.php'); /**
* PHP 5.1
*/
/**
* index.php
*
* @version 1.00
* @license free, Noncommercial — You may not use this work for commercial purposes.
* @author Adam Berger <ber34@o2.pl>
* @Site www.joomla-cms.com.pl
*/
$create = new createtableclass();
$table="admin";
$sql2 = 'CREATE TABLE IF NOT EXISTS `admin` ('
.'`id_ad` int(11) NOT NULL AUTO_INCREMENT,'
.'`login` varchar(255) NOT NULL,'
.'`password` varchar(255) NOT NULL,'
.'`sesion` varchar(255) NOT NULL,'
.'PRIMARY KEY (`id_ad`)'
.') ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;';
################################################################################
##
// zapytanie
$insert=$sql3 = "INSERT INTO `admin` (`id_ad`, `login`, `password`, `sesion`) VALUES
(?, ?, ?, ?)";
// dane dla insert
$insert_execute = array('2', 'admin', 'admin', '0');
$create->drop_table($table); /* or */ $create->create_table($table, $sql2, $insert, $insert_execute);
echo $create->error_table();