19
What are braces for {}
in the following SQL string used in PHP for Mysql?
$sql = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})"
19
What are braces for {}
in the following SQL string used in PHP for Mysql?
$sql = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})"
23
Keys {}
followed by a dollar $
indicate that the complex syntax string interpolation is being used, it serves to invoke methods of an object. It also serves to display the value of a variable (somewhat exaggerated or necessary in a very particular case) this is only valid within double quotes. Static members NAY can be invoked inside double quotes in this 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}
12
Using double-quoted keys allows calling methods to generate a value to be concatenated into the string.
It is valid to remember that it will work only with double quotes.
In this your example you could quietly remove the keys ({}).
9
What are 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 going too deep, it might be more interesting to use Prepared statments and have darlings specific per table instead of a string generic susceptible to SQL Injection.
When PHP finds a $
in a string
in double quotes "
or Heredocs, it will try to interpret the value of the variable.
Because it is a string, we can have characters that blend with the name of our variables or we want to concatenate in the string
a more complex structure, such as the so-called method of an object or a array
for example.
That’s where the keys come in (or braces) {}
. Next to the dollar sign $
they act as an extra delimiter, enabling the use of simple or complex expressions.
Simple Expressions
When we wish to display a position of array
or an object property for example, or even a simple variable where the continuation of 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 keys are omitted, for example $obj->property
, but the use of the keys gives us more control to display exactly what we want.
Complicated Expressions
Key syntax also works with complex expressions, such as multi-dimensional vectors, called methods, 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 will directly display complex structures in PHP.
When I use simple variables, case the string
does not collide with valid variable names, I simply omit keys {}
.
Examples inspired by PHP documentation
Variable variables? What does that mean? Or are they variables (vary in value) or constants (keep the value)
@Jorgeb. php allows the content of a variable to invoke another variable in its code, thus creating a variable that is variable, i.e., that depends on the value of another variable. Follows a example.
@gmsantos congratulations. I would curl up to explain what is variable
Browser other questions tagged php mysql
You are not signed in. Login or sign up in order to post.
http://answall.com/a/4665/91
– rray
In your case it will replace the keys and what is inside them with the value of the variable. If it did not have the keys it would interpret
$fields
as a simplestring
.– Franchesco