Create mysql table with php variable not working

后端 未结 4 998
生来不讨喜
生来不讨喜 2020-12-07 06:28

I\'m pretty new to php.. and this is probably a stupid mistake... but I have no idea what is going on. I\'m trying to create a table in my database using php. I want to name

相关标签:
4条回答
  • 2020-12-07 07:00

    // Create MySql table with variable

    $tableName = "tb-"."$userEmail";
    $tName="Beta";  
    $createTable = "CREATE TABLE ".$tName." ( UserName varchar(30), UserPassword varchar(30) )" ;
    

    This above syntax works. Apply this example to your code. Please review some error in your concatenation

    0 讨论(0)
  • 2020-12-07 07:01

    Add this after your SQL querys - (It really helps and speeds up error correcting time)

    or die("A MySQL error has occurred.<br />Error: (" . mysql_errno() . ") " . mysql_error());
    

    echos this in your instance:

    A MySQL error has occurred. Error: (1064) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' . ' ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, ' . ' please VARCH' at line 1

    This then indicates to me that the error regards " & '.


    After changing the code to contain single quotes and executing it, there is now no echo.

       <?php
        $tableusername = "philip";
        $create = "CREATE TABLE `".$tableusername."` ("
            . " `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, "
            . " `please` VARCHAR(50) NOT NULL, "
            . " `make` VARCHAR(50) NOT NULL, "
            . " `this` VARCHAR(50) NOT NULL, "
            . " `work` VARCHAR(50) NOT NULL"
            . " )"
            . " ENGINE = myisam;";
    
        mysql_query($create)or die("A MySQL error has occurred.<br />Error: (" . mysql_errno() . ") " . mysql_error());
    
        ?>
    

    Note: Please refer to the MySQLi extension when using SQL embedded in PHP. mysql_* is in a deprecation process.

    Hope this helps.

    0 讨论(0)
  • 2020-12-07 07:16

    you have invalid concatenation of string, use double quotes instead of single quotes.

    $create = "CREATE TABLE `".$tableusername."` ("
        . " `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, "
        . " `please` VARCHAR(50) NOT NULL, "
        . " `make` VARCHAR(50) NOT NULL, "
        . " `this` VARCHAR(50) NOT NULL, "
        . " `work` VARCHAR(50) NOT NULL' "
        . " )"
        . " ENGINE = myisam;";
    
    0 讨论(0)
  • 2020-12-07 07:18

    Use a heredoc:

    $create = <<<SQL
    CREATE TABLE `$tableusername` (
        `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `please` VARCHAR(50) NOT NULL,
        `make` VARCHAR(50) NOT NULL,
        `this` VARCHAR(50) NOT NULL,
        `work` VARCHAR(50) NOT NULL
    )
    ENGINE = myisam;
    SQL;
    

    Notably, you can use string interpolation in a heredoc, but you should really tend toward parametrized queries.

    0 讨论(0)
提交回复
热议问题