What are the {}
keys in the following SQL string used in PHP for MySQL?
$sql = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})"
What are the {}
keys in the following SQL string used in PHP for MySQL?
$sql = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})"
{}
followed by a $
signify that complex syntax string interpolation is being used, it is used to invoke methods of an object. Also it is used to display the value of a variable (a bit exaggerated or necessary in a very particular case) this is all valid inside double quotation marks. Static members NOT can be invoked within double quotation marks in which case it is mandatory to concatenate the strings
<?php
class Pessoa {
const FOO = 'algum valor';
public $nome = 'mario';
public $idade = '20';
public static $planeta = 'terra';
public function getNumeroAleatorioDaSorte(){
return 6;
}
}
$pessoa = new Pessoa();
//exemplos validos:
echo "{$pessoa->getNumeroAleatorioDaSorte()} <br>";
echo "{$pessoa->nome} <br>";
echo "$pessoa->nome <br>";
//exemplos invalidos
echo "$pessoa->getNumeroAleatorioDaSorte()";
//notice: Undefined property Pessoa::$getNumeroAleatorioDaSorte
echo "Pessoa::$planeta";//notice: Undefined variable: planeta e imprime Planeta::
echo "{Pessoa::$planeta}";//notice: Undefined variable: planeta e imprime {Pessoa::}
echo "Pessoa::FOO";//imprime Pessoa::FOO
echo "{Pessoa::FOO}";//imprime {Pessoa::FOO}
Using double-quoted keys allows methods to be invoked to generate a value to be concatenated in the string.
It's worth remembering that it will only work with double quotation marks.
In your example you could quietly remove the keys ({}).
What are the braces {} in the following SQL string used in PHP for MySQL?
In this case for nothing. PHP will interpret the keys and return you something like this:
$tabela = 'user';
$fields = 'nome,email';
$placeholders = "'Jorge','[email protected]'";
$sql = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})"
echo $sql; // INSERT INTO user (nome,email) VALUES ('Jorge','[email protected]')
Not getting too deep, it may be more interesting to use prepared statments > and have specific queries per table instead of a generic string susceptible to SQL Injection .
When PHP finds a $
in a string
in double quotation marks "
or Heredocs , it will try to interpret the value of the variable.
Because it is a string, we can have characters that mix with the names of our variables, or we want to concatenate a more complex structure, such as the method call of an object or a string
, for example.
That's where the keys (or keys) array
come in. Next to the% dollar sign% they act as an extra delimiter, making it possible to use simple or complex expressions.
Simple Expressions
When we want to display a position of {}
or a property of an object for example, or even a simple variable where the continuation of the text influences the variable that is called.
Examples:
<?php
$cerveja = 'Heineken';
// funciona, "'" é um caractere inválido para nome de variáveis
echo "O sabor das '$cerveja's é ótimo";
// não funciona, 's' é um caractere válido para nome de variáveis
// e o php procurará a variável $cervejas
echo "Ele bebeu algumas $cervejas";
echo "Ele bebeu algumas ${cerveja}s"; // funciona
echo "Ele bebeu algumas {$cerveja}s"; // funciona
$fruits = ['morango' => 'vermelho', 'banana' => 'amarelo'];
// Funciona
echo "A banana é {$fruits['banana']}.";
// Funciona, mas o PHP procura por uma constante chamada 'banana' antes,
// gerando um Notice no seu código.
echo "A banana é {$fruits[banana]}."
$obj = new stdClass();
$obj->property = 'molezinha';
echo "Strings em php é {$obj->property}";
Some of these expressions also work if the keys are omitted, such as $
, however the use of the keys gives us more control to display exactly what we want.
Complex Expressions
The key syntax also works with complex expressions, such as multi-dimensional vectors, method calls, functions, or variable variables .
Examples:
<?php
echo "Isto funciona: {$arr['foo'][3]}";
echo "Isto funciona também {$obj->values[3]->name}";
echo "Este é o valor da variável chamada \$name: {${$name}}";
echo "Este é o valor da variável usando o valor retornado da getName(): {${getName()}}";
echo "Este é o valor da variável
usando o valor retornado da \$object->getName(): {${$object>getName()}}";
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
echo $a; //Rertorna Hello
echo "$$a"; //Rertorna World
echo "${$$a}"; //Rertorna Foo - Mais de um nível de variável variável
echo "${$$$a}"; //Rertorna Bar - precisamos das chaves
echo "${$$$$a}"; //Rertorna a
Personally, I always try to include the keys when I'm going to display complex structures directly in PHP.
When I use simple variables, if the array
does not collide with valid variable names, I simply omit the keys $obj->property
.
Examples inspired by PHP documentation