Array data dynamically in PHP [closed]

1

I'm developing a project, in which I need to dynamically retrieve the data that is registered in the database. To read this data, I have this function:

// Lê registros
function DBRead($table, $params = null, $fields = '*'){
    $table  = DB_PREFIX.'_'.$table;
    $params = ($params) ? " {$params}" : null; // Caso não haja parâmetros, remove espaço em branco no final da Query

    $query  = "SELECT {$fields} FROM {$table}{$params}";
    $result = DBExecute($query);

    if (!mysqli_num_rows($result))
        return false;
    else{
        while($res = mysqli_fetch_array($result)){
            $data[] = $res;
        }
        return $data;
    }

}

It returns me a array , with several indexes, and, within those indexes, comes another array , with more indexes. Return example:

array
      0 => 
        array
          0 => string 'Postagem de testes' (length=18)
          'titulo' => string 'Postagem de testes' (length=18)
          1 => string 'Welington Braga' (length=15)
          'autor' => string 'Welington Braga' (length=15)
      1 => 
          array
            0 => string 'Huheuhehue' (length=10)
            'titulo' => string 'Huheuhehue' (length=10)
            1 => string 'Welington Braga' (length=15)
            'autor' => string 'Welington Braga' (length=15)

I do not understand why this function is returning error:

  

"mysql_fetch_array () expects parameter 1 to be resource, given in array":

$postagens = DBRead('postagens', 'WHERE status = 1', 'titulo, autor, conteudo');

while ($dados = mysql_fetch_array($postagens)){
    echo '.$dados['titulo']'; //Imprime os dados que preciso
}
    
asked by anonymous 20.10.2016 / 23:30

2 answers

2
  

I do not understand why this function is returning error " mysql_fetch_array() expects parameter 1 to be resource, array given in":

The function DBRead returns a array with the data you want, it is not necessary to use mysql_fetch_array again.

Do this:

$postagens = DBRead('postagens', 'WHERE status = 1', 'titulo, autor, conteudo');

if ($postagens) {
    foreach ($postagens as $postagem) {
        echo $postagem['titulo'] . "\n";
    }
}
    
20.10.2016 / 23:40
2

Change the read function for this:

// Lê registros
function DBRead($table, $params = null, $fields = '*'){
    $table  = DB_PREFIX.'_'.$table;
    $params = ($params) ? " {$params}" : null; // Caso não haja parâmetros, remove espaço em branco no final da Query

    $query  = "SELECT {$fields} FROM {$table}{$params}";
    $result = DBExecute($query);

    if (mysqli_num_rows($result) <= 0){
        return false;
    }else{
        return $result;
    }

}

And the code that calls the read, swaps it:

$postagens = DBRead('postagens', 'WHERE status = 1', 'titulo, autor, conteudo');

if($postagens != false){
while ($dados = mysqli_fetch_array($postagens)){
    echo $dados['titulo']; //Imprime os dados que preciso
}
}else{
echo 'Nenhum registro foi encontrado';
}
    
20.10.2016 / 23:36