Foros del Web » Programando para Internet » PHP »

problema con foreach

Estas en el tema de problema con foreach en el foro de PHP en Foros del Web. Hola! Estoy tratando de levantar los registros de una tabla haciendo el recorrido con un foreach, cargué un par de registros, pero el siguiente código ...
  #1 (permalink)  
Antiguo 02/04/2012, 10:07
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
problema con foreach

Hola!

Estoy tratando de levantar los registros de una tabla haciendo el recorrido con un foreach, cargué un par de registros, pero el siguiente código me devuelve 5 registros iguales tomando como referencia el primero que cargué.

Código PHP:
$conn = new conection();
$rs = new RecordSet($conn);

$sql="SELECT * FROM `novedades`";

$novedades $rs->get_object($sql);

foreach(
$novedades as $novedad)   {   
           
         echo 
$novedades->titulo 
         
echo $novedades->texto
     
    

Les agradezco la ayuda de antemano.
__________________
Saludos!!!
Maru.-
  #2 (permalink)  
Antiguo 02/04/2012, 10:12
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: problema con foreach

Intenta de esta forma

Código PHP:
Ver original
  1. foreach($novedades as $novedad)   {    
  2.            
  3.          echo $novedad->titulo  
  4.          echo $novedad->texto
  5.      
  6.     }
  #3 (permalink)  
Antiguo 02/04/2012, 10:22
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: problema con foreach

Gracias por responder!
No me devuelve nada de ese modo.
__________________
Saludos!!!
Maru.-
  #4 (permalink)  
Antiguo 02/04/2012, 10:42
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: problema con foreach

Perdon mala mia si no te funciona con esto
no sabria que mas decirte.



Código PHP:
Ver original
  1. foreach($rs->get_object($sql) as $novedad)   {    
  2.            
  3.          echo $novedad->titulo;  
  4.          echo $novedad->texto;
  5.      
  6.     }  
  7.  
  8.  
  9. # o quizas
  10.  
  11. while($novedad = $rs->get_object($sql) ){
  12.  
  13.          echo $novedad->titulo;  
  14.          echo $novedad->texto;
  15.  
  16. }
  #5 (permalink)  
Antiguo 02/04/2012, 11:26
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: problema con foreach

no resultó, la verdad no veo que el código que me pasaste esté mal.

El while me devuelve muchisimos registros en realidad es uno solo repetido y solo tengo 2 cargados en la tabla.

Estoy desconsertada...
__________________
Saludos!!!
Maru.-
  #6 (permalink)  
Antiguo 02/04/2012, 12:00
 
Fecha de Ingreso: septiembre-2010
Mensajes: 53
Antigüedad: 13 años, 7 meses
Puntos: 4
Respuesta: problema con foreach

Te hago una pregunta para que el foreach si puedes hacer esto:

$consulta = mysql_query("SELECT * FROM novedades");

while ($array= mysql_fetch_array($consulta)){

echo $array['titulo']+" "+$array['texto'];

}
De esta forma te complicas menos. >_<
  #7 (permalink)  
Antiguo 02/04/2012, 12:04
 
Fecha de Ingreso: septiembre-2010
Mensajes: 53
Antigüedad: 13 años, 7 meses
Puntos: 4
Respuesta: problema con foreach

Que pena con voz jejeje, cambia los signos de mas ( + ) por puntos. estaba con javascript en la cabeza.
  #8 (permalink)  
Antiguo 02/04/2012, 12:09
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: problema con foreach

Pero como haría la conexión a la base? tengo todo hecho con esto:

Código PHP:
$conn = new conection(); 
$rs = new RecordSet($conn); 

$sql="SELECT * FROM `novedades`"

$novedades $rs->get_object($sql); 
__________________
Saludos!!!
Maru.-
  #9 (permalink)  
Antiguo 02/04/2012, 12:16
 
Fecha de Ingreso: septiembre-2010
Mensajes: 53
Antigüedad: 13 años, 7 meses
Puntos: 4
Respuesta: problema con foreach

mmmm.... prueba asi:

Este es la estructura de el foreach:

$novedades = $rs->get_object($sql); // pregunta esto si devuelve el array

foreach($array as $clave=>$valor){
instrucciones;
}

Revisalo bien y si algo manda todo el codigo
  #10 (permalink)  
Antiguo 02/04/2012, 12:30
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: problema con foreach

Esta es la clase con la que trabajo.

Código PHP:
<?php 

# includes
include_once("conf.inc.php"); // aca conecta a la base
include_once(INCLUDES_PATH."messages.php");

class 
RecordSet{
    var 
$conection;
    var 
$fields = array();
    var 
$rs = array();
    var 
$position 0;
    var 
$bof false# flag Begin of File
    
var $eof false# flag End of File
    
    # constructor method of the class. Instanciate a conection object as a class atribute
    
function RecordSet($conn){
        
$this->conection = &$conn;
    }
    
    
# main method, to open, execute and populate a rs with the sql return
    
function open($sql){
        switch(
$this->conection->type){
            case 
"mysql":
                
$this->conection->open_conn();
                
$this->conection->executeQuery($sql);
                
$this->conection->close_conn();
                
# creating the array with the fields names
                
$n_fields mysql_num_fields($this->conection->result);
                for(
$i=0;$i<$n_fields;$i++){
                    
$this->fields[] = mysql_field_name($this->conection->result,$i);
                }
                
                
# creating the current recordset with the current register
                
$temp = array();
                while(
$row mysql_fetch_array($this->conection->result)){
                    for(
$i=0;$i<$n_fields;$i++){
                        
$temp[$this->fields[$i]] = $row[$i];
                        
                    }
                    
# inserting new array into the main array
                    
$this->rs[] = $temp;
                }
                if(
sizeof($this->rs) > 0){
                    
$this->bof true;
                    
$this->eof false;
                    
$this->position 0;
                }else{
                    
$this->bof true;
                    
$this->eof true;
                    
$this->position 0;
                }
                break;
            case 
"mssql":
                
# not implemented yet    
                
break;
            case 
"access":
                
# not implemented yet
                
$this->conection->open_conn();
                
$this->conection->executeQuery($sql);
                
$this->conection->close_conn();
                
# creating the array with the fields names
                
$n_fields odbc_num_fields($this->conection->result);
                for(
$i=0;$i<$n_fields;$i++){
                    
$this->fields[] = odbc_field_name($this->conection->result,$i);
                }
                
                
# creating the current recordset with the current register
                
$temp = array();
                while(
$row odbc_fetch_array($this->conection->result)){
                    for(
$i=0;$i<$n_fields;$i++){
                        
$temp[$this->fields[$i]] = $row[$i];
                        
                    }
                    
# inserting new array into the main array
                    
$this->rs[] = $temp;
                }
                if(
sizeof($this->rs) > 0){
                    
$this->bof true;
                    
$this->eof false;
                    
$this->position 0;
                }else{
                    
$this->bof true;
                    
$this->eof true;
                    
$this->position 0;
                }
                break;
            
# if you have another type of db, just create a new case here.
        
}    
    }
    
# yo
    
function close(){
        
$this->fields = array();
        
$this->rs = array();
        
$this->position 0;
        
$this->bof false;
        
$this->eof false;
    }
    function 
field($campo){
        if(
is_integer($campo)){
            return 
$this->rs[$this->position][$this->fields[$campo]];
        }else{
            return 
$this->rs[$this->position][$campo];
        }
    }
    function 
next(){    
        if (
$this->position >= sizeof($this->rs)){
            
# end of file, so we don´t do anything
            
PrintMessage("Warning : You have reached the end of file. The method next() will stop now.");
        }else{
            
$this->position++;
            if (
$this->bof){
                
$this->bof false;
            }
            if (
$this->position >= sizeof($this->rs)){
                
# end of file, so we set the eof flag
                
$this->eof true;
            }
        }
    }
    function 
previous(){
        if(
$this->bof){
            
# if flag bof is set, don´t do anything
        
}else{
            
$this->position--;
            if (
$this->eof){
                
$this->eof false;
            }
            if(
$this->position 0){
                
$this->bof true;
                
$this->position 0;
            }
        }
    }
    function 
first(){
        
$this->bof true;
        
$this->eof false;
        
$this->position 0;
    }
    function 
last(){
        
$this->eof true;
        
$this->bof false;
        
$this->position sizeof($this->rs) - 1;
    }
    function 
count_registers(){
        return 
sizeof($this->rs);
    }
    
#desde acá lo cambié
    
function get_record_by_ID($table$id$fields "*"){
        
$sql "SELECT $fields FROM $table WHERE id = '$id'";
        
/*$result = $this->sqlordie($sql);
        return mysql_fetch_assoc($result);*/
        
$this->open($sql);
        for(
$j=0;$j<sizeof($this->fields);$j++){
            
$campo=$this->fields[$j];
            
$record->$campo $this->field($j);
        }
        
$this->close();
        return 
$record;
    }
    function 
get_object_list($sql,$open=true){
        if(
$open)
            
$this->open($sql);
        
$object=array();
        for(
$i=0;$i<sizeof($this->rs);$i++){
            for(
$j=0;$j<sizeof($this->fields);$j++){
                
$campo=$this->fields[$j];
                
$object[$i]->$campo $this->rs[$i][$campo];
            }
        }
        if(
$open)
            
$this->close();
        return 
$object;
    }
    function 
get_object($sql){
        
$this->open($sql);
        foreach(
$this->fields as $campo){
            
$record->$campo $this->rs[0][$campo];    
        }
        
$this->close();
        return 
$record;
    }
    function 
login($sql){
        
$this->open($sql);
        foreach(
$this->fields as $campo){
            
$record->$campo $this->rs[0][$campo];    
        }
        
$this->close();
        return !
$this->eof?$record:false;
    }

}
?>

Este es el código con el que se recorre la tabla y deberia devolver los registros, pero solo lee 1 y lo repite 5 veces. En la tabla tengo cargados 2 registros. Además probé con otras tablas y hace lo mismo.

Código PHP:
<?php

$conn 
= new conection();
$rs = new RecordSet($conn);

$sql="SELECT * FROM `novedades`";

$novedades $rs->get_object($sql); 

foreach(
$novedades as $clave=>$valor){

echo 
$novedades->titulo;
echo 
$novedades->texto;

}

?>
__________________
Saludos!!!
Maru.-
  #11 (permalink)  
Antiguo 02/04/2012, 12:40
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: problema con foreach

Prueba esto


Código PHP:
Ver original
  1. $conn = new conection();
  2. $rs = new RecordSet($conn);
  3.  
  4. $sql="SELECT * FROM `novedades`";
  5.  
  6. $novedades = $rs->get_object_list($sql);  
  7.  
  8. foreach($novedades as  $novedad){
  9.  
  10. echo $novedad->titulo;
  11. echo $novedad->texto;
  12.  
  13. }
  #12 (permalink)  
Antiguo 02/04/2012, 12:46
 
Fecha de Ingreso: septiembre-2010
Mensajes: 53
Antigüedad: 13 años, 7 meses
Puntos: 4
Respuesta: problema con foreach

faltan los dos

1. include_once("conf.inc.php"); // aca conecta a la base
2. include_once(INCLUDES_PATH."messages.php");
  #13 (permalink)  
Antiguo 02/04/2012, 12:49
 
Fecha de Ingreso: septiembre-2010
Mensajes: 53
Antigüedad: 13 años, 7 meses
Puntos: 4
Respuesta: problema con foreach

gjx2 no te hace falta un parametro get_object_list($sql,$open=true) creo
  #14 (permalink)  
Antiguo 02/04/2012, 13:04
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: problema con foreach

dehost el valor esta definido por defecto en la funcion
function get_object_list($sql,$open=true){}

@Maru77 Me gustaria que probara de esta forma.
Código PHP:
Ver original
  1. $conn = new conection();
  2. $rs = new RecordSet($conn);
  3.  
  4. $sql="SELECT * FROM `novedades`";
  5.  
  6. $novedades = $rs->get_object_list($sql);
  7.  
  8.  
  9.  foreach($novedades as $field => $key){
  10.            
  11. echo $novedades [$field]->titulo;
  12. echo $novedades [$field]->texto;
  13.  
  14.            
  15.         }
  #15 (permalink)  
Antiguo 02/04/2012, 13:11
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: problema con foreach

gjx2 gracias miles!!! funcionó!!! :)

dehost!!! gracias miles a vos tb por ayudarme!!!

unos genios!!!
__________________
Saludos!!!
Maru.-

Etiquetas: foreach, registro, sql, tabla
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 00:59.