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

0

I have some tables that follow a pattern:

  

UserName_SubscribeUserID_User_Semento
  Jefferson_Carlos_1_sementes
  Carlos_Drummond_2_sementes

The name, surname, and ID are stored in the session and retrieved to insert into the database:

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

Then I retrieve the data reported by the user:

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

The query looks like this (or at least I wish it were):

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

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

  

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

If I remove the ':

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

give this error:

  

Notice: Undefined variable: in_name   /storage/emulated/0/www/registra_semente.php on line 23

     

Notice: Undefined variable: LastName_ in   /storage/emulated/0/www/registra_semente.php on line 23

     

Notice: Undefined variable: ID_sementes in   /storage/emulated/0/www/registra_semente.php on line 23

And the query prints like this:

  

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

What do I do?

    
asked by anonymous 08.12.2017 / 13:33

2 answers

1

Try to concatenate the string this way:

$sql = " INSERT INTO $nome"."_"."$sobrenome"."_"."$ID_sementes(ano, mes, titulo, descricao) VALUES ('$ano', '$mes', '$titulo', '$descricao') ";
    
08.12.2017 / 13:38
0

First of all, check the variables that receive the session value before attempting to insert , it will avoid good stress in the future. You can then concatenate the table name:

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