moskitos moskitos - 5 months ago 19
SQL Question

variable in SQL INSERT

I'm new in SQL, I would like to know how I can have this code working. Because it doesn't understand that

$lala
and
$lolo
are variable.

$lolo = "ahha";
$lala = "2";
$sql = "INSERT INTO organisation (id_orga, nom) VALUES ";
$sqll = '($lala, $lolo)';

$resultat = $conn->query($sql.$sqll);


so I tried:

$lolo = "ahha";
$lala = "2";
$sql = "INSERT INTO organisation (id_orga, nom) VALUES ";
$sqll = '('.$lala.','. $lolo.')';

$resultat = $conn->query($sql.$sqll);


But both code don't
INSERT
in my
BDD
and also give no error.

M.M M.M
Answer

In PHP the varibles are declared like so:

$lala = "ahah";

When you need to echo or print them you can do the string concatenation like echo 'this is my' . $lala; OR echo "this is my $lala";

This happens because the double quotes allow you to insert the variable without the need to concatenate. So, in your case:

$sqll = '('.$lala.','. $lolo.')';

is correct and is the same as:

$sqll = "($lala, $lolo)";

With the single quotes $sqll = '($lala, $lolo)'; wouldn't work as it would output ($lala, $lolo) and not (2, ahaha)


Note: take a look at pdo which is a better alternative to mysql security-wise