Foros del Web » Programando para Internet » PHP »

Problema con clase en PDO

Estas en el tema de Problema con clase en PDO en el foro de PHP en Foros del Web. Hola amigos. Cuestión que es un tema que vengo de hace tiempo. Estuve estudiando lo que pude hasta ahora porque avancé pero no llegué aún ...
  #1 (permalink)  
Antiguo 09/06/2013, 23:54
 
Fecha de Ingreso: abril-2012
Ubicación: Argentina
Mensajes: 215
Antigüedad: 12 años
Puntos: 2
Busqueda Problema con clase en PDO

Hola amigos. Cuestión que es un tema que vengo de hace tiempo.
Estuve estudiando lo que pude hasta ahora porque avancé pero no llegué aún al éxito. Necesito su ayuda por favor.

El siguiente ejemplo funciona bien:

Código:
class Helper {	

	private static $router = array (	
	
    '/' => array(
        'column' => 'columns/tabOne/columnA.php',
        'content' => 'content/tabOne/contentA.php'
    ),
    '/index' => array(
        'column' => 'columns/tabOne/columnA.php',
        'content' => 'content/tabOne/contentA.php'
    ),
	 '/contentAtabOne' => array(
        'column' => 'columns/tabOne/columnA.php',
        'content' => 'content/tabOne/contentA.php'
    ),
	 '/contentBtabOne' => array(
        'column' => 'columns/tabOne/columnA.php',
        'content' => 'content/tabOne/contentB.php'
    ),
    '/tabTwo' => array(    
		'content' => 'content/tabTwo.php'		
    ),			
     '/tabThree' => array(        
        'content' => 'content/tabThree.php'
    ),
	'/tabFour' => array(       
        'content' => 'content/tabFour.php'
    )

);

public static function getColumn($file = null ) {
    if (array_key_exists($file, self::$router) && isset(self::$router[$file]['column'])) {
        ob_start();
		is_file(self::$router[$file]['column']);
        require_once(self::$router[$file]['column']);
        return ob_get_clean();		
    }
}

public static function getContent($file = null) {
    if (array_key_exists($file, self::$router) && is_file(self::$router[$file]['content'])) {
        ob_start();
        require_once(self::$router[$file]['content']);
        return ob_get_clean();
    }
}

}
El tema es que necesito hacer lo mismo pero desde una conexión PDO a la BD.

Esto es lo que conseguí:

Código:
class Helper {

    private $_db;//Atributos o propiedad de clase

    public function __construct($db) {//Constructor
           $this->_db = $db;
    }

//Métodos:
    public function otraFuncion() {
        // Con $this->_db tienes acceso a la base de datos
	$si="ejemplo de otra funcion aprobado!!"; // Con $this->_db tienes acceso a la base de datos
	
        return $si;
    }		

}

try
   {
    $con = new PDO('mysql:host=localhost;dbname=pruebaarray', 'root', '');//Conexión a nuetra BD por PDO con el constructor de la clase 
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//Mensaje de Error si no conecta	
    }
  catch(PDOException $e)
    {
  echo 'Error: ' . $e->getMessage();
    }

try
   {
    $helper = new Helper($con);// Ahora se instancea helper, proporcionando la conexión	
	
	echo $helper -> otraFuncion();//Llmao al método de la clase
    }
  catch(PDOException $e)
    {
  echo 'Error: ' . $e->getMessage();
    }

Esta es la BD:





Como muestro en la imagen, la tabla (se llama "arrayUrl") consta de 4 campos:
(1: "arrayUrl_id", 2:"arrayUrl_name", 3:"arrayUrl_column" y 4:"arrayUrl_content")




Os ruego su ayuda, o por donde seguir estudiando para este caso. La verdad que quiero llegar al éxito.
  #2 (permalink)  
Antiguo 10/06/2013, 00:27
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Problema con clase en PDO

1- Define $router como propiedad privada
2- Crea un método setRouter() que ejecutarás en el constructor
3- Ejecuta la consulta para obtener todos los registros
4- Recorre el juego de resultados para llenar $router

Si todavía sigues problemas, debes ser más específico respecto a la parte que se te dificulta; por ejemplo, mencionas PDO, pero no se ve que intentes hacer la consulta.
__________________
- León, Guanajuato
- GV-Foto
  #3 (permalink)  
Antiguo 18/06/2013, 08:34
 
Fecha de Ingreso: abril-2012
Ubicación: Argentina
Mensajes: 215
Antigüedad: 12 años
Puntos: 2
Busqueda Respuesta: Problema con clase en PDO

Hola Triby. Gracias por responder. Ahora ahondé más el tema.

Código:
class Helper {
	
//Propiedades	
    private $host      = 'localhost';
    private $user      = 'root';
    private $pass      = '';
    private $dbname    = 'pruebaarray';	
	
	private $dbh;
    private $error;
	
	private $router;
 
    public function __construct(){
        // Set DSN
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;	
		
        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );	
		
        // Create a new PDO instanace
        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
	    $this->setRouter();		
        }
        // Catch any errors
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
    }
	
	   public function setRouter() {//Le cargo a 'router' los valores de inicialización	   
           $resultsColumn  = $this->getColumn();//Selecciono la 2nda columna	
           $resultsContent = $this->getContent();//Selecciono la 3nda columna
           return $resultsContent;//Retorna 3nda columna
           return $resultsColumn;//Retorna 2nda columna
	   }
	  
	    public function getColumn() {		 
           $stmt = $this->dbh->prepare('SELECT * FROM arrayurl WHERE arrayUrl_name=arrayUrl_name');//Preparo la consulta   
           $stmt->execute() ;	  
           return $stmt->fetchAll(PDO::FETCH_COLUMN,2);//Obtener la 3nda columna de la tabla 
	   }
	   
	    public function getContent() {		 
           $stmt = $this->dbh->prepare('SELECT * FROM arrayurl WHERE arrayUrl_content=arrayUrl_content');//Preparo la consulta  
           $stmt->execute() ;	  
           return $stmt->fetchAll(PDO::FETCH_COLUMN,3);//Obtener la 4nda columna de la tabla (Esto se cuenta desde base 0, en este caso:3)
	   }
}

//Instanceo Helper
$db = new Helper();

//Consultas:

$resultsColumn = $db->getColumn();//Selecciono la 2nda columna
print_r($resultsColumn);//Imprimo 2nda columna

$resultsContent = $db->getContent();//Selecciono la 3nda columna
print_r($resultsContent);//Imprimo 3nda columna

Voy a hacer más específico: Aparentemente el problema lo tengo con cómo recorrer los resultados para llenar $router.

¿Alguna idea por favor?

Última edición por mikehove; 18/06/2013 a las 09:10
  #4 (permalink)  
Antiguo 18/06/2013, 18:29
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Problema con clase en PDO

A ver, tan fácil que es obtener un juego de resultados y recorrerlo:

Código PHP:
Ver original
  1. $array = array();
  2.  
  3. $stmt = $this->dbh->prepare('SELECT * FROM arrayurl ORDER BY campo_para_ordenar');
  4. $stmt->execute();
  5. // Luego recorres el juego de resultados:
  6. while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  7.       $array[$row['arrayUrl_name']] = array(
  8.                'arrayUrl_content' => $row['arrayUrl_content']
  9.       );
  10.       // Asignas la columna sólo si es necesaria
  11.       if($row['arrayUrl_column'] != '') {
  12.               $array[$row['arrayUrl_name']]['arrayUrl_column'] = $row['arrayUrl_column'];
  13.       }
  14. }
  15.  
  16. // Finalmente compruebas si el array se creó correctamente
  17. var_dump($array);
  18. // Si todo va bien, eliminas estas últimas líneas

Adáptalo en tu código, no creo que tengas mayor problema.
__________________
- León, Guanajuato
- GV-Foto
  #5 (permalink)  
Antiguo 21/06/2013, 08:00
 
Fecha de Ingreso: abril-2012
Ubicación: Argentina
Mensajes: 215
Antigüedad: 12 años
Puntos: 2
Respuesta: Problema con clase en PDO

¿Qué estaré haciendo incorrecto?

Pues cuando recorre el juego de resultados está bien, aparece esto como el original (como se muestra al principio del post con arrays):

Código:
 array(7) { 

  ["/"]=> array(2) { 
        ["arrayUrl_content"]=> string(27) "content/tabOne/contentA.php" 
        ["arrayUrl_column"]=> string(26) "columns/tabOne/columnA.php" 
  } 
  ["/contentAtabOne"]=> array(2) { 
        ["arrayUrl_content"]=> string(27) "content/tabOne/contentA.php" 
        ["arrayUrl_column"]=> string(26) "columns/tabOne/columnA.php"
  } 
  ["/contentBtabOne"]=> array(2) { 
        ["arrayUrl_content"]=> string(27) "content/tabOne/contentB.php" 
        ["arrayUrl_column"]=> string(26) "columns/tabOne/columnA.php" 
  } 
  ["/index"]=> array(2) { 
        ["arrayUrl_content"]=> string(27) "content/tabOne/contentA.php" 
        ["arrayUrl_column"]=> string(26) "columns/tabOne/columnA.php" 
  } 
  ["/tabFour"]=> array(1) { 
        ["arrayUrl_content"]=> string(19) "content/tabFour.php" 
  } 
  ["/tabThree"]=> array(1) { 
        ["arrayUrl_content"]=> string(20) "content/tabThree.php" 
  } 
  ["/tabTwo"]=> array(1) { 
        ["arrayUrl_content"]=> string(18) "content/tabTwo.php" 
  } 

}
En definitiva queda así 'Helper.php':

Código:
<?php

class Helper {
	
//Propiedades	
    private $host      = 'localhost';
    private $user      = 'root';
    private $pass      = '';
    private $dbname    = 'pruebaarray';	
	
	private $dbh;
    private $error;
	
	private $router;
 
    public function __construct(){
        // Set DSN
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;		
        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );			
        // Create a new PDO instanace
        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
			$this->setRouter();		
        }
        // Catch any errors
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
    }
	
    public function setRouter() {//Le cargo a 'router' los valores de inicialización
    $array = array(); 
    $stmt = $this->dbh->prepare('SELECT * FROM arrayurl');
    $stmt->execute();

    // Luego recorres el juego de resultados:
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
          $array[$row['arrayUrl_name']] = array(
               'arrayUrl_content' => $row['arrayUrl_content']
      );
    // Asignas la columna sólo si es necesaria
    if($row['arrayUrl_column'] != '') {
          $array[$row['arrayUrl_name']]['arrayUrl_column'] = $row['arrayUrl_column'];
      }
    }
/* 
// Finalmente compruebas si el array se creó correctamente
var_dump($array);
// Si todo va bien, eliminas estas últimas líneas
*/
    }
	  
    public function getColumn() {		   
        $stmt = $this->dbh->prepare('SELECT * FROM arrayurl ORDER BY arrayUrl_column');//Preparo la consulta 
        $stmt->execute();		   
        return $stmt->fetchAll(PDO::FETCH_COLUMN,2);//Obtener la 3nda columna de la tabla		   
	}
		   
	public function getContent() {		
        $stmt = $this->dbh->prepare('SELECT * FROM arrayurl ORDER BY arrayUrl_content');          
        $stmt->execute() ;	  
        return $stmt->fetchAll(PDO::FETCH_COLUMN,3);//Obtener la 4nda columna de la tabla (Esto se cuenta desde base 0)
	}
	   	   
}

//Instanceo Helper
$db = new Helper();

//Consultas:

/*
$resultsColumn = $db->getColumn();//Selecciono la 2nda columna
print_r($resultsColumn);//Imprimo 2nda columna

$resultsContent = $db->getContent();//Selecciono la 3nda columna
print_r($resultsContent);//Imprimo 3nda columna
*/

?>
Me salta error en index.php:

Código:
<?php
	
	defined("DS")
		|| define("DS", DIRECTORY_SEPARATOR);
	
	defined("ROOT_PATH")
		|| define("ROOT_PATH", realpath(dirname(__FILE__)));
		
	require_once(ROOT_PATH.DS.'classes'.DS.'Helper.php');
	
	$page = '/';
    
$uri = $_SERVER['REQUEST_URI'];

if (!empty($uri) && $uri != '/') {
    $uri = explode('?', $uri);
    $page = $uri[0];
}
	
	$content = array(
	'right' => $db->getColumn($page),
	'left' =>  $db->getContent($page)
	);
	
	
	if (!empty($_GET['ajax'])) {
		echo json_encode($content);
	} else {
		require_once('template/template.php');
	}
	
	
?>

Y el index original con arrays es así:

Código:
<?php
	
	defined("DS")
		|| define("DS", DIRECTORY_SEPARATOR);
	
	defined("ROOT_PATH")
		|| define("ROOT_PATH", realpath(dirname(__FILE__)));
		
	require_once(ROOT_PATH.DS.'classes'.DS.'Helper.php');
	
	$page = '/';
    
$uri = $_SERVER['REQUEST_URI'];

if (!empty($uri) && $uri != '/') {
    $uri = explode('?', $uri);
    $page = $uri[0];
}
	
	$content = array(
		'right' => Helper::getContent($page),
		'left' => Helper::getColumn($page)
	);
	
	
	if (!empty($_GET['ajax'])) {
		echo json_encode($content);
	} else {
		require_once('template/template.php');
	}
	
	
?>
  #6 (permalink)  
Antiguo 21/06/2013, 08:18
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Problema con clase en PDO

¿Donde inicializas $db?
  #7 (permalink)  
Antiguo 21/06/2013, 08:29
 
Fecha de Ingreso: abril-2012
Ubicación: Argentina
Mensajes: 215
Antigüedad: 12 años
Puntos: 2
Respuesta: Problema con clase en PDO

Hola GatorV. Inicializo $db en Helper.php (gracias al constructor -Código completo justo arriba de este post).


Código:
class Helper {
...
...
...


public function __construct(){
        // Set DSN
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;		
        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
        );			
        // Create a new PDO instanace
        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
			$this->setRouter();		
        }
        // Catch any errors
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
...
...
...
    }

//Instanceo Helper
$db = new Helper(); 
  #8 (permalink)  
Antiguo 21/06/2013, 09:32
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Problema con clase en PDO

Entonces la pregunta sería ¿que es lo que falla en este punto?
  #9 (permalink)  
Antiguo 21/06/2013, 10:12
 
Fecha de Ingreso: abril-2012
Ubicación: Argentina
Mensajes: 215
Antigüedad: 12 años
Puntos: 2
Respuesta: Problema con clase en PDO

¿Podrá ser la llamada a los métodos siguientes? : (Estará bien llamado?)


index.php:

$content = array(
'right' => $db->getColumn($page),
'left' => $db->getContent($page)
);
  #10 (permalink)  
Antiguo 21/06/2013, 19:14
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Problema con clase en PDO

A mi me parece que falta algo por hacer con $array en la función que te sugerí, porque no retorna el valor ni se asigna a la propiedad adecuada (aka $router).

Por algo siempre digo que copiar/pegar, sin analizar y entender, no lleva a nada bueno.
__________________
- León, Guanajuato
- GV-Foto
  #11 (permalink)  
Antiguo 27/06/2013, 10:20
 
Fecha de Ingreso: abril-2012
Ubicación: Argentina
Mensajes: 215
Antigüedad: 12 años
Puntos: 2
Problema con condición

Muchas gracias Triby y Gator, a varios tutoriales, profes y demás porque llego al éxito.

mikehove.-

Última edición por mikehove; 27/06/2013 a las 14:01 Razón: Problema con pdo

Etiquetas: pdo, php+base+de+datos+array, php+basedatos, php+clases
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 13:19.