Apparently global variable does not store the entire mysqli_query output

Asked

Viewed 84 times

1

I am facing problems when trying to pass the result of mysqli_query by globals, because I can only print on screen data from the first row of the table. Follows the code:

function of class select:

public function select($dataset_name,$entire = True){

    $table = $this->get_table();
    $db_connection = $this->get_db_connection();

    if ($entire == True) {
       $GLOBALS[$dataset_name] = mysqli_query($db_connection,"SELECT * FROM {$table}");
    }else {
      $array = func_get_args();
      unset($array [0]);
      unset($array [1]);
      $columns = implode(",", $array);
      $GLOBALS[$dataset_name] = mysqli_query($db_connection,"SELECT {$columns} FROM {$table}");
    }
  }

function responsible for printing the result (PS: It is unfinished, because missing format the data in a table)

<?php
function list_dataset($dataset_name){
  $num_columns = mysqli_field_count($GLOBALS['connection']) - 1;
  $count = 0;

   while ($array = mysqli_fetch_array($GLOBALS[$dataset_name])) {

    while ($count <= $num_columns ) {
           echo $array[$count].'</br>';

      $count = $count + 1;

    }
  }
}
?>

The result of inserting print_r(array_keys($GLOBALS)); exit; before the function mysqli_fetch_array() is:

 Array ( [0] => _GET [1] => _POST [2] => _COOKIE [3] => _FILES [4] => GLOBALS [5] => db_connection [6] => db_action [7] => mysqli [8] => connection [9] => con [10] => teste [11] => select )

Other information:

  • $GLOBALS['connection'] and $GLOBALS[$dataset_name] coincide, as only a connection was made.
  • The function list_dataset() has to suit any select, otherwise it loses its meaning completely.

  • I call it that:

  $db_connection = new db_connection;
  $db_connection->set_all('localhost','usuário','senha','db');
  $db_connection->open();
  $db_action = new db_action;
  $db_action->set_all('tabela_usuarios');
  $db_action->select('teste');
  $db_action->list_dataset('teste');

Doubt: What am I doing wrong? Am I putting some part of the code in the wrong place?

  • The code is susceptible to inconsistencies. Example, in the same routine has $GLOBALS['connection'] and $GLOBALS[$dataset_name]. If $dataset_name do not match 'connection' may be a cause of the error. But there may be other miscellaneous reasons. To be more objective, try a breakpoint before calling mysqli_field_count(). Do so: print_r(array_keys($GLOBALS)); exit; and put in question the result of this test.

  • @Danielomine ready, I added the result! As for connection conflicts, only has the 'connection' really! Thank you, from now on!

  • It would be good if you show the sample code in which you are calling the functions for testing.

  • Rafael, there is no need to put "SOLVED" in the title of the question. You could post the solution as an answer, but as the question is closed, the most that can be done is you follow the yellow box guidelines so that the question is reopened and then yes post the solution as an answer.

  • @diegofm right, thanks for the warning. I no longer see what to make the question clearer. If I can’t see where I’m going wrong, please let me know. I put the solution in the question, trying to make it as clear as possible and to show that the initial hypothesis was wrong. I don’t want the topic to be useless to the community, I know the error is foolish, but maybe it helps someone with similar error.

  • Or leave the solution comment. If you think the solution can help someone in the future, edit the question to make it clearer. And then try to get it reopened.

  • @Jorgeb. Let’s see if it was clear, then I put in the answers the solution. Thank you!

Show 2 more comments

1 answer

1

There are a lot of things wrong, but I will refrain from commenting on the points outside the main purpose of the question. So let’s get to the point.

The function list_dataset(), modify in this way:

function list_dataset($dataset_name){
    /*
    Note o segundo parâmetro. Defini como MYSQLI_ASSOC. Se preferir, modifique para MYSQLI_NUM. A diferença é que MYSQLI_ASSOC retorna um array associativo, ou seja, a chave de cada array será o nome da coluna da tabela. Com MYSQLI_NUM, os nomes das chaves serão numéricas.

    Consulte: http://php.net/manual/en/mysqli-result.fetch-array.php


    */
    while ($data = mysqli_fetch_array($GLOBALS[$dataset_name], MYSQLI_ASSOC)) {
        /*
        id e parent_id são os nomes das colunas da tabela usada para teste.
        modifique para os nomes das colunas da sua tabela 
        */
        echo $data['id'].' - '.$data['parent_id'].'<br>';
    }
}

That’s enough to go on.

If you want something clearer, see a full test:

class Foo {
    public function get_db_connection(){
        return new mysqli('localhost', "root", '', 'test');
    }
    public function select($dataset_name,$entire = True){

    $table = 'foo'; // "foo" é nome da tabela que usei para teste. Se quiser pode continuar usando o $table = $this->get_table(); conforme está originalmente.

    $db_connection = $this->get_db_connection();

    if ($entire == True) {
       $GLOBALS[$dataset_name] = mysqli_query($db_connection,"SELECT * FROM {$table}");
    }else {
      $array = func_get_args();
      unset($array [0]);
      unset($array [1]);
      $columns = implode(",", $array);
      $GLOBALS[$dataset_name] = mysqli_query($db_connection,"SELECT {$columns} FROM {$table}");
    }
  }

}

function list_dataset($dataset_name){
    /*
    $GLOBALS[$dataset_name]->num_rows retorna a quantidade de registros encontrados.
    Toda aquela doidera com $count é desnecessária e era a causa principal do problema.
    */
    if ($GLOBALS[$dataset_name]->num_rows > 0) {
        while ($data = mysqli_fetch_array($GLOBALS[$dataset_name], MYSQLI_ASSOC)) {
            /*
            id e parent_id são os nomes das colunas da tabela usada para teste.
            modifique para os nomes das colunas da sua tabela 
            */
            echo $data['id'].' - '.$data['parent_id'].'<br>';
        }
    } else {
        echo 'nada encontrado';
    }
}

$c = new Foo();
$c->select('connection', true);
list_dataset('connection');

The table I used for tests:

CREATE TABLE `foo` (
  `id` int(1) NOT NULL,
  `parent_id` int(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `foo` VALUES ('1', '0'), ('2', '1'), ('3', '1'), ('4', '1');
  • 1

    Dear @Danielomine, I found the mistake, I just had to reset the count in each while Father of the counting. Following your suggestion, it really works, but I eliminate the flexibility of the function, which would make it lose sense, because it needs to build tables of any data set that is provided. I’ll post it like it looks, thank you very much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.