Skip to content

Commit

Permalink
Problemas creación BD solucionados
Browse files Browse the repository at this point in the history
  • Loading branch information
UO291047 committed Dec 17, 2024
1 parent 8516499 commit f5c1d0a
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions php/consultor.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ public function __construct(){

$this->pdo = new PDO("mysql:host=$this->host", $this->user, $this->password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if(!$this->databaseExists()){
$this->create_database();
}
}

public function getConexion(): PDO{
Expand All @@ -47,25 +51,28 @@ public function getConexion(): PDO{

public function databaseExists(): bool {
try {
$pdo = $this->getConexion();
$stmt = $pdo->prepare("SHOW DATABASES LIKE :dbname");
$stmt->bindParam(':dbname', $this->dbname);
// Ejecuta una consulta para comprobar si la base de datos existe
$stmt = $this->pdo->prepare("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = :dbname");
$stmt->bindParam(':dbname', $this->dbname, PDO::PARAM_STR);
$stmt->execute();
return $stmt->rowCount() > 0;

// Comprueba si hay resultados
$result = $stmt->fetch() !== false;
return $result;

} catch (PDOException $e) {
// Manejo de errores, por ejemplo, logear o mostrar el error
echo "Error: " . $e->getMessage();
// Maneja errores si ocurren
echo "Error al comprobar la base de datos: " . $e->getMessage();
return false;
}
}


public function create_database(){
try {
$pdo = $this->getConexion();
$pdo->exec("DROP DATABASE IF EXISTS $this->dbname");
$pdo->exec("CREATE DATABASE $this->dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
$pdo->exec("USE $this->dbname");
$this->pdo->exec("DROP DATABASE IF EXISTS $this->dbname");
$this->pdo->exec("CREATE DATABASE $this->dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
$this->pdo->exec("USE $this->dbname");
$sqlFilePath = 'informacion.sql';
$sqlContent = file_get_contents($sqlFilePath);

Expand All @@ -77,7 +84,7 @@ public function create_database(){

foreach ($statements as $statement) {
if (!empty($statement)) {
$pdo->exec($statement);
$this->pdo->exec($statement);
}
}
} catch (PDOException $e) {
Expand Down Expand Up @@ -351,9 +358,6 @@ public function handleExportImport() {
<h2>Consultor F1</h2>

<?php
if(!$database->databaseExists()){
$database->create_database();
}
$pdo = $database->getConexion();
?>

Expand Down

0 comments on commit f5c1d0a

Please sign in to comment.