Access direct key

Asked

Viewed 60 times

0

I would like to access the direct key of an array object without having to loop (foreach)

Instead of being like this:

    $nome = "";
    $codigo   = 0;
    $objeto  = DB::select( "SELECT NOME FROM TABELA WHERE CODIGO = ?", array( $codigo ) );
    foreach ( $objeto as $obj ){
        $nome = $obj->nome;
    }
    echo $nome;

I wish I didn’t need foreach

Type

   $nome = $objeto->nome;

But give the following message:

Trying to get Property of non-object

2 answers

2


Your query is wrong:

SELECT NOME WHERE ID = ?

Foul FROM [NOME DA TABELA AQUI], it should be like this:

DB::select( "SELECT NOME FROM minhatabela WHERE ID = ?", $nome );

And for the record, I have no idea if the variable $nome is an array or a string, but random be string you should pass like this:

DB::select('SELECT NOME FROM minhatabela WHERE ID = ?', [ $nome ]);

[edited]

Your query is still wrong:

SELECT CODIGO FROM TABELA WHERE ID=?

In SELECT you only ask for the CODE column, but you want the object ->nome, soon it is necessary to select it too, so:

SELECT codigo, nome FROM TABELA WHERE ID=?

So you don’t have to use the foreach as only will bring a result can use so:

$objeto = DB::select( "SELECT NOME FROM minhatabela WHERE ID = ?", [ $nome ])->first();

echo $objeto[0]->nome;
  • 1

    Blz. Thank you very much, already helped me a lot and already saved some lines of code rsrs

0

When you make a query it returns an array to you, if you do not pass through a foreach it will not bring the attributes. That in the case Attributes is an index of that array!

  • It is. Since it returns an array I would like to access the direct Indice

  • Use find in the query. This will return only one record, and you can access without using foreach.

Browser other questions tagged

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