Foros del Web » Programando para Internet » PHP »

Array

Estas en el tema de Array en el foro de PHP en Foros del Web. Hola que tal a todos, quisiera ver si me hechan una mano por favor tengo el sig codigo con una clase que baje pero trato ...
  #1 (permalink)  
Antiguo 05/03/2013, 03:26
 
Fecha de Ingreso: septiembre-2012
Mensajes: 112
Antigüedad: 11 años, 7 meses
Puntos: 1
Array

Hola que tal a todos, quisiera ver si me hechan una mano por favor tengo el sig codigo con una clase que baje pero trato de imprimir un campo especifico y aparece array al imprimir , como puedo imprimir ese arreglo?

Código PHP:
<?php
$insertData 
= array(
    
'usuario' => 'Inserted title',
    
'password' => 'Inserted body'
);

$results $db->get('usuarios');
echo 
$results// contains array of returned rows
?>


Código PHP:
<?php

class MysqliDB {

    
/**
     * Static instance of self
     *
     * @var object
     */
    
protected static $_instance;
    
/**
     * MySQLi instance
     *
     * @var object
     */
    
protected $_mysqli;
    
/**
     * The SQL query to be prepared and executed
     *
     * @var object
     */
    
protected $_query;
    
/**
     * An array that holds where conditions 'fieldname' => 'value'
     *
     * @var array
     */
    
protected $_where = array();
    
/**
     * Dynamic type list for where condition values
     *
     * @var array
     */
    
protected $_whereTypeList;
    
/**
     * Dynamic type list for table data values
     *
     * @var array
     */
    
protected $_paramTypeList;
    
/**
     * Dynamic array that holds a combination of where condition/table data value types and parameter referances
     *
     * @var array
     */
    
protected $_bindParams = array('');        // Create the empty 0 index

    
public function __construct($host$username$password$db) {
        
$this->_mysqli = new mysqli($host$username$password$db
            or die(
'There was a problem connecting to the database');
        
self::$_instance $this;
    }

    
    public static function 
getInstance()
    {
        return 
self::$_instance;
    }

    
    protected function 
reset()
    {
        
$this->_where = array();
        
$this->_bindParams = array('');        // Create the empty 0 index
        
unset($this->_query);
        unset(
$this->_whereTypeList);
        unset(
$this->_paramTypeList);
    }

    
    public function 
rawQuery($query$bindParams NULL
    {
        
$this->_query filter_var($queryFILTER_SANITIZE_STRING);
        
$stmt $this->_prepareQuery();

        if (
gettype($bindParams) === 'array') {
            
$params = array('');        // Create the empty 0 index
            
foreach ($bindParams as $prop => $val) {
                
$params[0] .= $this->_determineType($val);
                
array_push($params$bindParams[$prop]);
            }

                    
call_user_func_array(array($stmt"bind_param"),$this->refValues($params));

        }

        
$stmt->execute();
        
$this->reset();

        
$results $this->_dynamicBindResults($stmt);
        return 
$results;
    }

    
    public function 
query($query$numRows NULL
    {
        
$this->_query filter_var($queryFILTER_SANITIZE_STRING);
        
$stmt $this->_buildQuery($numRows);
        
$stmt->execute();
        
$this->reset();

        
$results $this->_dynamicBindResults($stmt);
        return 
$results;
    }

    
    public function 
get($tableName$numRows NULL
    {

        
$this->_query "SELECT * FROM $tableName where id=1";
        
$stmt $this->_buildQuery($numRows);
        
$stmt->execute();
        
$this->reset();

        
$results $this->_dynamicBindResults($stmt);
        return 
$results;
    }


    public function 
insert($tableName$insertData
    {
        
$this->_query "INSERT into $tableName";
        
$stmt $this->_buildQuery(NULL$insertData);
        
$stmt->execute();
        
$this->reset();

        (
$stmt->affected_rows) ? $result $stmt->insert_id $result false;
        return 
$result;
    }


    public function 
update($tableName$tableData
    {
        
$this->_query "UPDATE $tableName SET ";

        
$stmt $this->_buildQuery(NULL$tableData);
        
$stmt->execute();
        
$this->reset();

        (
$stmt->affected_rows) ? $result true $result false;
        return 
$result;
    }


    public function 
delete($tableName$numRows NULL) {
        
$this->_query "DELETE FROM $tableName";

        
$stmt $this->_buildQuery($numRows);
        
$stmt->execute();
        
$this->reset();

        (
$stmt->affected_rows) ? $result true $result false;
        return 
$result;
    }

    
/**
     * This method allows you to specify multipl (method chaining optional) WHERE statements for SQL queries.
     *
     * @uses $MySqliDb->where('id', 7)->where('title', 'MyTitle');
     *
     * @param string $whereProp The name of the database field.
     * @param mixed $whereValue The value of the database field.
     */
    
public function where($whereProp$whereValue
    {
        
$this->_where[$whereProp] = $whereValue;
        return 
$this;
    }


    
    public function 
getInsertId()
    {
            return 
$this->_mysqli->insert_id;
        }

    
/**
     * Escape harmful characters which might affect a query.
     *
     * @param string $str The string to escape.
     * @return string The escaped string.
    */
    
public function escape $str )
    {
        return 
$this->_mysqli->real_escape_string $str );
    }

    
    protected function 
_determineType($item
    {
        switch (
gettype($item)) {
            case 
'NULL':
            case 
'string':
                return 
's';
                break;

            case 
'integer':
                return 
'i';
                break;

            case 
'blob':
                return 
'b';
                break;

            case 
'double':
                return 
'd';
                break;
        }
    }

    
    protected function 
_buildQuery($numRows NULL$tableData NULL
    {
        (
gettype($tableData) === 'array') ? $hasTableData true $hasTableData false;    
        (!empty(
$this->_where )) ? $hasConditional true $hasConditional false;

        
// Did the user call the "where" method?
        
if (!empty($this->_where)) {

            
// if update data was passed, filter through and create the SQL query, accordingly.
            
if ($hasTableData) {
                
$i 1;
                
$pos strpos($this->_query'UPDATE');
                if ( 
$pos !== false) {
                    foreach (
$tableData as $prop => $value) {
                        
// determines what data type the item is, for binding purposes.
                        
$this->_paramTypeList .= $this->_determineType($value);

                        
// prepares the reset of the SQL query.
                        
($i === count($tableData)) ?
                            
$this->_query .= $prop ' = ?':
                            
$this->_query .= $prop ' = ?, ';

                        
$i++;
                    }
                }
            }

            
//Prepair the where portion of the query
            
$this->_query .= ' WHERE ';    
            
$i 1;
            foreach (
$this->_where as $column => $value) {
                
// Determines what data type the where column is, for binding purposes.
                
$this->_whereTypeList .= $this->_determineType($value);

                
// Prepares the reset of the SQL query.
                
($i === count($this->_where)) ?
                    
$this->_query .= $column ' = ?':
                    
$this->_query .= $column ' = ? AND ';

                
$i++;
            }

        }

        
// Determine if is INSERT query
        
if ($hasTableData) {
            
$pos strpos($this->_query'INSERT');

            if (
$pos !== false) {
                
//is insert statement
                
$keys array_keys($tableData);
                
$values array_values($tableData);
                
$num count($keys);

                
// wrap values in quotes
                
foreach ($values as $key => $val) {
                    
$values[$key] = "'{$val}'";
                    
$this->_paramTypeList .= $this->_determineType($val);
                }

                
$this->_query .= '(' implode($keys', ') . ')';
                
$this->_query .= ' VALUES(';
                while (
$num !== 0) {
                    (
$num !== 1) ? $this->_query .= '?, ' $this->_query .= '?)';
                    
$num--;
                }
            }
        }

        
// Did the user set a limit
        
if (isset($numRows)) {
            
$this->_query .= " LIMIT " . (int) $numRows;
        }

        
// Prepare query
        
$stmt $this->_prepareQuery();

        
// Prepare table data bind parameters
        
if ($hasTableData) {
            
$this->_bindParams[0] = $this->_paramTypeList;
            foreach (
$tableData as $prop => $val) {
                
array_push($this->_bindParams$tableData[$prop]);
            }
        }
        
// Prepare where condition bind parameters
        
if($hasConditional) {
            if (
$this->_where) {
                
$this->_bindParams[0] .= $this->_whereTypeList;
                foreach (
$this->_where as $prop => $val) {
                    
array_push($this->_bindParams$this->_where[$prop]);
                }
            }    
        }
        
// Bind parameters to statment
        
if ($hasTableData || $hasConditional){
            
call_user_func_array(array($stmt"bind_param"),$this->refValues($this->_bindParams));
        }

        return 
$stmt;
    }

    
/**
     * This helper method takes care of prepared statements' "bind_result method
     * , when the number of variables to pass is unknown.
     *
     * @param object $stmt Equal to the prepared statement object.
     * @return array The results of the SQL fetch.
     */
    
protected function _dynamicBindResults($stmt
    {
        
$parameters = array();
        
$results = array();

        
$meta $stmt->result_metadata();

        
$row = array();
        while (
$field $meta->fetch_field()) {
            
$row[$field->name] = NULL;
            
$parameters[] = &$row[$field->name];
        }

        
call_user_func_array(array($stmt"bind_result"),$parameters);

        while (
$stmt->fetch()) {
            
$x = array();
            foreach (
$row as $key => $val) {
                
$x[$key] = $val;
            }
            
array_push($results$x);
        }
        return 
$results;
    }

    protected function 
_prepareQuery() 
    {
        if (!
$stmt $this->_mysqli->prepare($this->_query)) {
            
trigger_error("Problem preparing query ($this->_query) ".$this->_mysqli->errorE_USER_ERROR);
        }
        return 
$stmt;
    }

    public function 
__destruct() 
    {
        
$this->_mysqli->close();
    }

    function 
refValues($arr)
    {
        
//Reference is required for PHP 5.3+
        
if (strnatcmp(phpversion(),'5.3') >= 0) {
                
$refs = array();
                foreach(
$arr as $key => $value)
                        
$refs[$key] = &$arr[$key];
                return 
$refs;
            }
           return 
$arr;
    }

// END class
  #2 (permalink)  
Antiguo 05/03/2013, 07:54
Avatar de h2swider  
Fecha de Ingreso: julio-2007
Ubicación: Ciudad de Buenos Aires
Mensajes: 932
Antigüedad: 16 años, 9 meses
Puntos: 194
Respuesta: Array

Código PHP:
Ver original
  1. var_dump($results);
  2. foreach($results as $result){
  3.   echo $result;
  4. }
__________________
Codifica siempre como si la persona que finalmente mantedra tu código sea un psicópata violento que sabe donde vives
  #3 (permalink)  
Antiguo 05/03/2013, 10:24
 
Fecha de Ingreso: septiembre-2012
Mensajes: 112
Antigüedad: 11 años, 7 meses
Puntos: 1
Respuesta: Array

Cita:
Iniciado por h2swider Ver Mensaje
Código PHP:
Ver original
  1. var_dump($results);
  2. foreach($results as $result){
  3.   echo $result;
  4. }
Gracias h2 pero me refiero a que si solo quiero imprimir el nombre y el id, no todos los datos :/
  #4 (permalink)  
Antiguo 05/03/2013, 17:45
Avatar de carlos_belisario
Colaborador
 
Fecha de Ingreso: abril-2010
Ubicación: Venezuela Maracay Aragua
Mensajes: 3.156
Antigüedad: 14 años
Puntos: 461
Respuesta: Array

pues deberías modificar la consulta para que no te traiga todos los datos, o incluso viendo que estas trabajando con una clase modificar el método que realizas la consulta para poder indicar cuales campos , sino simplemente en ves de hacer el foreach que te indico el amigo hacer esto

Código PHP:
Ver original
  1. echo $results['id'] . " " . $results['nombre'];

pero es cuestión tuya, saludos
__________________
aprende d tus errores e incrementa tu conocimientos
it's not a bug, it's an undocumented feature By @David
php the right way

Etiquetas: mysql, select, sql, usuarios, variables
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 05:15.