How to define table that will receive the Insert using PHP variable?

Asked

Viewed 105 times

0

I have some tables that follow a pattern:

NomeUsuário_SobreomeUsuário_IDUsuário_sementes
Jefferson_carlos_1_seeds
Carlos_drummond_2_seeds

the name, surname and ID are stored in the session and I recover to enter in the database:

$ID         = $_SESSION['ID'];
$nome       = $_SESSION['nome'];
$sobrenome  = $_SESSION['sobrenome'];

Then I recover the user informed data:

$ano        = $_POST['ano'];
$mes        = $_POST['mes'];
$titulo     = $_POST['titulo'];
$descricao  = $_POST['descricao'];

The query looks like this (or at least I would like it to be):

$sql = " INSERT INTO '$nome'_'$sobrenome'_'$ID'_sementes(ano, mes, titulo, descricao) VALUES ('$ano', '$mes', '$titulo', '$descricao') ";

I echo the query to see how it looked (obviously it was not executed correctly):

INSERT INTO 'Jefferson''Carlos''1'_seeds(year, month, title, description) VALUES ('2017', 'July', 'example title', 'description example')

If I remove the ' :

$sql = " INSERT INTO $nome_$sobrenome_$ID_sementes(ano, mes, titulo, descricao) VALUES ('$ano', '$mes', '$titulo', '$descricao') ";

makes that mistake:

Notice: Undefined variable: name_in /Storage/Emulated/0/www/registra_seed.php on line 23

Notice: Undefined variable: last name_in /Storage/Emulated/0/www/registra_seed.php on line 23

Notice: Undefined variable: Id_seeds in /Storage/Emulated/0/www/registra_seed.php on line 23

And the query prints like this:

INSERT INTO (year, month, title, description) VALUES ('2017', 'July', 'example title', 'description example')

What I do?

2 answers

2


Try concatenating the string this way:

$sql = " INSERT INTO $nome"."_"."$sobrenome"."_"."$ID_sementes(ano, mes, titulo, descricao) VALUES ('$ano', '$mes', '$titulo', '$descricao') ";
  • Bro, it’s all right, VLW

  • You are welcome, if you can accept the answer, please thank!

  • It took me long to accept because I couldn’t, I said I had to wait... but now it’s all right, see again.

  • No trouble at all.

0

First of all, check the variables that receive the Session value before trying to do the insert, will avoid good stress in the future. Then you can concatenate the table name:

$tabela = $nome."_".$sobrenome."_".$ID_sementes;
$sql = "INSERT INTO '".$tabela."'(ano, mes, titulo, descricao) VALUES ('".$ano."', '".$mes."', '".$titulo."', '".$descricao."')";

Browser other questions tagged

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