Array key filled with an expression from a SQL query

0

What does this mean exactly?

Array
(
[0] => Array
    (
        [MAX(nr_ficha)] => 13
    )
)

I gave a print on the screen and saw that my foreign key (% with%) is getting value 13 (yes, that is the last value in the table), but I do not understand the rest of the code and nor why it does not work.

  

Notice: Array to string conversion in C: \ xampp \ htdocs \ TEST_BANCADA \ Models \ Teste.php on line 16

     

Fatal error: Uncaught PDOException: SQLSTATE [23000]: Integrity constraint violation: 1452 Can not add or update child row: a foreign key constraint fails ( nr_ficha . teste__bancada , CONSTRAINT teste FOREIGN KEY ( nr_ficha_teste ) REFERENCES nr_ficha ( cab_teste )) in C: \ xampp \ htdocs \ TEST_CHANGE \ Models \ Test.php: 18 Stack trace: # 0 C: \ xampp \ htdocs \ TEST_CHANGE \ Models \ Test.php (18 ): PDO-> exec ('INSERT INTO tes ...') # 1 C: \ xampp \ htdocs \ TEST_CHANGE \ Controllers \ processa_testeq.php (30): Test-> register_test (Array, '4', ' 4 ',' 1 ') # 2 {main} thrown in C: \ xampp \ htdocs \ TESTE_BANCADA \ Models \ Teste.php on line 18

The function I used was this:

public function busca_ficha(){
$conexao = Database::getConnection();

$select="SELECT MAX(nr_ficha) FROM cab_teste";

  $busca = $conexao->query($select);
  $nr_ficha = $busca->fetchAll(PDO::FETCH_ASSOC);

  return $nr_ficha;
}

And I called it that:

$ficha = new Cabecalho();
$nr_ficha = $ficha->busca_ficha();

Someone help me, please.

    
asked by anonymous 28.08.2018 / 15:09

1 answer

1

What the database communication engine you used takes the result of the query and places it in an arraay associative (note that even people think PHP is object-oriented, a good part of its library encourages the use of the old associative array and does not use a class. So each element of this array has a key and value. What matters most is the value, but to get there you need the key with a name and this name is the name of the column in the database. In this case you used an expression to get the column and did not give it a name, so it uses the expression as the name, which is what came from the database.

If you want to have a name, put it in query , like this:

SELECT MAX(nr_ficha) AS ULTIMO FROM cab_teste

What will return the result:

Array
(
[0] => Array
    (
        [ULTIMO] => 13
    )
)

But something tells me that it is doing something it should not. If two customers do the same they will receive the same number and if they register something based on it they will be duplicitous.

    
28.08.2018 / 15:14