Question

I have a table name on a variable but it doesn't work when I put it in CREATE TABLE IF NOT EXISTS command or it creates $table called table.

Here is the relevant part of my code:

   $con=mysqli_connect("localhost","user","pwd","DB");
   $usuario=$_SESSION["uid"];
   $tabla=$usuario;
   $tabla.='_partidos';
   echo $tabla; // shows the correct name of the table
   // Check connection
   if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
   //crear tabla
   $create_table =
   'CREATE TABLE IF NOT EXISTS $tabla (
   `ID` int(2) NOT NULL AUTO_INCREMENT,
    `Grupo` varchar(1),
   `Local` char(30),
   PRIMARY KEY (`ID`)
    )
    COLLATE=utf8_spanish_ci';


   $con->query($create_table);
Était-ce utile?

La solution

A variable in a single quoted string will not be parsed. However, it will be parsed in a double-quoted string:

"CREATE TABLE IF NOT EXISTS $tabla (
`ID` int(2) NOT NULL AUTO_INCREMENT,
`Grupo` varchar(1),
`Local` char(30),
PRIMARY KEY (`ID`)
)
COLLATE=utf8_spanish_ci";

http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

Alternatively you can always concatenate it:

"CREATE TABLE IF NOT EXISTS " . $tabla . " (
`ID` int(2) NOT NULL AUTO_INCREMENT,
`Grupo` varchar(1),
`Local` char(30),
PRIMARY KEY (`ID`)
)
COLLATE=utf8_spanish_ci";
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top