Search code examples
phppostgresqlpg-query

creating a table using $_POST parameters


I'm trying to create a table where the table name is a parameter. Is it possible? Like this:

$result = pg_query("CREATE TABLE '$_POST[nome_arquivo_software]' (
    id serial CONSTRAINT pk_'$_POST[nome_arquivo_software]' PRIMARY KEY,
    nome  varchar (80),
    email varchar (80),
    estado varchar (80),
    acessos numeric
)"); 

Solution

  • The table name is not a string literal but an identifier -> change single-quote to double-quotes -> quoted identifier.

    The name of the id field is not pk_+string literal but the whole thing is an identifier -> "pk_...."

    // <--- intensive checks on $_POST[nome_arquivo_software] and $_POST[nome_arquivo_software] here
    $result = pg_query("
        CREATE TABLE \"$_POST[nome_arquivo_software]\" (
        id serial CONSTRAINT \"pk_$_POST[nome_arquivo_software]\" PRIMARY KEY,
        nome  varchar (80),
        email varchar (80),
        estado varchar (80),
        acessos numeric
        )
    ");